import pygame
import sys
import random
pygame.init()
WIDTH = 800
HEIGHT = 600
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 20
BALL_RADIUS = 10
BRICK_WIDTH = 75
BRICK_HEIGHT = 30
FPS = 60
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打砖块游戏")
clock = pygame.time.Clock()
class Paddle:
def __init__(self):
self.x = WIDTH // 2 - PADDLE_WIDTH // 2
self.y = HEIGHT - 50
self.speed = 8
def move(self, direction):
if direction == "left" and self.x > 0:
self.x -= self.speed
elif direction == "right" and self.x < WIDTH - PADDLE_WIDTH:
self.x += self.speed
def draw(self):
pygame.draw.rect(screen, BLUE, (self.x, self.y, PADDLE_WIDTH, PADDLE_HEIGHT))
class Ball:
def __init__(self):
self.reset()
def reset(self):
self.x = WIDTH // 2
self.y = HEIGHT // 2
self.speed_x = 5 * random.choice([-1, 1])
self.speed_y = -5
self.active = False
def move(self):
if self.active:
self.x += self.speed_x
self.y += self.speed_y
if self.x <= 0 or self.x >= WIDTH:
self.speed_x *= -1
if self.y <= 0:
self.speed_y *= -1
def draw(self):
pygame.draw.circle(screen, RED, (self.x, self.y), BALL_RADIUS)
class Brick:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.active = True
def draw(self):
if self.active:
pygame.draw.rect(screen, self.color, (self.x, self.y, BRICK_WIDTH, BRICK_HEIGHT))
paddle = Paddle()
ball = Ball()
bricks = []
colors = [RED, GREEN, YELLOW]
for row in range(4):
for col in range(WIDTH // BRICK_WIDTH):
brick = Brick(col * BRICK_WIDTH, row * BRICK_HEIGHT + 50, colors[row % len(colors)])
bricks.append(brick)
score = 0
lives = 3
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball.active = True
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
paddle.move("left")
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
paddle.move("right")
ball.move()
if (ball.y + BALL_RADIUS >= paddle.y and
paddle.x <= ball.x <= paddle.x + PADDLE_WIDTH):
ball.speed_y *= -1
hit_pos = (ball.x - paddle.x) / PADDLE_WIDTH
ball.speed_x = 8 * (hit_pos - 0.5)
for brick in bricks:
if brick.active and (
brick.x <= ball.x <= brick.x + BRICK_WIDTH and
brick.y <= ball.y <= brick.y + BRICK_HEIGHT
):
brick.active = False
ball.speed_y *= -1
score += 10
break
if ball.y > HEIGHT:
lives -= 1
if lives == 0:
print("游戏结束!最终得分:", score)
running = False
else:
ball.reset()
paddle.draw()
ball.draw()
for brick in bricks:
brick.draw()
font = pygame.font.Font(None, 36)
text = font.render(f"得分: {score} 生命: {lives}", True, WHITE)
screen.blit(text, (10, 10))
# 胜利条件
if all(not brick.active for brick in bricks):
print("恭喜你赢了!最终得分:", score)
running = False
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()