pygame第7课——实现简单一个打砖块游戏

专栏导读

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

之前的课程

pygame课程课程名称
第1课:pygame安装
链接https://blog.csdn.net/weixin_42636075/article/details/130512509
第2课:pygame加载图片
链接https://blog.csdn.net/weixin_42636075/article/details/130562606
第3课:画图小程序
链接https://blog.csdn.net/weixin_42636075/article/details/130801371
第4课:颜色监测(迷宫小游戏)
链接https://blog.csdn.net/weixin_42636075/article/details/130804267
第5课:音乐播放器
链接https://blog.csdn.net/weixin_42636075/article/details/130811078
第6课:贪吃蛇小游戏
链接https://blog.csdn.net/weixin_42636075/article/details/132341210
第7课:打砖块游戏
链接https://blog.csdn.net/weixin_42636075/article/details/137239564

1、小球类设计

  • 1、小球的大小(球的半径)、初始坐标、速度

self.radius,半径
self.pos = [x,y],初始坐标
self.velocity = [2, -2],速度self.velocity[0]--x轴移动,self.velocity[1]--y轴移动,
  • 2、小球绘制方法

pygame.draw.circle(窗口对象, 颜色(RGB-元组), 初始位置(列表[x,y]), 半径(整数))
  • 3、小球的移动方法(x轴、y轴的移动)

如果小球的x轴坐标 < 小球半径,或者,小球的x轴坐标 > 屏幕的宽度就设置方向相反
同理y轴
# 球体类
class Ball:
    def __init__(self, radius):
        self.radius = radius
        self.pos = [screen_width // 2, screen_height - 20 - radius]
        self.velocity = [2, -2]

    def draw(self, surface):
        pygame.draw.circle(surface, WHITE, self.pos, self.radius)

    def update(self):
        self.pos[0] += self.velocity[0]
        self.pos[1] += self.velocity[1]
        # print(self.pos)
        # 碰到墙壁反弹
        # print(screen_width - self.radius)
        if self.pos[0] < self.radius or self.pos[0] > (screen_width - self.radius):
            # self.pos[0] = -self.pos[0]
            self.velocity[0] *= -1
            # if self.pos[0] < 0:
            #     self.pos[0] = -self.pos[0]

        # print(screen_height - self.radius)
        if self.pos[1] <= self.radius or self.pos[1] > (screen_height - self.radius):
            self.velocity[1] *= -1
            # if self.pos[1] < 0:
            #     self.pos[1] = -self.pos[1]

2、挡板类的设计

  • 1、挡板的宽x高

self.width = width
self.height = height
  • 2、挡板的初始坐标

self.pos = [screen_width // 2 - width // 2, screen_height - 20]
  • 3、挡板的速度,因为只在x轴运动,所以y轴为0

self.velocity = [-5, 0]
  • 4、挡板的绘制,x1,y1矩形左上角坐标点, x2,y2矩形右下角坐标点

pygame.draw.rect((窗口对象, 颜色(RGB-元组), (x1,y1, x2,y2), 0, 0)
  • 5、挡板的移动

接收键盘的事件(左键和右键),设置限制不可以超出屏幕外面
# 挡板类
class Paddle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pos = [screen_width // 2 - width // 2, screen_height - 20]
        self.velocity = [-5, 0]

    def draw(self, surface):
        pygame.draw.rect(surface, WHITE, (self.pos[0], self.pos[1], self.width, self.height), 0, 0)

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.pos[0] > 0:
            self.pos[0] += self.velocity[0]
        if keys[pygame.K_RIGHT] and self.pos[0] < screen_width - self.width:
            self.pos[0] -= self.velocity[0]

3、砖块类

  • 1、砖块的摆放坐标,宽、高、 颜色

  • 2、绘制砖块

pygame.draw.rect(surface, self.color, self.rect)
class Brick:
    def __init__(self, x, y, width, height, color):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect)

4、砖块与小球的边界碰撞检测

def check_collision(ball, brick):
    # 检查球与砖块的左右边界碰撞
    if (brick.rect.x - ball.radius <= ball.pos[0] <= brick.rect.x + brick.rect.width + ball.radius) and (
            brick.rect.y <= ball.pos[1] <= brick.rect.y + brick.rect.height):
        return 1  # 返回1表示碰撞发生在砖块的左右边界
    # 检查球与砖块的上下边界碰撞
    if (brick.rect.y - ball.radius <= ball.pos[1] <= brick.rect.y + brick.rect.height + ball.radius) and (
            brick.rect.x <= ball.pos[0] <= brick.rect.x + brick.rect.width):
        return 2  # 返回2表示碰撞发生在砖块的上下边界

    return 0

5、检测到碰撞,删除砖块,改变运动方向

def update_bricks(ball, bricks):
    score = 0
    for brick in bricks[:]:
        if check_collision(ball, brick) == 1:
            # 处理碰撞效果,比如删除砖块或改变球的方向
            bricks.remove(brick)
            ball.velocity[0] *= -1
            score += 10
            break
        elif check_collision(ball, brick) == 2:
            bricks.remove(brick)
            ball.velocity[1] *= -1
            score += 10
            break
            # 可能还需要更新分数或其他游戏状态
    return score

完整版代码

import math
import random

import pygame
import sys


# 球体类
class Ball:
    def __init__(self, radius):
        self.radius = radius
        self.pos = [screen_width // 2, screen_height - 20 - radius]
        self.velocity = [2, -2]

    def draw(self, surface):
        pygame.draw.circle(surface, WHITE, self.pos, self.radius)

    def update(self):
        self.pos[0] += self.velocity[0]
        self.pos[1] += self.velocity[1]
        # print(self.pos)
        # 碰到墙壁反弹
        # print(screen_width - self.radius)
        if self.pos[0] < self.radius or self.pos[0] > (screen_width - self.radius):
            # self.pos[0] = -self.pos[0]
            self.velocity[0] *= -1
            # if self.pos[0] < 0:
            #     self.pos[0] = -self.pos[0]

        # print(screen_height - self.radius)
        if self.pos[1] <= self.radius or self.pos[1] > (screen_height - self.radius):
            self.velocity[1] *= -1
            # if self.pos[1] < 0:
            #     self.pos[1] = -self.pos[1]


# 挡板类
class Paddle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pos = [screen_width // 2 - width // 2, screen_height - 20]
        self.velocity = [-5, 0]

    def draw(self, surface):
        pygame.draw.rect(surface, WHITE, (self.pos[0], self.pos[1], self.width, self.height), 0, 0)

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.pos[0] > 0:
            self.pos[0] += self.velocity[0]
        if keys[pygame.K_RIGHT] and self.pos[0] < screen_width - self.width:
            self.pos[0] -= self.velocity[0]




class Brick:
    def __init__(self, x, y, width, height, color):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect)


def check_collision(ball, brick):
    # 检查球与砖块的左右边界碰撞
    if (brick.rect.x - ball.radius <= ball.pos[0] <= brick.rect.x + brick.rect.width + ball.radius) and (
            brick.rect.y <= ball.pos[1] <= brick.rect.y + brick.rect.height):
        return 1  # 返回1表示碰撞发生在砖块的左右边界
    # 检查球与砖块的上下边界碰撞
    if (brick.rect.y - ball.radius <= ball.pos[1] <= brick.rect.y + brick.rect.height + ball.radius) and (
            brick.rect.x <= ball.pos[0] <= brick.rect.x + brick.rect.width):
        return 2  # 返回2表示碰撞发生在砖块的上下边界

    return 0


def update_bricks(ball, bricks):
    score = 0
    for brick in bricks[:]:
        if check_collision(ball, brick) == 1:
            # 处理碰撞效果,比如删除砖块或改变球的方向
            bricks.remove(brick)
            ball.velocity[0] *= -1
            score += 10
            break
        elif check_collision(ball, brick) == 2:
            bricks.remove(brick)
            ball.velocity[1] *= -1
            score += 10
            break
            # 可能还需要更新分数或其他游戏状态
    return score




def create_explosion(brick):
    # 创建一个表示爆炸效果的对象或动画
    pass


def update_explosions(explosions, bricks):
    for explosion in explosions[:]:
        # 更新爆炸效果
        if explosion.is_finished():
            explosions.remove(explosion)
        # 如果爆炸与砖块碰撞,移除砖块
        if explosion.intersects(brick):
            bricks.remove(brick)


if __name__ == '__main__':
    # 初始化Pygame
    pygame.init()

    # 设置屏幕大小
    screen_width, screen_height = 640, 480
    screen = pygame.display.set_mode((screen_width, screen_height))

    # 设置标题和时钟
    pygame.display.set_caption('Bounce Game')
    clock = pygame.time.Clock()

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

    # 创建球体和挡板
    ball = Ball(10)
    paddle = Paddle(80, 10)

    # 创建砖块
    bricks = []
    for x in range(0, screen_width, 80):  # 假设每个砖块宽度为80像素
        for y in range(0, screen_height // 4, 20):  # 假设每个砖块高度为40像素
            brick = Brick(x + 2, y + 2, 80 - 2, 20 - 2, (255, 255, 255))  # 白色砖块
            bricks.append(brick)

    # 得分变量
    score = 0

    # 游戏主循环
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 更新球体和挡板的位置
        ball.update()
        paddle.update()

        # print(ball.pos, paddle.pos)
        # 检测球体是否碰到挡板
        if ball.pos[1] + ball.radius > paddle.pos[1]:
            if ball.pos[0] < paddle.pos[0] or ball.pos[0] > paddle.pos[0] + paddle.width:
                # running = False
                score -= 1
            else:
                ss = abs(ball.pos[0] - (paddle.pos[0]+paddle.width//2)) / 20
                ball.velocity[0] = 2+ss*2
                ball.velocity[1] *= -1
                # screen.fill(BLACK)

        # 渲染背景
        screen.fill(BLACK)

        # 绘制球体和挡板
        ball.draw(screen)
        paddle.draw(screen)
        xx = random.randint(0, 255)

        # 绘制砖块
        for brick in bricks:
            # 渐变ß
            # r = math.sqrt((ball.pos[0] - brick.rect.x) ** 2 + (ball.pos[1] - brick.rect.y) ** 2)
            # brick.color = ((r)/720 *255 % 255,  255, (r)/720*255 % 255)
            brick.draw(screen)

        if ball.pos[1] <= screen_height//2:
           score += update_bricks(ball, bricks)

        # 显示得分
        font = pygame.font.Font(None, 36)
        score_text = font.render('Score: ' + str(score), True, RED)
        screen.blit(score_text, (10, 10))

        # 更新屏幕显示
        pygame.display.flip()

        # 设置帧率
        clock.tick(60)

    # 退出游戏
    pygame.quit()
    sys.exit()

本文转载至:https://blog.csdn.net/u010095372/article/details/137205814?spm=1001.2014.3001.5506

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏

  • 25
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
抱歉,我是一个语言模型,不能实际运行程序。但是,我可以提供下面的代码和说明供您参考。 首先,需要导入pygame和其他必要的库: ```python import pygame import random ``` 接下来,需要定义一些常量和变量: ```python # 窗口大小 WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 # 砖块大小 BRICK_WIDTH = 60 BRICK_HEIGHT = 20 # 砖块行数和列数 BRICK_ROWS = 5 BRICK_COLS = 10 # 球的大小和速度 BALL_RADIUS = 10 BALL_SPEED = 5 # 板子的大小和速度 PADDLE_WIDTH = 100 PADDLE_HEIGHT = 10 PADDLE_SPEED = 5 # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # 初始化pygame pygame.init() # 创建窗口 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # 设置窗口标题 pygame.display.set_caption('打砖块') # 加载字体 font = pygame.font.SysFont(None, 48) # 定义游戏状态 GAME_STATE_READY = 0 GAME_STATE_PLAYING = 1 GAME_STATE_GAMEOVER = 2 game_state = GAME_STATE_READY # 定义计分和生命值 score = 0 lives = 3 # 创建砖块 bricks = [] for row in range(BRICK_ROWS): for col in range(BRICK_COLS): brick = pygame.Rect(col * BRICK_WIDTH, row * BRICK_HEIGHT + 50, BRICK_WIDTH, BRICK_HEIGHT) bricks.append(brick) # 创建球和板子 ball = pygame.Rect(WINDOW_WIDTH // 2 - BALL_RADIUS, WINDOW_HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2) paddle = pygame.Rect(WINDOW_WIDTH // 2 - PADDLE_WIDTH // 2, WINDOW_HEIGHT - PADDLE_HEIGHT - 10, PADDLE_WIDTH, PADDLE_HEIGHT) # 设置球的速度和方向 ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ``` 然后,需要定义一些函数来处理游戏逻辑: ```python def draw_ball(): pygame.draw.circle(window, WHITE, (ball.x + BALL_RADIUS, ball.y + BALL_RADIUS), BALL_RADIUS) def draw_paddle(): pygame.draw.rect(window, WHITE, paddle) def draw_bricks(): for brick in bricks: pygame.draw.rect(window, GREEN, brick) def draw_score(): score_text = font.render('Score: ' + str(score), True, WHITE) window.blit(score_text, (10, 10)) def draw_lives(): lives_text = font.render('Lives: ' + str(lives), True, WHITE) window.blit(lives_text, (WINDOW_WIDTH - 120, 10)) def move_ball(): global ball_speed_x, ball_speed_y, score, lives, game_state # 碰到左右边界 if ball.left < 0 or ball.right > WINDOW_WIDTH: ball_speed_x = -ball_speed_x # 碰到上边界 if ball.top < 0: ball_speed_y = -ball_speed_y # 碰到板子 if ball.colliderect(paddle): ball_speed_y = -BALL_SPEED ball_speed_x = random.randint(-BALL_SPEED, BALL_SPEED) # 碰到砖块 for brick in bricks: if ball.colliderect(brick): bricks.remove(brick) ball_speed_y = -ball_speed_y score += 10 # 球掉落到底部 if ball.top > WINDOW_HEIGHT: lives -= 1 if lives == 0: game_state = GAME_STATE_GAMEOVER else: ball.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ball.move_ip(ball_speed_x, ball_speed_y) def move_paddle(): keys = pygame.key.get_pressed() # 左右移动板子 if keys[pygame.K_LEFT] and paddle.left > 0: paddle.move_ip(-PADDLE_SPEED, 0) if keys[pygame.K_RIGHT] and paddle.right < WINDOW_WIDTH: paddle.move_ip(PADDLE_SPEED, 0) def show_message(message): message_text = font.render(message, True, WHITE) message_rect = message_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)) window.blit(message_text, message_rect) def reset_game(): global game_state, score, lives, bricks, ball_speed_x, ball_speed_y game_state = GAME_STATE_READY score = 0 lives = 3 bricks = [] for row in range(BRICK_ROWS): for col in range(BRICK_COLS): brick = pygame.Rect(col * BRICK_WIDTH, row * BRICK_HEIGHT + 50, BRICK_WIDTH, BRICK_HEIGHT) bricks.append(brick) ball.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ``` 最后,需要在主循环中调用这些函数: ```python while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if game_state == GAME_STATE_READY: game_state = GAME_STATE_PLAYING elif game_state == GAME_STATE_GAMEOVER: reset_game() # 清空屏幕 window.fill(BLACK) # 根据游戏状态绘制界面 if game_state == GAME_STATE_READY: show_message('Press SPACE to start') elif game_state == GAME_STATE_PLAYING: move_ball() move_paddle() draw_ball() draw_paddle() draw_bricks() draw_score() draw_lives() elif game_state == GAME_STATE_GAMEOVER: show_message('Game Over\nPress SPACE to restart') # 更新屏幕 pygame.display.update() ``` 这就是一个简单打砖块游戏。您可以根据需要修改其中的细节和功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一晌小贪欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值