from microbit import * import random import time # CONSTANTS 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 = 3000 ASTEROID_BRIGHTNESS = 5 PLAYER_BRIGHTNESS = 9 SLEEP_TIME_MS = 20 GAME_OVER_TIME = 1000 IMAGE_GAME_OVER = Image.ANGRY # VARIABLES player_x = N_X // 2 asteroid_x = random.randint(0,N_X-1) asteroid_y = 0 asteroid_delay = ASTEROID_DELAY_MAX game_over = False level = 1 time_last_asteroid_update = time.ticks_ms() time_last_level_update = time.ticks_ms() # 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: # speed up game asteroid_delay -= ASTEROID_DELAY_DELTA else: # avoid negative times 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: game_over = True # update display display.clear() if game_over: display.show(IMAGE_GAME_OVER) sleep(GAME_OVER_TIME) # wait before can reset display.scroll("Level: " + str(level)) display.show(Image.ANGRY) while True: # reset game (not great because is copy paste from above) if button_a.get_presses() or button_b.get_presses(): player_x = N_X // 2 asteroid_x = random.randint(0,N_X-1) asteroid_y = 0 asteroid_delay = ASTEROID_DELAY_MAX game_over = False time_last_asteroid_update = time.ticks_ms() time_last_level_update = time.ticks_ms() break else: 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)