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

这篇具有很好参考价值的文章主要介绍了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基础学习专栏

文章来源地址https://www.toymoban.com/news/detail-852750.html

到了这里,关于pygame第7课——实现简单一个打砖块游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Pygame —— 一个好玩的游戏 Python 库

    在电子游戏的世界里,每一个精彩跳跃、每一个刺激冲刺、每一次动听的背景音乐,都是通过精心设计的代码和资源组合出来的奇幻体验。 想象一下,如果你能够制作自己的电子游戏,将内心的奇思妙想实现在屏幕上,那会是多么令人兴奋和自豪的事情。这个梦想,并不遥远

    2024年02月20日
    浏览(46)
  • Pygame 游戏开发 基础知识

    Pygame 是一个跨平台的 Python 模块, 专为电子游戏设计. Pygame 在已经非常优秀的 SDL 库的基础上增加了许多功能. 安装命令: 导入 Pygame 包: pygame.locals 模块包括了 pygame 中定义的各种常量. 导入所有常量 pygame.init() 是启动 pygame 并初始化的命令, 类似 python 中的 __init__ . 例子: pygame.

    2023年04月25日
    浏览(34)
  • Python基础篇(十五)-- Pygame游戏编程

            Pygame是一个开源的Python模块,专门用于多媒体应用(如电子游戏)的开发,其中包含对图像、声音、视频、事件、碰撞等的支持。Pygame建立在SDL的基础上,SDL是一套跨平台的多媒体开发库,用C语言实现,被广泛的应用于游戏、模拟器、播放器等的开发。而Pygame让

    2024年02月05日
    浏览(35)
  • Python -- 利用pygame库进行游戏开发基础

            Pygame是一个基于Python的游戏开发库,它提供了一系列的工具和接口,使开发人员能够轻松地创建各种类型的游戏,包括2D游戏和简单的3D游戏,主要是为了开发2D游戏而生。具有免费、开源,支持多种操作系统,具有良好的跨平台性等优点。 在开始学习Pygame之前,您

    2024年01月22日
    浏览(45)
  • 【python】之pygame模块,游戏开发【基础篇】

    什么是pygame? Pygame 是一个专门用来开发游戏的 Python 模块,主要为开发、设计 2D 电子游戏而生,具有免费、开源,支持多种操作系统,具有良好的跨平台性等优点。它提供了诸多操作模块,比如图像模块(image)、声音模块(mixer)、输入/输出(鼠标、键盘、显示屏)模块等

    2024年02月08日
    浏览(44)
  • Python -- 利用pygame库进行游戏开发基础(二)

    1、pygame的窗口创建         这段代码生成了一个窗口导入pygame模块和sys模块,这两个模块准备后续开发所需的命令以及作用,进行pygame的初始化,而后上设置窗口大小,创建窗口,而后进入循环确保窗口持续显示,再判断是否有退出事件,有则退出程序,再退出pygame,清空

    2024年02月19日
    浏览(37)
  • python | 基础学习(六)pygame游戏开发:飞机大战

    pygame 模块,转为电子游戏设计 $ sudo pip3 install pygame windows: pip install pygame (1)新建项目 飞机大战 (2)新建文件 pygame.py (3)建立游戏窗口: ①pygame的初始化和退出 pygame.init() :导入并初始化所有pygame模块,使用其他模块之前,必须先调用init方法。 pygame.quit() :卸载所有

    2024年02月08日
    浏览(41)
  • Python Pygame 游戏开发基础教程与项目实践(总目录)

    原文链接:https://xiets.blog.csdn.net/article/details/131368147 版权声明:原创文章禁止转载 Pygame 是一个免费的开源的跨平台库(支持 Windows、MacOS、Linux),用于使用 Python 开发视频游戏等多媒体应用程序。 Pygame 基础教程01: Python (Pygame) 游戏开发模块简介与安装 Pygame 基础教程02: 显示

    2024年02月14日
    浏览(38)
  • 【Python】pygame弹球游戏实现

    游戏源码: pygame_os库:

    2024年02月12日
    浏览(44)
  • Python利用pygame实现飞机大战游戏

    文章目录: 一:运行效果 1.演示 2.思路和功能 二:代码 文件架构 Demo 必备知识:python图形化编程pygame游戏模块 效果图 ◕‿◕✌✌✌ Python利用pygame实现飞机大战游戏运行演示 参考:【Python游戏】1小时开发飞机大战游戏-Pygame版本(1小时40分钟) 博主提取资源: 提取

    2024年04月09日
    浏览(51)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包