Created
October 14, 2020 07:56
-
-
Save IdrisCytron/3c081aa4f3feca78a09cffee4f13f7c1 to your computer and use it in GitHub Desktop.
Playing Flappy Astronaut Game on Raspberry Pi Sense HAT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# References: | |
# https://projects.raspberrypi.org/en/projects/flappy-astronaut | |
from sense_hat import SenseHat | |
from random import randint | |
from time import sleep | |
sense = SenseHat() | |
RED = (255, 0, 0) | |
BLUE = (0, 0, 255) | |
YELLOW = (255, 255, 0) | |
DELAY_DECREASE = 0.02 | |
def flatten(matrix): | |
flattened = [pixel for row in matrix for pixel in row] | |
return flattened | |
def gen_pipes(matrix): | |
for row in matrix: | |
row[-1] = RED | |
gap = randint(1, 6) | |
matrix[gap][-1] = BLUE | |
matrix[gap - 1][-1] = BLUE | |
matrix[gap + 1][-1] = BLUE | |
return matrix | |
def move_pipes(matrix): | |
for row in matrix: | |
for i in range(7): | |
row[i] = row[i + 1] | |
row[-1] = BLUE | |
return matrix | |
def draw_astronaut(event): | |
global y | |
global x | |
global score | |
global gameOver | |
sense.set_pixel(x, y, BLUE) | |
if event.action == "pressed": | |
if event.direction == "up" and y > 0 and gameOver == False: | |
y -= 1 | |
elif event.direction == "down" and y < 7 and gameOver == False: | |
y += 1 | |
elif event.direction == "right" and x < 7 and gameOver == False: | |
x += 1 | |
elif event.direction == "left" and x > 0 and gameOver == False: | |
x -= 1 | |
elif event.direction == "middle" and score > 0: | |
score = 0 | |
sense.set_pixel(x, y, YELLOW) | |
def check_collision(matrix): | |
global gameOver | |
if matrix[y][x] == RED: | |
gameOver = True | |
return True | |
else: | |
return False | |
x = 0 | |
y = 0 | |
score = 0 | |
gameDelay = 1 | |
gameOver = False | |
sense.stick.direction_any = draw_astronaut | |
while True: | |
matrix = [[BLUE for column in range(8)] for row in range(8)] | |
gameDelay = 1 | |
gameOver = False | |
while True: | |
matrix = gen_pipes(matrix) | |
if check_collision(matrix): | |
sleep(1) | |
break | |
for i in range(3): | |
matrix = move_pipes(matrix) | |
sense.set_pixels(flatten(matrix)) | |
sense.set_pixel(x, y, YELLOW) | |
if check_collision(matrix): | |
sleep(1) | |
break | |
if i == 2: | |
score = score + 1 | |
gameDelay = gameDelay - DELAY_DECREASE | |
if gameDelay < 0.2: | |
gameDelay = 0.2 | |
sleep(gameDelay) | |
while score: | |
sense.show_message("Score: {}".format(score-2), text_colour=YELLOW) | |
# Press joystick middle button to play again |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment