98 lines
2.5 KiB
Python
98 lines
2.5 KiB
Python
# pong.py
|
|
import time
|
|
import board_config
|
|
|
|
def run_pong(frames=200):
|
|
display = board_config.display_instance
|
|
if not display:
|
|
print("No display found")
|
|
return
|
|
|
|
width = display.width
|
|
height = display.height
|
|
|
|
# Ball state
|
|
bx, by = width // 2, height // 2
|
|
vx, vy = 6, 4
|
|
ball_size = 6
|
|
|
|
# Paddle state
|
|
pad_w, pad_h = 8, 40
|
|
p1_y = height // 2 - pad_h // 2
|
|
p2_y = height // 2 - pad_h // 2
|
|
|
|
p1_score = 0
|
|
p2_score = 0
|
|
|
|
for _ in range(frames):
|
|
# Update ball
|
|
bx += vx
|
|
by += vy
|
|
|
|
# Bounce top/bottom
|
|
if by <= 0 or by >= height - ball_size:
|
|
vy = -vy
|
|
|
|
# Paddle AI (simple tracking)
|
|
target1 = by - pad_h // 2
|
|
p1_y += int((target1 - p1_y) * 0.15)
|
|
p1_y = max(0, min(height - pad_h, p1_y))
|
|
|
|
target2 = by - pad_h // 2
|
|
p2_y += int((target2 - p2_y) * 0.15)
|
|
p2_y = max(0, min(height - pad_h, p2_y))
|
|
|
|
# Bounce left paddle
|
|
if vx < 0 and bx <= 20 and bx >= 10:
|
|
if by + ball_size >= p1_y and by <= p1_y + pad_h:
|
|
vx = -vx
|
|
vy += int((by - (p1_y + pad_h // 2)) * 0.2)
|
|
|
|
# Bounce right paddle
|
|
if vx > 0 and bx >= width - 20 - pad_w and bx <= width - 10:
|
|
if by + ball_size >= p2_y and by <= p2_y + pad_h:
|
|
vx = -vx
|
|
vy += int((by - (p2_y + pad_h // 2)) * 0.2)
|
|
|
|
# Score left
|
|
if bx < 0:
|
|
p2_score += 1
|
|
bx, by = width // 2, height // 2
|
|
vx = 6
|
|
vy = 4
|
|
|
|
# Score right
|
|
if bx > width:
|
|
p1_score += 1
|
|
bx, by = width // 2, height // 2
|
|
vx = -6
|
|
vy = -4
|
|
|
|
# Draw everything
|
|
display.clear(0)
|
|
|
|
# Center line
|
|
for y in range(0, height, 15):
|
|
display.fill_rect(width // 2 - 1, y, 2, 8, 1)
|
|
|
|
# Paddles
|
|
display.fill_rect(10, p1_y, pad_w, pad_h, 1)
|
|
display.fill_rect(width - 20, p2_y, pad_w, pad_h, 1)
|
|
|
|
# Ball
|
|
display.fill_rect(bx, by, ball_size, ball_size, 1)
|
|
|
|
# Score
|
|
display.text(str(p1_score), width // 2 - 30, 10, 1)
|
|
display.text(str(p2_score), width // 2 + 20, 10, 1)
|
|
|
|
display.show()
|
|
time.sleep_ms(30)
|
|
|
|
# Clear screen at the end
|
|
display.clear(0)
|
|
display.show()
|
|
|
|
# Run the animation
|
|
run_pong()
|