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 synchro_centre = 0 #x-coordinate of synchronous bombing centre point synchro_timer = 0 #keeps time since last bomb drop, to synchronise all bombers 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 UFO = 1 #a simple easy to hit block INVADER = 2 #a classic SPACE INVADERS shape SCORE = 3 #looks like the score SHIELD = 4 #has a shield SYNCHRO = 6 #synchro-bomber 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 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 if variant == Alien.SHIELD: # sprite data is in the UPDATE function for this alien alien.shield = 35 alien.point_value = 20 if variant == Alien.SYNCHRO: alien.spritedata[0:9] = b'\x05\x62\x7A\xEE\xFE\xEE\x7A\x62\x05' alien.point_value = 30 alien.dropped_already = True # When a new line of Synchro Bombers spawns, the timer is set to nearly-ready-to-drop if Alien.synchro_timer < 350: Alien.synchro_timer = 350 # 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 if self.variant == Alien.SHIELD: # Check if the shield is charged, to draw the appropriate sprite if self.shield >= 35: self.spritedata[0:9] = b'\x80\x8E\xAD\xBD\xAF\xBD\xAD\x8E\x80' else: self.spritedata[0:9] = b'\x00\x0E\x2D\x3D\x2F\x3D\x2D\x0E\x00' self.shield += 1 if self.variant == Alien.SYNCHRO: # check if there is something to synchro with if self.x > Alien.synchro_centre - Alien.synchro_timer and self.x < Alien.synchro_centre + Alien.synchro_timer and self.dropped_already == False: self.dropped_already = True Bullet.launch(self.x+4, self.y+6, 1) # when an alien is shot, call this. Returns score to be awarded to the player def shot(self): # If the shot alien has a shield, remove the shield and do nothing else if self.variant == Alien.SHIELD and self.shield >= 35: self.shield = 0 return 0 # 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] # get all aliens of a given variant def get_all_of_variant(variant): return [alien for alien in Alien.pool if alien.variant == variant] # Pre-allocate 60 aliens [Alien() for i in range(0,60)] # Spawning Aliens alien_wave = -1 def spawn_alien_wave(x=0, y=0, alien_type=None): global alien_wave allowed_aliens = [Alien.UFO, Alien.INVADER, Alien.SHIELD, Alien.SYNCHRO] if alien_type is None: alien_wave += 1 # Every third wave is a SCORE wave if alien_wave % 3 == 0: alien_type = Alien.SCORE # Remaining waves are at random, but based on current difficulty. Harder aliens come later else: # randomize a numberfrom 1 to difficulty+1 and spawn the most "expensive" alien that number affords alien_type = max([a for a in allowed_aliens if a <= randrange(difficulty)+1]) if alien_type in [Alien.UFO, Alien.INVADER, Alien.SHIELD, Alien.SYNCHRO]: for i in range(0, 8): Alien.spawn(i*13 +x, y, alien_type) if alien_type == Alien.SCORE: for i in range(0, 6): Alien.spawn(i*9 +23 +x, y, Alien.SCORE) Alien.spawn(0 +x, y, Alien.INVADER) Alien.spawn(11 +x, y, Alien.INVADER) Alien.spawn(80 +x, y, Alien.INVADER) Alien.spawn(91 +x, y, Alien.INVADER) # game variables tank_x = 63 # position of players tank alien_step_delay = 6 # every this many frames, aliens take a step alien_step_timer = 0 # counts the frames for aliens alien_step_direction = 1 # direction (left or right) for aliens alien_armada_offset = 0 # x-position of aliens, tracked so that new rows spawn in-line with exisitng ones alien_descent_rate = 4 # how far the aliens move down, whenever they move down shoot_left_was_released = True shoot_right_was_released = True game_is_not_over_yet = True ammo = 6 timer = 0 difficulty = 1 debug_value = 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, 0, Alien.SCORE) spawn_alien_wave(0, 12, Alien.UFO) # main loop while game_is_not_over_yet: # useful game timer 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 # slow gun recharge: if timer%20 == 0 and ammo < 6: ammo += 1 buzz_ms(1,2) cp_off() cp_on((ammo + 8)%12) # fancy math to select which LED represents ammo count # time-based difficulty increment if timer%700 == 0: difficulty += 1 # at first, the aliens accelerate in x-direction if alien_step_delay > 3: alien_step_delay -= 1 # then, they start moving DOWN faster as well, every third difficulty increase elif difficulty %3 == 0 and alien_descent_rate < 8: alien_descent_rate += 1 # Draw new frame, start from blank 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 stepping. They take a step every couple of frames alien_step_timer += 1 if alien_step_timer >= alien_step_delay: alien_step_timer = 0 # check for direction change, each direction coded separatly switching_direction = False if alien_step_direction > 0: for alien in Alien.get_all_active(): if alien.x > 118: switching_direction = True break if alien_armada_offset > 40: alien_armada_offset = 28 switching_direction = True if alien_step_direction < 0: for alien in Alien.get_all_active(): if alien.x < 1: switching_direction = True break if alien_armada_offset < -12: alien_armada_offset = 0 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 += alien_descent_rate if(alien.y > 58): #aliens reached planet Bell - GAME OVER! game_is_not_over_yet = False buzz_ms(2,4) else: alien_armada_offset += alien_step_direction for alien in Alien.get_all_active(): alien.x += alien_step_direction # If all aliens were shot down, and we have an empty screen: if len(Alien.get_all_active())==0: # reward the player for clearing the screen with some points and a beep game_score += 50 buzz_ms(10,3); # Switch direction, reset offset, spawn a new row! alien_step_direction *= 1 alien_armada_offset = 0 if alien_step_direction >0 else 28 spawn_alien_wave(alien_armada_offset, 0) # Otherwise, if there are aliens on screen, check if there is room for a new row: else: highest_alien = min([alien.y for alien in Alien.get_all_active() if alien.y < 23]) # the alien.y<23 filter is a patch for the odd case where player manages to shoot top level or aliens without clearing the entire screen if highest_alien >= 12: spawn_alien_wave(0 if alien_step_direction > 0 else 28, highest_alien-12) # Every frame, update all aliens that have extra animation/logic for alien in Alien.get_all_active(): alien.update() oled.blit(alien.sprite, alien.x, alien.y, 0) # Synchro-bomber aliens have common logic that also updates once per frame Alien.synchro_timer += 3 if Alien.synchro_timer > 400 and randrange(50) == 1: Alien.synchro_timer = 0 Alien.synchro_centre = randrange(80) + 24 #randomize a mid-point for the synchro-bombing for alien in Alien.get_all_of_variant(Alien.SYNCHRO): alien.dropped_already = False # 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(difficulty), 2, 52, 1) # send updated image to display 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()