综合练习:接球游戏
52.8 综合练习:接球游戏
挡板左右移动接住下落的小球(简化版)。
接球简化版
扩展:加重新开始、音效。
# ========================================
# 示例:挡板接球
# 说明:左右键移动 paddle,球下落
# ========================================
import pygame
pygame.init()
W, H = 400, 400
screen = pygame.display.set_mode((W, H))
px = W // 2
bx, by = W//2, 50
vy = 4
clock = pygame.time.Clock()
score = 0
running = True
while running:
for e in pygame.event.get():
if e.type == pygame.QUIT: running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: px = max(40, px - 6)
if keys[pygame.K_RIGHT]: px = min(W-40, px + 6)
by += vy
if by > H - 30:
if abs(bx - px) < 50:
score += 1
by = 50
else:
running = False
screen.fill((20, 20, 40))
pygame.draw.rect(screen, (100, 200, 255), (px-40, H-25, 80, 10))
pygame.draw.circle(screen, (255, 220, 0), (bx, int(by)), 12)
font = pygame.font.Font(None, 28)
screen.blit(font.render(f'Score:{score}', True, (255,255,255)), (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()