代码如下
import pygame
import sys
# 初始化Pygame
pygame.init()
# 游戏窗口尺寸
WIDTH, HEIGHT = 800, 600
# 颜色定义
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# 创建游戏窗口
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打砖块游戏")
# 定义板和球的初始位置
paddle_x = 350
paddle_y = 550
ball_x = 400
ball_y = 400
# 定义板和球的移动速度
paddle_speed = 15
ball_x_speed = 7
ball_y_speed = 7
# 定义板的尺寸
paddle_width = 100
paddle_height = 10
# 定义球的尺寸
ball_radius = 10
# 初始化砖块
bricks = []
brick_width = 70
brick_height = 20
brick_color = BLUE
brick_spacing = 5
for i in range(8):
for j in range(10):
brick = pygame.Rect(j * (brick_width + brick_spacing), i * (brick_height + brick_spacing), brick_width, brick_height)
bricks.append(brick)
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle_x -= paddle_speed
if keys[pygame.K_RIGHT]:
paddle_x += paddle_speed
# 更新球的位置
ball_x += ball_x_speed
ball_y += ball_y_speed
# 球碰到窗口边界时反弹
if ball_x <= 0 or ball_x >= WIDTH:
ball_x_speed *= -1
if ball_y <= 0:
ball_y_speed *= -1
# 球碰到板时反弹
if ball_y >= paddle_y - ball_radius and paddle_x <= ball_x <= paddle_x + paddle_width:
ball_y_speed *= -1
# 检查球是否碰到砖块
for brick in bricks:
if brick.colliderect(ball_x - ball_radius, ball_y - ball_radius, ball_radius * 2, ball_radius * 2):
ball_y_speed *= -1
bricks.remove(brick)
# 清空屏幕
win.fill(WHITE)
# 绘制板
pygame.draw.rect(win, GREEN, (paddle_x, paddle_y, paddle_width, paddle_height))
# 绘制球
pygame.draw.circle(win, GREEN, (ball_x, ball_y), ball_radius)
# 绘制砖块
for brick in bricks:
pygame.draw.rect(win, brick_color, brick)
# 更新屏幕
pygame.display.flip()
# 控制帧率
pygame.time.delay(20)
# 游戏结束,关闭Pygame
pygame.quit()
sys.exit()