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) #global variables. Sue me. game_score = 0 # A somewhat flexible BUZZ function. The buzzer has a fixed frequency, but by pulsing it repeatadly in short pulses, # some variety of sounds can be acheived 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) # This is python, we might as well be classy. An Object class for bullets, to neatly handle the many bullets on screen 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 launch(x, y, velocity): # Step 1: find an unused bullet instance in the bullet pool. # Unused bullets have their velocity set to 0, since its not a useful velocity for bullet in Bullet.pool: if bullet.velocity == 0: break # found one, use the current value of bullet bullet.x = x bullet.y = y bullet.velocity = velocity # returns all active bullets shot by the player (going up, so negative y-speed) def get_all_player_bullets(): return [bullet for bullet in Bullet.pool if bullet.velocity < 0] # returns all active bullets shot by the aliens (going down, so positive y-speed) def get_all_alien_bullets(): return [bullet for bullet in Bullet.pool if bullet.velocity > 0] #pre-allocate 60 bullets statically. No new objects will be allocated at runtime. We ain't savages, we respect our RAM [Bullet() for i in range(0,60)] class Alien: pool = [] #keeps all aliens in one place digitCounter = 5 #for the "score" type alien, to know which ship is which digit of the players score 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): # Step 1: Find an "empty" instance in the pool for alien in Alien.pool: if alien.variant == 0: break # found one, use the current value of 'alien' # Step 2: Update with data for the new Alien alien.x = x alien.y = y alien.variant = variant # Step 3: load the graphics for this specific alien # 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 # Some aliens have their extra logic that needs to be updated every frame def update(self): # INVADER aliens have a 1/300 chance of dropping a bomb every frame! if self.variant == Alien.INVADER: if self.y<48 and randrange(300) == 1: Bullet.launch(self.x+4, self.y+6, 1) # SCORE aliens update their values to always represent the players score 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 an alien is shot, call this. Returns score to be awarded to the player def shot(self): # variant 0 represents an inactive alien, so seting it essentially removes an alien self.variant = 0 return self.point_value # helper function to get a list of all active aliens. Useful to doing a for loop on all aliens 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)] # Setup the waves of aliens alien_wave = -1 alien_waves = [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, alien_type=None): global alien_wave global alien_waves if alien_type is None: alien_wave += 1 alien_type = alien_waves[alien_wave % len(alien_waves)] if alien_type in [Alien.UFO, Alien.INVADER]: for i in range(0, 8): Alien.spawn(i*13, y, alien_type) if alien_type == Alien.SCORE: for i in range(0, 6): Alien.spawn(i*9 + 23, y, Alien.SCORE) Alien.spawn(0, y, Alien.INVADER) Alien.spawn(11, y, Alien.INVADER) Alien.spawn(80, y, Alien.INVADER) Alien.spawn(91, y, Alien.INVADER) # game variables tank_x = 63 alien_step_delay = 8 alien_step_timer = 0 alien_step_direction = 1 alien_armada_offset = 0 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(0, Alien.SCORE) spawn_alien_wave(12, Alien.UFO) # 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(): # switch direction if an alien hits a side wall if alien.x + alien_step_direction> 119 or alien.x + alien_step_direction < 0: switching_direction = True break # BUT, shooting the aliens on the edge can only postpone the advancing to the next line by the width of 1 alien if alien_armada_offset + alien_step_direction > 41 or alien_armada_offset + alien_step_direction < -13: alien_armada_offset -= alien_step_direction * 13 switching_direction = True 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: alien_armada_offset += alien_step_direction 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.get_all_player_bullets(): # 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 # draw the bullet (just 1 pixel) oled.pixel(bullet.x, bullet.y, 1) # process all bombs dropped by aliens for bomb in Bullet.get_all_alien_bullets(): bomb.y += bomb.velocity if(bomb.y > 64): bomb.velocity = 0 continue # Hit detection bomb to player if bomb.y>58 and bomb.x > tank_x-4 and bomb.x < tank_x + 3: game_is_not_over_yet = False # draw the bomb (2x3 rectangle) oled.fill_rect(bomb.x, bomb.y, 2, 3, 1) #debug text #oled.text(str(alien_armada_offset), 2, 52, 1) 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()