【Python游戏】打砖块

发布于:2025-02-25 ⋅ 阅读:(14) ⋅ 点赞:(0)
以下是一个使用 Python 的 pygame 库创建的复杂图形界面游戏示例 —— 打砖块游戏。在这个游戏中,玩家需要控制一个挡板来反弹小球,击碎上方的砖块。

在这里插入图片描述

import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 10
BALL_RADIUS = 10
BRICK_WIDTH = 70
BRICK_HEIGHT = 20
BRICK_ROWS = 5
BRICK_COLS = 10

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打砖块游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 挡板类
class Paddle:
    def __init__(self):
        self.x = (WIDTH - PADDLE_WIDTH) // 2
        self.y = HEIGHT - PADDLE_HEIGHT - 10
        self.width = PADDLE_WIDTH
        self.height = PADDLE_HEIGHT
        self.speed = 5

    def move_left(self):
        if self.x > 0:
            self.x -= self.speed

    def move_right(self):
        if self.x < WIDTH - self.width:
            self.x += self.speed

    def draw(self):
        pygame.draw.rect(screen, WHITE, (self.x, self.y, self.width, self.height))

# 球类
class Ball:
    def __init__(self):
        self.x = WIDTH // 2
        self.y = HEIGHT // 2
        self.radius = BALL_RADIUS
        self.dx = random.choice([-2, 2])
        self.dy = -2

    def move(self):
        self.x += self.dx
        self.y += self.dy

        # 边界检测
        if self.x - self.radius < 0 or self.x + self.radius > WIDTH:
            self.dx = -self.dx
        if self.y - self.radius < 0:
            self.dy = -self.dy

    def draw(self):
        pygame.draw.circle(screen, WHITE, (self.x, self.y), self.radius)

    def collide_with_paddle(self, paddle):
        if (
            self.y + self.radius >= paddle.y
            and self.x >= paddle.x
            and self.x <= paddle.x + paddle.width
        ):
            self.dy = -self.dy

    def collide_with_brick(self, brick):
        if (
            self.y - self.radius <= brick.y + brick.height
            and self.y + self.radius >= brick.y
            and self.x >= brick.x
            and self.x <= brick.x + brick.width
        ):
            self.dy = -self.dy
            return True
        return False

# 砖块类
class Brick:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = BRICK_WIDTH
        self.height = BRICK_HEIGHT
        self.color = random.choice([RED, GREEN, BLUE])

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))

# 创建挡板、球和砖块
paddle = Paddle()
ball = Ball()
bricks = []
for row in range(BRICK_ROWS):
    for col in range(BRICK_COLS):
        brick = Brick(col * (BRICK_WIDTH + 10) + 50, row * (BRICK_HEIGHT + 10) + 50)
        bricks.append(brick)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        paddle.move_left()
    if keys[pygame.K_RIGHT]:
        paddle.move_right()

    ball.move()
    ball.collide_with_paddle(paddle)

    # 检测球与砖块的碰撞
    for brick in bricks[:]:
        if ball.collide_with_brick(brick):
            bricks.remove(brick)

    # 绘制挡板、球和砖块
    paddle.draw()
    ball.draw()
    for brick in bricks:
        brick.draw()

    # 检测游戏结束条件
    if ball.y + ball.radius > HEIGHT:
        print("游戏结束,你输了!")
        running = False
    if len(bricks) == 0:
        print("游戏结束,你赢了!")
        running = False

    pygame.display.flip()
    clock.tick(60)

# 退出 Pygame
pygame.quit()

代码说明:

**初始化部分:**初始化 pygame 库,设置游戏窗口的大小和标题,定义一些常量和颜色。

类的定义:
1、Paddle 类:表示玩家控制的挡板,包含移动和绘制方法。
2、Ball 类:表示小球,包含移动、碰撞检测和绘制方法。
3、Brick 类:表示砖块,包含绘制方法。
游戏主循环:
1、处理事件,如退出事件和键盘输入事件。
2、更新挡板、球的位置,检测碰撞。
3、绘制所有游戏元素。
4、检测游戏结束条件,如球出界或所有砖块被击碎。
**退出部分:**游戏结束后,退出 pygame 库。

运行这个代码,你将看到一个打砖块游戏的界面,通过左右箭头键控制挡板移动,反弹小球击碎上方的砖块。