from microbit import * import random import time # CONSTANT N_X = 5 # nr pixels in x direction N_Y = 5 # nr pixels in x direction ASTEROID_DELAY_MAX = 500 ASTEROID_DELAY_MIN = 100 ASTEROID_DELAY_DELTA = 50 TIME_LEVEL_UPDATE = 2000 GAME_OVER_SLEEP = 2000 IMAGE_GAME_OVER = Image.ANGRY ASTEROID_BRIGHTNESS = 5 PLAYER_BRIGHTNESS = 9 SLEEP_TIME_MS = 20 def game(): # VARIABLES player_x = N_X // 2 asteroid_x = random.randint(0,N_X-1) asteroid_y = 0 asteroid_delay = ASTEROID_DELAY_MAX t0 = time.ticks_ms() time_last_asteroid_update = t0 time_last_level_update = t0 level = 1 # GAME LOOP while True: # get current time t1 = time.ticks_ms() # update level if t1 - time_last_level_update > TIME_LEVEL_UPDATE: if asteroid_delay > ASTEROID_DELAY_MIN: asteroid_delay -= ASTEROID_DELAY_DELTA else: asteroid_delay = ASTEROID_DELAY_MIN level += 1 time_last_level_update = t1 # update asteroid position if t1 - time_last_asteroid_update > asteroid_delay: if asteroid_y < N_Y-1: asteroid_y += 1 else: asteroid_x = random.randint(0,N_X-1) asteroid_y = 0 time_last_asteroid_update = t1 # update player (button presses) if button_a.get_presses() and player_x > 0: player_x -= 1 elif button_b.get_presses() and player_x < N_X-1: player_x += 1 # collision check if asteroid_y == N_Y-1 and asteroid_x == player_x: return level # update display display.clear() display.set_pixel(player_x,N_Y-1,PLAYER_BRIGHTNESS) display.set_pixel(asteroid_x,asteroid_y,ASTEROID_BRIGHTNESS) # short sleep sleep(SLEEP_TIME_MS) def game_over(level): display.show(IMAGE_GAME_OVER) sleep(GAME_OVER_SLEEP) display.scroll("Level: " + str(level)) display.show(IMAGE_GAME_OVER) while True: # restart if button_a.get_presses() or button_b.get_presses(): return while True: level = game() game_over(level)