from machine import Pin, I2C
import ssd1306
import time
import random
import framebuf
# OLED setup
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Button
button = Pin(15, Pin.IN, Pin.PULL_UP)
# ---------------- BIRD ----------------
bird_bitmap = bytearray([
0b00110000,
0b01111000,
0b11111100,
0b01110000,
0b00100000,
0b00000000,
0b00000000,
0b00000000
])
bird = framebuf.FrameBuffer(bird_bitmap, 8, 8, framebuf.MONO_HLSB)
# ---------------- VARIABLES ----------------
bird_y = 30
velocity = 0
gravity = 1
jump = -4
pipe_x = 128
gap_y = random.randint(15, 40)
gap_size = 20
score = 0
high_score = 0
game_over = False
game_started = False
def reset_game():
global bird_y, velocity, pipe_x, gap_y, score, game_over
bird_y = 30
velocity = 0
pipe_x = 128
gap_y = random.randint(15, 40)
score = 0
game_over = False
# ---------------- MAIN LOOP ----------------
while True:
# -------- START SCREEN --------
if not game_started:
oled.fill(0)
oled.text("FLAPPY BIRD", 10, 20)
oled.text("Press Btn", 20, 40)
oled.show()
if button.value() == 0:
game_started = True
time.sleep(0.3)
# -------- GAME RUNNING --------
elif not game_over:
# Jump
if button.value() == 0:
velocity = jump
# Gravity
velocity += gravity
bird_y += velocity
# Pipes
pipe_x -= 2
if pipe_x < -10:
pipe_x = 128
gap_y = random.randint(15, 40)
score += 1
# Collision
if bird_y <= 0 or bird_y >= 56:
game_over = True
if pipe_x < 18 and pipe_x > 2:
if bird_y < gap_y or bird_y > gap_y + gap_size:
game_over = True
# Draw
oled.fill(0)
oled.blit(bird, 10, int(bird_y))
oled.fill_rect(pipe_x, 0, 10, gap_y, 1)
oled.fill_rect(pipe_x, gap_y + gap_size, 10, 64, 1)
oled.text("S:{}".format(score), 0, 0)
oled.text("H:{}".format(high_score), 70, 0)
oled.show()
time.sleep(0.05)
# -------- GAME OVER --------
else:
if score > high_score:
high_score = score
oled.fill(0)
oled.text("GAME OVER", 20, 15)
oled.text("Score: {}".format(score), 20, 30)
oled.text("High: {}".format(high_score), 20, 45)
oled.text("Press Btn", 15, 55)
oled.show()
if button.value() == 0:
reset_game()
game_started = False # go back to start screen
time.sleep(0.5)