【Python】pygame弹球游戏实现

这篇具有很好参考价值的文章主要介绍了【Python】pygame弹球游戏实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

弹球游戏实现

游戏源码:

import pygame,pygame_os,random,math
"""
砖块设定:80*30 一个砖块 其中 70*20是有颜色的,边缘的5*5(四周)是白色--为了区分块与块之间
        总块数在10*13=130块,第一行是(0,0)-(0,9);第二行是(1,0)-(1,9)如此类推,用random函数进行随机放置方块
"""

# 查找数组元素
def find(list, num):
    try:
        index = list.index(num)
    except:
        return -1
    else:
        return index

# 初始变量
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
yellow = (255, 255, 0)
font_file = "IPix中文像素字体.ttf"
win_width, win_height, bg_color, caption_title = (800, 600, white, "弹球游戏")
clock = pygame.time.Clock()

if __name__ == '__main__':
    # 程序死循环
    while 1:
        # 初始游戏窗口
        window_init = pygame_os.Start_Name(win_width, win_height, bg_color, caption_title)
        window = pygame_os.Start_Name.start_init(window_init)

        # 初始游戏开始界面
        pygame_os.Font.set_font(window, font_file, 45, "欢迎来到弹球游戏", (255, 0, 0),"top")
        for i in range(3):
            button_pos = ((win_width - 200)/2, 200 + 100 * i)
            button_name = ["简单难度", "普通难度", "困难难度"]
            locals()[f"button_{i}"] = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, button_name[i])
            pygame_os.Button.set_button(locals()[f"button_{i}"])


        #游戏选择难度while循环
        Start_bool = True
        difficulty = None
        tem_bool = True # 控制只执行一次的按钮if判断
        while Start_bool:
            for event in pygame.event.get():
                # 当按钮经过时:
                if event.type == pygame.MOUSEMOTION:
                    # 简单难度按钮
                    if (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 200 <= event.pos[1] <=250:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_0)
                            tem_bool = False
                    # 普通难度按钮
                    elif (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 300 <= event.pos[1] <=350:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_1)
                            tem_bool = False
                    # 困难难度按钮
                    elif (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 400 <= event.pos[1] <=450:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_2)
                            tem_bool = False
                    #重画
                    else:
                        pygame_os.Button.button_MOUSEMOTION_end(button_0)
                        pygame_os.Button.button_MOUSEMOTION_end(button_1)
                        pygame_os.Button.button_MOUSEMOTION_end(button_2)
                        tem_bool = True

                # 当按钮按下时:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    # 简单难度按钮
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 200 <= event.pos[1] <= 250:
                            pygame_os.Button.button_MOUSEDOWN(button_0)
                            difficulty = 0
                    # 普通难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 300 <= event.pos[1] <= 350:
                            pygame_os.Button.button_MOUSEDOWN(button_1)
                            difficulty = 1
                    # 困难难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 400 <= event.pos[1] <= 450:
                            pygame_os.Button.button_MOUSEDOWN(button_2)
                            difficulty = 2
                # 当按钮松开时:
                if event.type == pygame.MOUSEBUTTONUP:
                    # 简单难度按钮
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 200 <= event.pos[1] <= 250:
                            pygame_os.Button.button_MOUSEUP(button_0)
                            Start_bool = False
                            break
                    # 普通难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 300 <= event.pos[1] <= 350:
                            pygame_os.Button.button_MOUSEUP(button_1)
                            Start_bool = False
                            break
                    # 困难难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 400 <= event.pos[1] <= 450:
                            pygame_os.Button.button_MOUSEUP(button_2)
                            Start_bool = False
                            break

                # 退出游戏代码
                if event.type == pygame.QUIT:exit()

        # 清屏
        pygame.draw.rect(window, white, (0, 0, win_width, win_height))
        pygame.display.update()

        # 画长板以及小球
        plank_size = 25 + 50 * (3 - difficulty)
        pygame.draw.rect(window, red, ((win_width - plank_size) / 2, 500, plank_size, 10))
        pygame.draw.circle(window, green, (win_width / 2, 490), 10)
        pygame.display.update()

        # 游戏开始设置开关
        Start_bool = True

        last_x, last_y, last_plank_x = win_width / 2, 490, (win_width - plank_size) / 2
        while Start_bool:
            for event in pygame.event.get():
                # 长板随着鼠标移动而移动
                if event.type == pygame.MOUSEMOTION:
                    if event.pos[1] >= 500:
                        pygame.draw.rect(window, white, (0, 500, win_width, 10))
                        pygame.draw.rect(window, red, (event.pos[0] - plank_size/2, 500, plank_size, 10))
                        pygame.draw.rect(window, white, (0, 480, win_width, 20))
                        last_x, last_y, last_plank_x = event.pos[0], 490, event.pos[0] - plank_size/2
                        pygame.draw.circle(window, green, (last_x, last_y), 10)
                        pygame.display.update()
                if event.type == pygame.MOUSEBUTTONUP:
                    angle = random.choice(range(20,60))
                    x_speed = math.cos(math.radians(angle)) * (difficulty * 3 + 5)
                    y_speed = - math.sin(math.radians(angle)) * (difficulty * 3 + 5)
                    Start_bool = False
                    break
                # 退出游戏代码
                if event.type == pygame.QUIT:exit()

        # 砖块放置函数
        brick_list = []
        def set_brick(difficulty):
            global brick_list, last_x, last_y
            brick_list = []
            tem_list = []
            # 设立砖块数列
            for row in range(10):
                for column in range(13):
                    brick_list.append([row, column, False])
            brick_num = random.choice(range(50 + 20 * difficulty, 80 + 20 * difficulty))
            # 删除球附近的砖块
            index = find(brick_list, [int((last_x-10)/80),int((last_y-10)/30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x + 10) / 80), int((last_y - 10) / 30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x - 10) / 80), int((last_y + 10) / 30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x + 10) / 80), int((last_y + 10) / 30), False])
            if index != -1:
                del brick_list[index]

            # 随机砖块数列
            for i in range(len(brick_list)):
                tem_list.append(i)
            for num in range(brick_num):
                random_num = random.choice(range(len(tem_list)))
                brick_list[tem_list[random_num]][2] = True
                del tem_list[random_num]
            # 构建被抽中砖块
            for num in range(len(brick_list)):
                if brick_list[num][2] == True:
                    random_color = (
                        random.choice(range(50, 200)),
                        random.choice(range(50, 200)),
                        random.choice(range(50, 200))
                    )
                    x = 80*brick_list[num][0]+5
                    y = 30*brick_list[num][1]+5
                    pygame.draw.rect(window, random_color, (x, y, 70, 20))



        # 游戏正式开始
        game_score = 0
        while True:
            # 刷新分数
            pygame.draw.rect(window, white, (0, 530, win_width, win_height - 530))
            pygame_os.Font.set_font(window, font_file, 30, "目前得分:{0}".format(game_score), (0, 0, 0), (0, 550))
            # 无尽模式砖块打完刷新
            Start_bool = False
            tem_num = 0
            for brick in brick_list:
                if brick[2] == True:
                    tem_num += 1
            if tem_num >= 5:
                Start_bool = True
            if Start_bool == False:
                pygame.draw.rect(window, white, (0, 0, win_width, 490))
                set_brick(difficulty)

            # 画球的运动轨迹
            pygame.draw.circle(window, white, (last_x, last_y), 10)
            last_x += x_speed
            last_y += y_speed
            pygame.draw.circle(window, green, (last_x , last_y), 10)
            # 碰到边缘反弹
            if last_x + 10 >= win_width or last_x - 10 <= 0:
                x_speed = -x_speed
            if (last_y <= 500 <= last_y + 10 and last_plank_x <= last_x <= last_plank_x + plank_size) or last_y - 10 <= 0:
                y_speed = -y_speed

            # 画边缘线
            pygame.draw.line(window, (0, 0, 0), (0, 0), (win_width, 0), 2)
            pygame.draw.line(window, (0, 0, 0), (0, 0), (0, 498), 2)
            pygame.draw.line(window, (0, 0, 0), (win_width - 2, 0), (win_width - 2, 498), 2)
            pygame.draw.line(window, (0, 0, 0), (0, 498), (win_width, 498), 2)

            # 画长板
            pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))

            # 判断砖块碰撞消失
                # 碰撞删除砖块
            def clean_break(window, pos_x, pos_y, ball_last_x, ball_last_y):
                global white
                x = 80 * pos_x + 5
                y = 30 * pos_y + 5
                pygame.draw.rect(window, white, (x, y, 70, 20))
                # 重新画球
                pygame.draw.circle(window, green, (last_x, last_y), 10)
                pygame.display.update()

                # 从砖块左边碰撞
            judge_x = int((last_x+10)/80)
            judge_y = int(last_y/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and x_speed > 0:
                brick_list[index][2] = False
                game_score += 1
                x_speed = -x_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块右边碰撞
            judge_x = int((last_x-10)/80)
            judge_y = int(last_y/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and x_speed < 0:
                brick_list[index][2] = False
                game_score += 1
                x_speed = -x_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块上边碰撞
            judge_x = int(last_x/80)
            judge_y = int((last_y+10)/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and y_speed > 0:
                brick_list[index][2] = False
                game_score += 1
                y_speed = -y_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块下边碰撞
            judge_x = int(last_x/80)
            judge_y = int((last_y-10)/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and y_speed < 0:
                brick_list[index][2] = False
                game_score += 1
                y_speed = -y_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

            pygame.display.update()

            # 判断Gameover
            if last_y > 525:
                pygame.draw.circle(window, white, (last_x, last_y), 10)
                pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))
                pygame.display.update()
                break

            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    if event.pos[1] >= 500:
                        last_plank_x = event.pos[0] - plank_size / 2
                        pygame.draw.rect(window, white, (0, 500, win_width, 10))
                        pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))

                    pygame.display.update()

                if event.type == pygame.QUIT: exit()
            # 限制最大帧数为60
            clock.tick(60)

        # 画Gameover画面
        Start_bool = True
        tem_bool = True  # 控制只执行一次的按钮if判断
        while Start_bool:
            pygame.draw.rect(window, (128, 128, 128), (0, 0, win_width, win_height / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (128, 128, 0), (0, win_height / 4, win_width, win_height*2 / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (128, 0, 128), (0, win_height*2 / 4, win_width, win_height*3 / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (0, 128, 128), (0, win_height*3 / 4, win_width, win_height))
            pygame.display.update()
            clock.tick(1)
            Start_bool = False
        # 画结束按钮
        button_pos = ((win_width - 200)/2, 350)
        button_refresh_init = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, "重来")
        pygame_os.Button.set_button(button_refresh_init)

        button_pos = ((win_width - 200)/2, 450)
        button_end_init = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, "退出")
        pygame_os.Button.set_button(button_end_init)

        # 画GAMEOVER字样
        pygame_os.Font.set_font(window, "IPix中文像素字体.ttf", 45, "GAMEOVER", (0, 0, 0), "center")

        pygame.display.update()

        Start_bool = True
        while Start_bool:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_refresh_init)
                            tem_bool = False
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_end_init)
                            tem_bool = False
                    # 重画
                    else:
                        pygame_os.Button.button_MOUSEMOTION_end(button_refresh_init)
                        pygame_os.Button.button_MOUSEMOTION_end(button_end_init)
                        tem_bool = True

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        pygame_os.Button.button_MOUSEDOWN(button_refresh_init)
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        pygame_os.Button.button_MOUSEDOWN(button_end_init)

                if event.type == pygame.MOUSEBUTTONUP:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        pygame_os.Button.button_MOUSEUP(button_refresh_init)
                        Start_bool = False
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        pygame_os.Button.button_MOUSEUP(button_end_init)
                        exit()

                if event.type == pygame.QUIT:exit()


"""
①道具
②砖块消失 √
③分裂球
④按Esc游戏暂停且跳出窗口
"""

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

import pygame


class Start_Name:
    def __init__(self, win_width, win_height, bg_color, caption_title):
        self.win_width = win_width
        self.win_height = win_height
        self.bg_color = bg_color
        self.caption_title = caption_title

    def start_init(self):
        pygame.init()
        window = pygame.display.set_mode((self.win_width, self.win_height))
        pygame.display.set_caption(self.caption_title)
        window.fill(self.bg_color)
        return window


class Button:
    def __init__(self, window, button_color, pos, width, height, font_name, font_size, font_color, font_text):
        self.window = window
        self.button_color = button_color
        self.pos = pos
        self.width = width
        self.height = height
        self.font_name = font_name
        self.font_size = font_size
        self.font_color = font_color
        self.font_text = font_text
        self.button_tem_DU_color = button_color
        self.button_tem_motion_color = button_color

    def set_button(self):
        x, y = self.pos
        pygame.draw.rect(self.window, self.button_color, (x, y, self.width, self.height))
        font01 = pygame.font.Font(self.font_name, self.font_size)
        text01 = font01.render(self.font_text, True, self.font_color)
        w, h = text01.get_size()
        self.window.blit(text01, (x + (self.width - w) / 2, y + (self.height - h) / 2))
        pygame.display.update()
        return text01

    def button_MOUSEDOWN(self):
        self.button_tem_DU_color = self.button_color
        self.button_color = (128, 128, 128)
        Button.set_button(self)
        return True

    def button_MOUSEMOTION(self):
        self.button_tem_motion_color = self.button_color
        self.button_color = (175, 175, 175)
        Button.set_button(self)
        return True

    def button_MOUSEUP(self):
        self.button_color = self.button_tem_DU_color
        Button.set_button(self)
        return True

    def button_MOUSEMOTION_end(self):
        self.button_color = self.button_tem_motion_color
        Button.set_button(self)
        return True


class Font:
    @staticmethod
    def set_font(window, font_file, font_size, text, font_color, text_pos):
        font01 = pygame.font.Font(font_file, font_size)
        text01 = font01.render(text, True, font_color)
        if text_pos == "top":
            text_pos = ((window.get_size()[0] - text01.get_size()[0])/2, 0)
        if text_pos == "bottom":
            text_pos = (0, (window.get_size()[1] - text01.get_size()[1]) / 2)
        if text_pos == "center":
            text_pos = ((window.get_size()[0] - text01.get_size()[0])/2, (window.get_size()[1] - text01.get_size()[1])/2)
        window.blit(text01, text_pos)
        pygame.display.update()
        return text01

到了这里,关于【Python】pygame弹球游戏实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • 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日
    浏览(54)
  • 【python】 pygame学习示例 --飞机大战小游戏制作

    python版本:3.8.5 所需模块:pygame random os pygame版本:20.1 开发环境:pycharm专业版 硬件环境:win11 8G内存以上 使用python的第三方库–pygame 制作飞机大战小游戏 小游戏的内容包括: 玩家player的移动 子弹的发射 陨石的随机掉落(包括旋转 大小 下落角度) 玩家 子弹 陨石的碰撞交互

    2024年02月04日
    浏览(51)
  • 基于Python pygame简易版斗兽棋小游戏源代码

    基于Python pygame简易版斗兽棋小游戏源代码 游戏规则如下: 胜利条件: 1.吃掉对方全部棋子 2.走入对方兽穴(不可进入自己洞穴) 吃法: 1.象狮虎豹狼狗猫鼠象 2.同类棋子先行者吃掉对方 3.老鼠可以进河,老鼠在河里时,岸上的动物不能捕食他,他也不能捕食岸上的动物 4.狮虎在河中没

    2023年04月09日
    浏览(113)
  • Python利用pygame实现飞机大战游戏

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

    2024年04月09日
    浏览(80)
  • Python “贪吃蛇”游戏,在不断改进中学习pygame编程

    目录 前言 改进过程一 增加提示信息 原版帮助摘要 pygame.draw pygame.font class Rect class Surface 改进过程二 增加显示得分 改进过程三 增加背景景乐 增加提示音效 音乐切换 静音切换 mixer.music.play 注意事项 原版帮助摘要 pygame.mixer pygame.mixer.Sound 改进过程四 增加WASD方向键 增加退出事

    2024年02月12日
    浏览(51)
  • Python版基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式

    基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式 按空格进入单人模式,按‘t’进入双人模式,双人模式下玛丽1采用空格键上跳,玛丽2采用方向上键上跳。 完整代码下载地址:Python版基于pygame的玛丽快跑小游戏源代码 完整代码下载地址:Python版基于

    2024年02月11日
    浏览(61)
  • Python版经典小游戏愤怒的小鸟源代码,基于pygame+pymunk

    Python版经典小游戏愤怒的小鸟源代码,基于pygame+pymunk 程序依赖:pygame 2.0.1, pymunk 5.5.0 直接运行main.py 完整代码下载地址:Python版经典小游戏愤怒的小鸟源代码 tool.py 完整代码下载地址:Python版经典小游戏愤怒的小鸟源代码

    2024年02月16日
    浏览(49)
  • 使用Python+pygame实现贪吃蛇小游戏

    使用第三方库pygame,关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520 给出两种实现。 第一种 运行效果如下: 游戏源码如下: 第二种 就不给出运行效果图了,你可以运行看看。 下面给出另一种实现源码: OK! 

    2024年01月16日
    浏览(73)
  • 强化学习Agent系列(一)——PyGame游戏编程,Python 贪吃蛇制作实战教学

    大家好,未来的开发者们请上座 随着人工智能的发展,强化学习基本会再次来到人们眼前,遂想制作一下相关的教程。强化学习第一步基本离不开虚拟环境的搭建,下面用大家耳熟能详的贪吃蛇游戏为基础,制作一个Agent,完成对这个游戏的绝杀。 万里长城第一步:用pytho

    2024年01月21日
    浏览(62)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包