| from microbit import * | |
| # quickly create a level of two rows, with pixels set to 0 hits and 1 hits | |
| blocks = [[1 - i for j in range(5) ] for i in range(2)] | |
| ball = [2, 3] | |
| ball_direction = [1,-1] | |
| paddle = [2, 4] | |
| previous_game_time = running_time() | |
| ball_timing = running_time() | |
| game_time = running_time() | |
| running = True | |
| # Set up the board. | |
| def setup_line(line, value): | |
| for i in range(5): | |
| display.set_pixel(i, line, value) | |
| def draw_blocks(): | |
| for x in range(5): | |
| for y in range(2): | |
| display.set_pixel(x, y, blocks[y][x]) | |
| def draw_ball(): | |
| display.set_pixel(ball[0], ball[1], 4) | |
| def draw_paddle(): | |
| display.set_pixel(paddle[0], paddle[1], 5) | |
| display.set_pixel(paddle[0]+1, paddle[1], 5) | |
| def move_ball(): | |
| global ball | |
| ball = next_position() | |
| def next_position(): | |
| return [ball[0] + ball_direction[0], ball[1] + ball_direction[1]] | |
| def check_ball_collisions(): | |
| global running | |
| if ball[1] == 4: | |
| # Has the ball hit the bottom. Stop the ball and Game over | |
| ball_direction[0] = 0 | |
| ball_direction[1] = 0 | |
| running = False | |
| return | |
| # Has the ball hit the paddle. | |
| if ball[1] == 3 and (ball[0] == paddle[0] or ball[0] == paddle[0] + 1): | |
| # 3, so it doesn't embed in the paddle | |
| ball_direction[1] = -ball_direction[1] | |
| if ball[1] == 3 and (ball[0] == paddle[0] - 1 or ball[0] == paddle[0] + 2): | |
| # ball hit odd angle of paddle.. note might reflect it back up one day | |
| ball_direction[0] = -ball_direction[0] | |
| # Has the ball hit wall (left, right, top). We can still hit something | |
| if ball[0] == 0 or ball[0] == 4: | |
| ball_direction[0] = -ball_direction[0] | |
| if ball[1] == 0: | |
| ball_direction[1] = -ball_direction[1] | |
| if ball[1] <= 2: | |
| # Blocks can only be in top two rows in this game | |
| if blocks[ball[1] - 1][ball[0]] > 0: | |
| # We hit a block, take a life from the block | |
| blocks[ball[1] -1][ball[0]] = blocks[ball[1] -1][ball[0]] -1 | |
| # send the ball back down. | |
| ball_direction[1] = -ball_direction[1] | |
| flipflop = 1 | |
| while running: | |
| display.clear() | |
| # get input | |
| if button_a.is_pressed() and paddle[0] >= 1: | |
| paddle[0] = paddle[0] - 1 | |
| if button_b.is_pressed() and paddle[0] < 3: | |
| paddle[0] = paddle[0] + 1 | |
| if game_time - ball_timing > 500: | |
| flipflop = flipflop ^ 1 | |
| display.set_pixel(4, 4, flipflop) | |
| move_ball() | |
| check_ball_collisions() | |
| ball_timing = game_time | |
| # draw state | |
| draw_blocks() | |
| draw_ball() | |
| draw_paddle() | |
| previous_game_time = game_time | |
| game_time = running_time() | |
| sleep(100) | |
| display.clear() | |
| display.scroll('Game Over') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment