一个简单的敲砖块游戏

练手用pygame做了一个简单到简陋的敲砖块游戏:

import math
from abc import ABCMeta, abstractmethod
import pygame


class GameObject(object, metaclass=ABCMeta):
    """游戏对象类"""
    def __init__(self, x=0, y=0, color=(0, 0, 0)):
        self._x = x
        self._y = y
        self._color = color

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, y):
        self._y = y

    @property
    def color(self):
        return self._color

    @abstractmethod
    def draw(self, screen):
        pass


class Border(GameObject):
    """边框"""
    def __init__(self, x, y, width, height, color=(255, 255, 255)):
        super().__init__(x, y, color)
        self._height = height
        self._width = width

    @property
    def height(self):
        return self._height

    @property
    def width(self):
        return self._width

    def draw(self, screen):
        pygame.draw.rect(screen, self._color, (self._x, self._y, self._width, self._height), 5)


class Brick(GameObject):
    """砖块"""
    def __init__(self, x, y, width=56, height=30, color=(125, 150, 160)):
        super().__init__(x, y, color)
        self._height = height
        self._width = width

    @property
    def height(self):
        return self._height

    @property
    def width(self):
        return self._width

    def draw(self, screen):
        pygame.draw.rect(screen, self._color,
                         (self._x, self._y, self._width, self._height), 0)
        pygame.draw.rect(screen, (50, 50, 100),
                         (self._x, self._y, self._width, self._height), 1)


class Wall(GameObject):
    """砖墙"""
    def __init__(self):
        super().__init__()
        self._bricks = []
        for i in range(5):
            for j in range(10):
                brick = Brick(60 + 56 * j, 80 + 30 * i)
                self._bricks.append(brick)

    @property
    def bricks(self):
        return self._bricks

    @bricks.setter
    def bricks(self, bricks):
        self._bricks = bricks

    def draw(self, screen):
        for brick in self._bricks:
            brick.draw(screen)


class Ball(GameObject):
    """球"""
    def __init__(self, x=340, y=605, radius=7, sx=2, sy=-4, color=(255, 255, 255)):
        GameObject.__init__(self, x, y, color)
        self._radius = radius
        self._sx = sx
        self._sy = sy

    @property
    def sx(self):
        return self._sx

    @sx.setter
    def sx(self, sx):
        self._sx = sx

    @property
    def sy(self):
        return self._sy

    @sy.setter
    def sy(self, sy):
        self._sy = sy

    @property
    def radius(self):
        return self._radius

    def move(self):
        """球的移动"""
        self._x += self._sx
        self._y += self._sy
        if (self._x + self._radius >= 640 and self._sx > 0) or \
                (self._x - self._radius <= 40 and self._sx < 0):
            self._sx = -self._sx
        if self._y - self._radius <= 40 and self._sy < 0:
            self._sy = -self._sy

    def draw(self, screen):
        pygame.draw.circle(screen, self._color,
                           (self._x, self._y), self._radius, 0)

    def distance(self, other):
        return math.sqrt((self._x - other.x) ** 2 +
                         (self._y - other.y) ** 2)

    def collide_detective(self, brick):
        """球与砖块的碰撞检测"""
        cornerx_1 = brick.x
        cornery_1 = brick.y
        cornerx_2 = brick.x + brick.width
        cornery_2 = brick.y
        cornerx_3 = brick.x + brick.width
        cornery_3 = brick.y + brick.height
        cornerx_4 = brick.x
        cornery_4 = brick.y + brick.height
        #  将一块砖分成8个部分分别判断
        if brick.y <= self._y <= (brick.y + brick.height) and \
                (brick.x - self._radius) <= self._x < brick.x:
            return 1
        elif brick.x <= self._x <= (brick.x + brick.width) and \
                (brick.y - self._radius) <= self.y < brick.y:
            return 2
        elif brick.y <= self._y <= (brick.y + brick.height) and \
                (brick.x + brick.width) < self._x <= \
                (brick.x + brick.width + self._radius):
            return 3
        elif brick.x <= self._x <= (brick.x + brick.width) and \
                (brick.y + brick.height) < self._y <= \
                (brick.y + brick.height + self._radius):
            return 4
        elif ((self._x - cornerx_1) ** 2 + (self._y - cornery_1) ** 2) \
                <= (self._radius ** 2):
            return 5
        elif ((self._x - cornerx_2) ** 2 + (self._y - cornery_2) ** 2) \
                <= (self._radius ** 2):
            return 6
        elif ((self._x - cornerx_3) ** 2 + (self._y - cornery_3) ** 2) \
                <= (self._radius ** 2):
            return 7
        elif ((self._x - cornerx_4) ** 2 + (self._y - cornery_4) ** 2) \
                <= (self._radius ** 2):
            return 8
        else:
            return 0


class Board(GameObject):
    """反弹板"""
    def __init__(self, x=290, y=615, width=100, height=5, sx=0, color=(30, 150, 170)):
        super().__init__(x, y, color)
        self._width = width
        self._height = height
        self._sx = sx

    @property
    def sx(self):
        return self._sx

    @sx.setter
    def sx(self, sx):
        self._sx = sx

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, width):
        self._width = width

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, height):
        self._height = height

    def draw(self, screen):
        pygame.draw.rect(screen, self._color,
                         (self._x, self._y, self._width, self._height), 0)

    def move(self):
        self._x += self._sx


def main():

    def collide(brick):
        """碰撞反弹"""
        num = ball.collide_detective(brick)
        if num != 0:
            wall.bricks.remove(brick)
        if num == 1 or num == 3:
            ball.sx = -ball.sx
        elif num == 2 or num == 4:
            ball.sy = -ball.sy
        elif num == 5 or num == 6 or num == 7 or num == 8:
            ball.sx = -ball.sx
            ball.sy = -ball.sy

    def refresh():
        """刷新窗口"""
        screen.fill((0, 0, 0))
        wall.draw(screen)
        ball.draw(screen)
        board.draw(screen)
        border.draw(screen)
        pygame.display.flip()

    def handle_key_event(key_event):
        """处理按键事件"""
        nonlocal start_move
        key = key_event
        if key == pygame.K_s:
            start_move = True
        elif key == pygame.K_SPACE:
            pass
        elif key == pygame.K_F2:
            start_move = False
            reset_game()

    def reset_game():
        """重置游戏"""
        nonlocal ball, wall, board, game_over
        wall = Wall()
        ball = Ball()
        board = Board()
        pygame.event.clear()
        game_over = False

    clock = pygame.time.Clock()
    wall = Wall()
    ball = Ball()
    board = Board()
    border = Border(40, 40, 600, 600)
    pygame.init()
    screen = pygame.display.set_mode([680, 680])
    pygame.display.set_caption('')
    start_move = False
    running = True
    game_over = False
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                handle_key_event(event.key)
        if not game_over:
            pressed_keys = pygame.key.get_pressed()  # 操作反弹板
            if pressed_keys[pygame.K_d] and board.x + board.width < 640:
                board.sx = 10
                board.move()
            elif pressed_keys[pygame.K_a] and board.x > 40:
                board.sx = -10
                board.move()
            if start_move:
                ball.move()
            for brick in wall.bricks:
                collide(brick)
            if board.x - ball.radius <= ball.x <= board.x + board.width + ball.radius \
                    and board.y - ball.radius <= ball.y < board.y:  # 球与板的碰撞反弹
                ball.sy = -ball.sy
                if (pressed_keys[pygame.K_d] or pressed_keys[pygame.K_a]) and \
                        (abs(ball.sx) <= 5 or ball.sx / board.sx < 0):
                    ball.sx += board.sx // 10  # 板给球的x方向的速度
            refresh()
            if ball.y > 680:
                my_font = pygame.font.SysFont('', 80)
                text = my_font.render("Game Over", 1, (255, 10, 10))
                screen.blit(text, (200, 300))
                pygame.display.flip()
                game_over = True
            if not wall.bricks:
                my_font = pygame.font.SysFont('', 80)
                text = my_font.render("You Win", 1, (255, 10, 10))
                screen.blit(text, (200, 300))
                pygame.display.flip()
                game_over = True
        clock.tick(60)
    pygame.quit()


if __name__ == '__main__':
    main()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以的!我可以给你一些简单的步骤: 1. 创建一个窗口,用于显示游戏 2. 加载图像,用于显示砖块和挡板 3. 创建一个循环,用于更新游戏内容 4. 在循环中,检查键盘输入,以控制挡板的移动 5. 检查砖块是否和挡板相撞,如果相撞,就移动砖块的方向 6. 检查砖块是否落地,如果落地,就将砖块从屏幕上移除 7. 如果所有砖块都被移除,就表示游戏结束,显示胜利消息 ### 回答2: 打砖块是一种经典的游戏,我们可以使用Python来实现一个简单的版本。首先,我们需要使用pygame库来创建游戏窗口和处理游戏逻辑。 在游戏开始时,我们要绘制一个滑块和一排砖块。滑块可以通过键盘的左右方向键来控制,用于接住从顶部下落的小球。砖块可以用二维数组表示,其中每个元素代表一个砖块的状态(是否被破坏)。 游戏的主循环中,我们需要检测用户的输入,并根据输入来移动滑块。同时,我们还需要不断地更新小球的位置,并检测其与滑块和砖块的碰撞。如果小球与滑块碰撞,则反弹回去;如果小球与砖块碰撞,则砖块被破坏并得分增加。 当所有砖块都被破坏或小球触底时,游戏结束。我们可以在游戏结束后显示得分,并等待用户选择重新开始或退出游戏。 总结起来,用Python一个打砖块游戏需要完成以下几个步骤: 1. 导入pygame库和其他必要的模块。 2. 初始化游戏窗口和游戏变量。 3. 绘制游戏元素,包括滑块和砖块。 4. 创建游戏主循环,处理用户的输入和更新游戏逻辑。 5. 创建碰撞检测函数,处理小球与滑块和砖块的碰撞。 6. 处理游戏结束时的逻辑和用户选择。 以上是一个简单打砖块游戏实现的大致步骤,通过使用Python和pygame库,我们可以实现一个简单但有趣的游戏。当然,我们还可以进一步优化和添加更多的功能来提升游戏的可玩性。 ### 回答3: 打砖块游戏是一款经典的游戏,我们可以使用Python编写一个简单的版本。 首先,我们需要导入pygame库。你可以使用pip命令在终端上安装: ``` pip install pygame ``` 然后,创建一个游戏窗口,并初始化pygame的库: ```python import pygame from pygame.locals import * SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("打砖块游戏") ``` 接下来,我们可以使用pygame的图形绘制功能来创建砖块、球和挡板: ```python BRICK_WIDTH = 60 BRICK_HEIGHT = 20 BRICK_COLOR = (255, 0, 0) PADDLE_WIDTH = 100 PADDLE_HEIGHT = 10 PADDLE_COLOR = (0, 0, 255) BALL_RADIUS = 10 BALL_COLOR = (0, 255, 0) brick = pygame.Rect(0, 0, BRICK_WIDTH, BRICK_HEIGHT) paddle = pygame.Rect(0, SCREEN_HEIGHT - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT) ball = pygame.Rect(SCREEN_WIDTH // 2 - BALL_RADIUS, SCREEN_HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS, BALL_RADIUS) def draw(): screen.fill((0, 0, 0)) pygame.draw.rect(screen, BRICK_COLOR, brick) pygame.draw.rect(screen, PADDLE_COLOR, paddle) pygame.draw.circle(screen, BALL_COLOR, ball.center, BALL_RADIUS) pygame.display.update() ``` 在游戏循环中,我们需要实现挡板的移动和球的运动逻辑: ```python PADDLE_SPEED = 5 BALL_SPEED_X = 3 BALL_SPEED_Y = 3 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[K_LEFT]: paddle.left -= PADDLE_SPEED if keys[K_RIGHT]: paddle.left += PADDLE_SPEED ball.left += BALL_SPEED_X ball.top += BALL_SPEED_Y if ball.left <= 0 or ball.right >= SCREEN_WIDTH: BALL_SPEED_X *= -1 if ball.top <= 0 or ball.colliderect(paddle): BALL_SPEED_Y *= -1 draw() ``` 以上就是简单打砖块游戏,运行代码后你将看到一个可以左右移动的挡板和一个可以弹跳的球。你可以根据自己的需求,进一步添加砖块、计分等功能来完善游戏

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值