commit d6e020edb8db693a5caa70e47fdb83739a986ffe Author: Marek Baczynski Date: Fri Nov 27 18:46:21 2026 +0100 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/how_to_play.jpg b/how_to_play.jpg new file mode 100644 index 0000000..c2ada81 Binary files /dev/null and b/how_to_play.jpg differ diff --git a/invader_types.jpg b/invader_types.jpg new file mode 100644 index 0000000..76d4a6d Binary files /dev/null and b/invader_types.jpg differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..f82f3d4 --- /dev/null +++ b/main.py @@ -0,0 +1,405 @@ +from ssd1306 import SSD1306_I2C +import framebuf +from machine import Pin, I2C, ADC +from time import sleep, sleep_ms +from math import sin, cos, pi +from random import randrange + +i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)#Grove - OLED Display 0.96" (SSD1306) +oled = SSD1306_I2C(128, 64, i2c) + +buzz = Pin(0, Pin.OUT) + +tmp36 = ADC(Pin(26)) +light = ADC(Pin(27)) +sw1 = ADC(Pin(28)) +sw2 = ADC(Pin(29)) + +# pin numbers for charlieplexing +cpin = [1, 2, 3, 4] +cled = [[0,1], [0,2], [0,3], [1,0], [1,2], [1,3], [2,0], [2,1], [2,3], [3,0], [3,1], [3,2]] + +def cp_on(led_nr): # allow led_nr between 0 and 11 + if led_nr >= 0 and led_nr < 12: + cp0 = Pin(cpin[cled[led_nr][0]], Pin.OUT) + cp0.value(0) + cp1 = Pin(cpin[cled[led_nr][1]], Pin.OUT) + cp1.value(1) + +def cp_off(): + for i in range(4): + cpoff = Pin(cpin[i], Pin.OPEN_DRAIN) + +BTN_SW1 = 4; +BTN_SW2 = 1 +BTN_SW3 = 8; +BTN_SW4 = 2; +def read_buttons(): + sw1_val = sw1.read_u16() + sw2_val = sw2.read_u16() + sw1_8 = int(sw1_val / 256) + if sw1_8 > 160: + sw1_t = 0 + elif sw1_8 > 135: + sw1_t = 4 + elif sw1_8 > 105: + sw1_t = 8 + elif sw1_8 > 80: + sw1_t = 12 + else: + sw1_t = 0 + sw2_8 = int(sw2_val / 256) + if sw2_8 > 160: + sw2_t = 0 + elif sw2_8 > 135: + sw2_t = 1 + elif sw2_8 > 105: + sw2_t = 2 + elif sw2_8 > 80: + sw2_t = 3 + else: + sw2_t = 0 + return(sw1_t + sw2_t) + +## ------------- BELL INVADERS START HERE ---------------- + +#global variables. Sue me. +game_score = 0 + +def buzz_ms(time, repeat=1): + while True: + buzz.value(1) + sleep_ms(time) + buzz.value(0) + repeat -= 1 + if repeat == 0: + break + sleep_ms(time) + +class Bullet: + pool = [] #keeps all bullets in one place + def __init__(self): + self.x = 0 + self.y = 0 + self.velocity = 0 + Bullet.pool.append(self) + + def pick_from_pool(): + for bullet in Bullet.pool: + if bullet.velocity == 0: + return bullet + return None + + def launch(x, y, velocity): + bullet = Bullet.pick_from_pool() + if bullet == None: + return #no available bullets. Pls wait + bullet.x = x + bullet.y = y + bullet.velocity = velocity + +class Bomb: + pool = [] #keeps all bombs in one place + def __init__(self): + self.x = 0 + self.y = 0 + self.velocity = 0 + Bomb.pool.append(self) + + def pick_from_pool(): + for bomb in Bomb.pool: + if bomb.velocity == 0: + return bomb + return None + + def launch(x, y, velocity): + bomb = Bomb.pick_from_pool() + if bomb == None: + return #no available bullets. Pls wait + bomb.x = x + bomb.y = y + bomb.velocity = velocity + +#pre-allocate 8 bullets statically. No new objects will be allocated at runtime. We ain't savages, we respect our RAM +[Bullet() for i in range(0,8)] +# same for bombs but 32 +[Bomb() for i in range(0, 32)] + +class Alien: + pool = [] #keeps all aliens in one place + digitCounter = 5 + + def __init__(self): + self.x = 0 + self.y = 0 + self.variant = 0 + self.spritedata = bytearray(9) + self.sprite = framebuf.FrameBuffer(self.spritedata, 9, 8, framebuf.MONO_VLSB) + Alien.pool.append(self) + + # Alien types + BIGBOX = 1 #max legal size of alien + UFO = 2 #a simple easy to hit block + INVADER = 3 #a classic SPACE INVADERS shape + SCORE = 4 #looks like the score + + def spawn(x, y, variant): + alien = Alien.pick_from_pool() + if alien == None: + return #too many aliens! skip this one + alien.x = x + alien.y = y + alien.variant = variant + + # alien.spritedata[0:9] = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00' #empty template + + if variant == Alien.BIGBOX: + alien.sprite.fill_rect(0, 0, 9, 8, 1) + + if variant == Alien.UFO: + alien.spritedata[0:9] = b'\x20\x70\x70\x7C\x74\x7C\x70\x70\x20' + alien.point_value = 5 + + if variant == Alien.INVADER: + alien.spritedata[0:9] = b'\x78\x18\x7F\xB6\x3C\xB6\x7F\x18\x78' + alien.point_value = 10 + + if variant == Alien.SCORE: + alien.digit = Alien.digitCounter + Alien.digitCounter -= 1 + if Alien.digitCounter < 0: + Alien.digitCounter = 5 + alien.sprite.fill(0) + alien.sprite.text(str(alien.digit), 0, 0, 1) + alien.point_value = 0 + + def update(self): + if self.variant == Alien.INVADER: + # INVADER aliens have a 1/300 chance of dropping a bomb! + if randrange(300) == 1: + Bomb.launch(self.x+4, self.y+6, 1) + + if self.variant == Alien.SCORE: + global game_score + self.sprite.fill(0) + digit = game_score // 10**self.digit % 10 + self.sprite.text(str(digit), 0, 0, 1) + self.point_value = digit*10 + 5 + + # when shot, call this. Returns score to be awarded to the player + def shot(self): + self.variant = 0 + return self.point_value + + def pick_from_pool(): + for alien in Alien.pool: + if alien.variant == 0: + return alien + return None + + def get_all_active(): + return [alien for alien in Alien.pool if alien.variant is not 0] + +#pre-allocate 60 aliens +[Alien() for i in range(0,60)] + +alien_wave = -1 +alien_waves = [Alien.UFO, Alien.SCORE, Alien.INVADER, Alien.UFO, Alien.INVADER, Alien.SCORE, Alien.INVADER, Alien.INVADER, Alien.SCORE, Alien.UFO, Alien.INVADER, Alien.INVADER, Alien.SCORE] + +def spawn_alien_wave(y=0): + global alien_wave + global alien_waves + alien_wave += 1 + next_wave = alien_waves[alien_wave % len(alien_waves)] + if next_wave in [Alien.UFO, Alien.INVADER]: + for i in range(0, 8): + Alien.spawn(i*13 + 1, y, next_wave) + + if next_wave == Alien.SCORE: + for i in range(0, 6): + Alien.spawn(i*9 + 24, y, next_wave) + Alien.spawn(1, y, Alien.INVADER) + Alien.spawn(12, y, Alien.INVADER) + Alien.spawn(81, y, Alien.INVADER) + Alien.spawn(92, y, Alien.INVADER) + +# game variables +tank_x = 63 +alien_step_delay = 8 +alien_step_timer = 0 +alien_step_direction = 1 +game_progress = 0 +shoot_left_was_released = True +shoot_right_was_released = True +game_is_not_over_yet = True +ammo = 6 +timer = 0 + +# Draw START screen +oled.fill(0) +oled.fill_rect(10, 12, 98, 36, 0) +oled.rect(9, 11, 100, 38, 1) +oled.text("BELLINVADERS", 11, 17, 1) +oled.text("PLAY", 40, 32, 1) +oled.show() + +# wait for keypress to start +while read_buttons() == 0: + pass + +# spawn the first 2 waves +spawn_alien_wave(12) +spawn_alien_wave(0) + +# main loop +while game_is_not_over_yet: + timer += 1 + + # Button logic + if read_buttons() & BTN_SW3: + if tank_x > 2: + tank_x -= 1 + + if read_buttons() & BTN_SW4: + if tank_x < 125: + tank_x += 1 + + if read_buttons() & BTN_SW1: + if shoot_left_was_released and ammo > 0: + Bullet.launch(tank_x-1, 60, -2) + shoot_left_was_released = False + ammo -= 1 + buzz_ms(1,2) + else: + shoot_left_was_released = True + + if read_buttons() & BTN_SW2 and ammo > 0: + if shoot_right_was_released: + Bullet.launch(tank_x+1, 60, -2) + shoot_right_was_released = False + ammo -= 1 + buzz_ms(2,2) + else: + shoot_right_was_released = True + + # Check if all aliens dead, if so, advance the game + if len(Alien.get_all_active()) == 0: + spawn_alien_wave() + alien_step_direction = 1 + buzz_ms(2,4) + game_progress = (game_progress//2+2)*2 #don't ask + + # slow gun recharge: + if timer%20 == 0 and ammo < 6: + ammo += 1 + buzz_ms(1,2) + + cp_off() + cp_on((ammo + 8)%12) # don't ask + + # Draw new frame + oled.fill(0); + + # draw the tank + oled.pixel(tank_x-1, 60, 1) + oled.pixel(tank_x+1, 60, 1) + oled.hline(tank_x-2, 61, 5, 1) + oled.fill_rect(tank_x-3, 62, 7, 2, 1) + + #process aliens + alien_step_timer += 1 + if alien_step_timer >= alien_step_delay: + alien_step_timer = 0 + switching_direction = False + for alien in Alien.get_all_active(): + if alien.x + alien_step_direction> 118 or alien.x + alien_step_direction < 1: + switching_direction = True + break + + if switching_direction: + # aliens turn around and go down by one line + alien_step_direction *= -1 + for alien in Alien.get_all_active(): + alien.y += 6 + if(alien.y > 58): #aliens reached planet Bell - GAME OVER! + game_is_not_over_yet = False + buzz_ms(2,4) + + # check for other game progression effects + game_progress += 1 + # every other line, we spawn new aliens + if game_progress % 2 == 0: + spawn_alien_wave() + # complex math to gradually increase game speed + if (12-game_progress)**2 > alien_step_delay and alien_step_delay > 3: + alien_step_delay -= 1 + + else: + for alien in Alien.get_all_active(): + alien.x += alien_step_direction + + + for alien in Alien.get_all_active(): + alien.update() + oled.blit(alien.sprite, alien.x, alien.y, 0) + + # check for collision between aliens and player tank + # only four points on the tank are checked - the corners + for alien in Alien.get_all_active(): + if any([alien.sprite.pixel(tank_x-3-alien.x, 60-alien.y), alien.sprite.pixel(tank_x+3-alien.x, 60-alien.y), alien.sprite.pixel(tank_x-3-alien.x, 62-alien.y), alien.sprite.pixel(tank_x+3-alien.x, 62-alien.y)]): + game_is_not_over_yet = False + + # Process all bullets (move and hit-detect) + for bullet in Bullet.pool: + if bullet.velocity is not 0: + #move and check for collisions + bullet.y += bullet.velocity + if bullet.y < 0: + bullet.velocity = 0 + continue + + # Hit detection bullet to alien + for alien in Alien.get_all_active(): + if alien.sprite.pixel(bullet.x-alien.x, bullet.y-alien.y) == 1: + game_score += alien.shot() + bullet.velocity = 0 + buzz_ms(10) + continue + + oled.pixel(bullet.x, bullet.y, 1) + + # process all bombs dropped by aliens + for bomb in Bomb.pool: + if bomb.velocity == 0: + continue + + bomb.y += bomb.velocity + if(bomb.y > 64): + bomb.velocity = 0 + continue + + # Hit detection bomb to player + if bomb.y>60 and bomb.x > tank_x-3 and bomb.x < tank_x + 2: + game_is_not_over_yet = False + + oled.fill_rect(bomb.x, bomb.y, 2, 3, 1) + + + # debug info + #debugvalue = game_score + #oled.text(str(debugvalue), 4, 50) + + oled.show() + +# outside of the loop, this is the GAME OVER SCREEN +buzz_ms(2, 6) +sleep_ms(5) +buzz_ms(3, 6) +sleep_ms(5) +buzz_ms(4, 6) + +oled.fill_rect(20, 12, 88, 36, 0) +oled.rect(19, 11, 90, 38, 1) +oled.text("GAME OVER", 25, 17, 1) +oled.text(str(game_score) + "pts", 25, 32, 1) +oled.show() \ No newline at end of file diff --git a/poster.jpg b/poster.jpg new file mode 100644 index 0000000..e5d936b Binary files /dev/null and b/poster.jpg differ diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..f00d41c --- /dev/null +++ b/readme.md @@ -0,0 +1,21 @@ +# BellInvaders +Defend planet Bell from the evil alien invaders in the BellBoy exclusive BELLINVADERS +![image](poster.jpg) + +# How to play +![image](how_to_play.jpg) + +![image](invader_types.jpg) + +# How to install +* Replace the main.py of the BellBoy with the one from this repo +* Make sure you also have the SSD1306.py on your BellBoy + +# Hardware requirements +BellBoy with working: +* SSD1306 128x64 OLED +* All four keys +* top 6 LEDs +* Buzzer + +For best experience, use a [BellBoyErgoGrip](https://git.elab.kth.se/marek/BellBoyErgoGrip) ergonomic grip! \ No newline at end of file diff --git a/ssd1306.py b/ssd1306.py new file mode 100644 index 0000000..e0fe7ec --- /dev/null +++ b/ssd1306.py @@ -0,0 +1,155 @@ +# MicroPython SSD1306 OLED driver, I2C and SPI interfaces + +from micropython import const +import framebuf + + +# register definitions +SET_CONTRAST = const(0x81) +SET_ENTIRE_ON = const(0xA4) +SET_NORM_INV = const(0xA6) +SET_DISP = const(0xAE) +SET_MEM_ADDR = const(0x20) +SET_COL_ADDR = const(0x21) +SET_PAGE_ADDR = const(0x22) +SET_DISP_START_LINE = const(0x40) +SET_SEG_REMAP = const(0xA0) +SET_MUX_RATIO = const(0xA8) +SET_COM_OUT_DIR = const(0xC0) +SET_DISP_OFFSET = const(0xD3) +SET_COM_PIN_CFG = const(0xDA) +SET_DISP_CLK_DIV = const(0xD5) +SET_PRECHARGE = const(0xD9) +SET_VCOM_DESEL = const(0xDB) +SET_CHARGE_PUMP = const(0x8D) + +# Subclassing FrameBuffer provides support for graphics primitives +# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html +class SSD1306(framebuf.FrameBuffer): + def __init__(self, width, height, external_vcc): + self.width = width + self.height = height + self.external_vcc = external_vcc + self.pages = self.height // 8 + self.buffer = bytearray(self.pages * self.width) + super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB) + self.init_display() + + def init_display(self): + for cmd in ( + SET_DISP | 0x00, # off + # address setting + SET_MEM_ADDR, + 0x00, # horizontal + # resolution and layout + SET_DISP_START_LINE | 0x00, + SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0 + SET_MUX_RATIO, + self.height - 1, + SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0 + SET_DISP_OFFSET, + 0x00, + SET_COM_PIN_CFG, + 0x02 if self.width > 2 * self.height else 0x12, + # timing and driving scheme + SET_DISP_CLK_DIV, + 0x80, + SET_PRECHARGE, + 0x22 if self.external_vcc else 0xF1, + SET_VCOM_DESEL, + 0x30, # 0.83*Vcc + # display + SET_CONTRAST, + 0xFF, # maximum + SET_ENTIRE_ON, # output follows RAM contents + SET_NORM_INV, # not inverted + # charge pump + SET_CHARGE_PUMP, + 0x10 if self.external_vcc else 0x14, + SET_DISP | 0x01, + ): # on + self.write_cmd(cmd) + self.fill(0) + self.show() + + def poweroff(self): + self.write_cmd(SET_DISP | 0x00) + + def poweron(self): + self.write_cmd(SET_DISP | 0x01) + + def contrast(self, contrast): + self.write_cmd(SET_CONTRAST) + self.write_cmd(contrast) + + def invert(self, invert): + self.write_cmd(SET_NORM_INV | (invert & 1)) + + def show(self): + x0 = 0 + x1 = self.width - 1 + if self.width == 64: + # displays with width of 64 pixels are shifted by 32 + x0 += 32 + x1 += 32 + self.write_cmd(SET_COL_ADDR) + self.write_cmd(x0) + self.write_cmd(x1) + self.write_cmd(SET_PAGE_ADDR) + self.write_cmd(0) + self.write_cmd(self.pages - 1) + self.write_data(self.buffer) + + +class SSD1306_I2C(SSD1306): + def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False): + self.i2c = i2c + self.addr = addr + self.temp = bytearray(2) + self.write_list = [b"\x40", None] # Co=0, D/C#=1 + super().__init__(width, height, external_vcc) + + def write_cmd(self, cmd): + self.temp[0] = 0x80 # Co=1, D/C#=0 + self.temp[1] = cmd + self.i2c.writeto(self.addr, self.temp) + + def write_data(self, buf): + self.write_list[1] = buf + self.i2c.writevto(self.addr, self.write_list) + + +class SSD1306_SPI(SSD1306): + def __init__(self, width, height, spi, dc, res, cs, external_vcc=False): + self.rate = 10 * 1024 * 1024 + dc.init(dc.OUT, value=0) + res.init(res.OUT, value=0) + cs.init(cs.OUT, value=1) + self.spi = spi + self.dc = dc + self.res = res + self.cs = cs + import time + + self.res(1) + time.sleep_ms(1) + self.res(0) + time.sleep_ms(10) + self.res(1) + super().__init__(width, height, external_vcc) + + def write_cmd(self, cmd): + self.spi.init(baudrate=self.rate, polarity=0, phase=0) + self.cs(1) + self.dc(0) + self.cs(0) + self.spi.write(bytearray([cmd])) + self.cs(1) + + def write_data(self, buf): + self.spi.init(baudrate=self.rate, polarity=0, phase=0) + self.cs(1) + self.dc(1) + self.cs(0) + self.spi.write(buf) + self.cs(1) \ No newline at end of file