from machine import Pin, I2C
import ssd1306
from time import sleep
import random
# OLED setup
i2c = I2C(0, scl=Pin(21), sda=Pin(20))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Buttons for paddle control
btn_up = Pin(14, Pin.IN, Pin.PULL_UP)
btn_down = Pin(15, Pin.IN, Pin.PULL_UP)
# Paddle variables
paddle_y = 20
paddle_height = 16
# Ball variables
ball_x = 64
ball_y = 32
ball_dx = 3 # faster speed
ball_dy = 3
score = 0
game_over = False
def draw_game():
oled.fill(0)
# Paddle
oled.fill_rect(5, paddle_y, 3, paddle_height, 1)
# Ball
oled.fill_rect(ball_x, ball_y, 3, 3, 1)
# Score
oled.text("Score: {}".format(score), 40, 0)
oled.show()
def move_paddle():
global paddle_y
if not btn_up.value() and paddle_y > 0: # button pressed = 0
paddle_y -= 4 # move paddle faster
if not btn_down.value() and paddle_y < (64 - paddle_height):
paddle_y += 4
def move_ball():
global ball_x, ball_y, ball_dx, ball_dy, score, game_over
ball_x += ball_dx
ball_y += ball_dy
# Bounce top/bottom
if ball_y <= 0 or ball_y >= 61:
ball_dy = -ball_dy
# Bounce paddle
if ball_x <= 8 and paddle_y <= ball_y <= paddle_y + paddle_height:
ball_dx = -ball_dx
score += 1
# Speed up a little every time
if ball_dx > 0:
ball_dx += 1
else:
ball_dx -= 1
if ball_dy > 0:
ball_dy += 1
else:
ball_dy -= 1
# Missed paddle
if ball_x < 0:
game_over = True
# Bounce right wall
if ball_x >= 125:
ball_dx = -ball_dx
def show_game_over():
oled.fill(0)
oled.text("GAME OVER!", 20, 20)
oled.text("Score: {}".format(score), 20, 40)
oled.show()
# Main loop
while True:
if game_over:
show_game_over()
break
move_paddle()
move_ball()
draw_game()
sleep(0.02) # smaller delay = faster game