代码如下
import pygame
import sys
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.quit()
sys.exit()