当前位置:

首页 > 编程开发 > Python+Pygame实现24点游戏教程

Python+Pygame实现24点游戏教程

游戏介绍(1)什么是24点游戏棋牌类益智游戏,要求结果等于二十四(2)游戏规则任意抽取4个数字(1——10),用加、减、乘、除(可加括号)把出现的数算成24。每个数字必须用一次且只能用一次。“算24点”作为一种锻炼思维的智力游戏,还应注意计算中的技巧问题。计算时,我们不可能把牌面上的4个数的不同组合形式——去试,更不能瞎碰乱凑。例:3、8、8、9答案:3×8÷(9-8)=24实现代码1.定义游戏这部分代码小写game.py文件

本文目录

    游戏介绍

    (1)什么是24点游戏

    棋牌类益智游戏,要求结果等于二十四

    (2)游戏规则

    任意抽取4个数字(1——10),用加、减、乘、除(可加括号)把出现的数算成24。每个数字必须用一次且只能用一次。“算24点”作为一种锻炼思维的智力游戏,还应注意计算中的技巧问题。计算时,我们不可能把牌面上的4个数的不同组合形式——去试,更不能瞎碰乱凑。

    例:3、8、8、9

    答案:3×8÷(9-8)=24

    实现代码

    1.定义游戏这部分代码小写game.py文件

    '''
    
        定义游戏
    
    '''
    import copy
    import random
    import pygame
    
    
    '''
    Function:
        卡片类
    Initial Args:
        --x,y: 左上角坐标
        --width: 宽
        --height: 高
        --text: 文本
        --font: [字体路径, 字体大小]
        --font_colors(list): 字体颜色
        --bg_colors(list): 背景色
    '''
    class Card(pygame.sprite.Sprite):
        def __init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute, **kwargs):
            pygame.sprite.Sprite.__init__(self)
            self.rect = pygame.Rect(x, y, width, height)
            self.text = text
            self.attribute = attribute
            self.font_info = font
            self.font = pygame.font.Font(font[0], font[1])
            self.font_colors = font_colors
            self.is_selected = False
            self.select_order = None
            self.bg_colors = bg_colors
        '''画到屏幕上'''
        def draw(self, screen, mouse_pos):
            pygame.draw.rect(screen, self.bg_colors[1], self.rect, 0)
            if self.rect.collidepoint(mouse_pos):
                pygame.draw.rect(screen, self.bg_colors[0], self.rect, 0)
            font_color = self.font_colors[self.is_selected]
            text_render = self.font.render(self.text, True, font_color)
            font_size = self.font.size(self.text)
            screen.blit(text_render, (self.rect.x+(self.rect.width-font_size[0])/2, self.rect.y+(self.rect.height-font_size[1])/2))
    
    
    '''按钮类'''
    class Button(Card):
        def __init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute, **kwargs):
            Card.__init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute)
        '''根据button function执行响应操作'''
        def do(self, game24_gen, func, sprites_group, objs):
            if self.attribute == 'NEXT':
                for obj in objs:
                    obj.font = pygame.font.Font(obj.font_info[0], obj.font_info[1])
                    obj.text = obj.attribute
                self.font = pygame.font.Font(self.font_info[0], self.font_info[1])
                self.text = self.attribute
                game24_gen.generate()
                sprites_group = func(game24_gen.numbers_now)
            elif self.attribute == 'RESET':
                for obj in objs:
                    obj.font = pygame.font.Font(obj.font_info[0], obj.font_info[1])
                    obj.text = obj.attribute
                game24_gen.numbers_now = game24_gen.numbers_ori
                game24_gen.answers_idx = 0
                sprites_group = func(game24_gen.numbers_now)
            elif self.attribute == 'ANSWERS':
                self.font = pygame.font.Font(self.font_info[0], 20)
                self.text = '[%d/%d]: ' % (game24_gen.answers_idx+1, len(game24_gen.answers)) + game24_gen.answers[game24_gen.answers_idx]
                game24_gen.answers_idx = (game24_gen.answers_idx+1) % len(game24_gen.answers)
            else:
                raise ValueError('Button.attribute unsupport %s, expect %s, %s or %s...' % (self.attribute, 'NEXT', 'RESET', 'ANSWERS'))
            return sprites_group
    
    
    '''24点游戏生成器'''
    class game24Generator():
        def __init__(self):
            self.info = 'game24Generator'
        '''生成器'''
        def generate(self):
            self.__reset()
            while True:
                self.numbers_ori = [random.randint(1, 10) for i in range(4)]
                self.numbers_now = copy.deepcopy(self.numbers_ori)
                self.answers = self.__verify()
                if self.answers:
                    break
        '''只剩下一个数字时检查是否为24'''
        def check(self):
            if len(self.numbers_now) == 1 and float(self.numbers_now[0]) == self.target:
                return True
            return False
        '''重置'''
        def __reset(self):
            self.answers = []
            self.numbers_ori = []
            self.numbers_now = []
            self.target = 24.
            self.answers_idx = 0
        '''验证生成的数字是否有答案'''
        def __verify(self):
            answers = []
            for item in self.__iter(self.numbers_ori, len(self.numbers_ori)):
                item_dict = []
                list(map(lambda i: item_dict.append({str(i): i}), item))
                solution1 = self.__func(self.__func(self.__func(item_dict[0], item_dict[1]), item_dict[2]), item_dict[3])
                solution2 = self.__func(self.__func(item_dict[0], item_dict[1]), self.__func(item_dict[2], item_dict[3]))
                solution = dict()
                solution.update(solution1)
                solution.update(solution2)
                for key, value in solution.items():
                    if float(value) == self.target:
                        answers.append(key)
            # 避免有数字重复时表达式重复(T_T懒得优化了)
            answers = list(set(answers))
            return answers
        '''递归枚举'''
        def __iter(self, items, n):
            for idx, item in enumerate(items):
                if n == 1:
                    yield [item]
                else:
                    for each in self.__iter(items[:idx]+items[idx+1:], n-1):
                        yield [item] + each
        '''计算函数'''
        def __func(self, a, b):
            res = dict()
            for key1, value1 in a.items():
                for key2, value2 in b.items():
                    res.update({'('+key1+'+'+key2+')': value1+value2})
                    res.update({'('+key1+'-'+key2+')': value1-value2})
                    res.update({'('+key2+'-'+key1+')': value2-value1})
                    res.update({'('+key1+'×'+key2+')': value1*value2})
                    value2 > 0 and res.update({'('+key1+'÷'+key2+')': value1/value2})
                    value1 > 0 and res.update({'('+key2+'÷'+key1+')': value2/value1})
            return res

    2.游戏主函数

    def main():
        # 初始化, 导入必要的游戏素材
        pygame.init()
        pygame.mixer.init()
        screen = pygame.display.set_mode(SCREENSIZE)
        pygame.display.set_caption('24点小游戏')
        win_sound = pygame.mixer.Sound(AUDIOWINPATH)
        lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
        warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
        pygame.mixer.music.load(BGMPATH)
        pygame.mixer.music.play(-1, 0.0)
        # 24点游戏生成器
        game24_gen = game24Generator()
        game24_gen.generate()
        # 精灵组
        # --数字
        number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
        # --运算符
        operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
        # --按钮
        button_sprites_group = getButtonSpritesGroup(BUTTONS)
        # 游戏主循环
        clock = pygame.time.Clock()
        selected_numbers = []
        selected_operators = []
        selected_buttons = []
        is_win = False
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(-1)
                elif event.type == pygame.MOUSEBUTTONUP:
                    mouse_pos = pygame.mouse.get_pos()
                    selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
                    selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
                    selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
            screen.fill(AZURE)
            # 更新数字
            if len(selected_numbers) == 2 and len(selected_operators) == 1:
                noselected_numbers = []
                for each in number_sprites_group:
                    if each.is_selected:
                        if each.select_order == '1':
                            selected_number1 = each.attribute
                        elif each.select_order == '2':
                            selected_number2 = each.attribute
                        else:
                            raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
                    else:
                        noselected_numbers.append(each.attribute)
                    each.is_selected = False
                for each in operator_sprites_group:
                    each.is_selected = False
                result = calculate(selected_number1, selected_number2, *selected_operators)
                if result is not None:
                    game24_gen.numbers_now = noselected_numbers + [result]
                    is_win = game24_gen.check()
                    if is_win:
                        win_sound.play()
                    if not is_win and len(game24_gen.numbers_now) == 1:
                        lose_sound.play()
                else:
                    warn_sound.play()
                selected_numbers = []
                selected_operators = []
                number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
            # 精灵都画到screen上
            for each in number_sprites_group:
                each.draw(screen, pygame.mouse.get_pos())
            for each in operator_sprites_group:
                each.draw(screen, pygame.mouse.get_pos())
            for each in button_sprites_group:
                if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']:
                    is_win = False
                if selected_buttons and each.attribute == selected_buttons[0]:
                    each.is_selected = False
                    number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
                    selected_buttons = []
                each.draw(screen, pygame.mouse.get_pos())
            # 游戏胜利
            if is_win:
                showInfo('Congratulations', screen)
            # 游戏失败
            if not is_win and len(game24_gen.numbers_now) == 1:
                showInfo('Game Over', screen)
            pygame.display.flip()
            clock.tick(30)

    游戏效果展示

    Python+Pygame实现24点游戏教程

    Python+Pygame实现24点游戏教程

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Python Pygame
    相关文章 更多
    python删除一个列表里的重复元素的方法与代码示例
    python删除一个列表里的重复元素的方法与代码示例

    学习如何使用Python高效删除列表中的重复元素。本文提供5种常见方法的代码示例,涵盖保持顺序与不保持顺序的场景,适合初学者和进阶开发者参考。

    Python写接口的步骤及完整代码示例
    Python写接口的步骤及完整代码示例

    详细讲解使用Python编写Web接口的核心步骤与完整代码示例,涵盖环境准备、路由定义、数据校验、服务启动及调试测试方法。

    codex怎么读取word文档及docx文件操作教程
    codex怎么读取word文档及docx文件操作教程

    介绍如何利用编程工具读取和解析Word文档(docx格式),涵盖基础文本提取代码示例、结构化数据处理逻辑,以及处理复杂排版时的技术局限与替代方案。

    怎么在Python中调用C语言代码提升性能
    怎么在Python中调用C语言代码提升性能

    详细讲解在Python中调用C语言代码提升性能的完整实践指南,包含原理分析、编译步骤、ctypes与CFFI具体实现、性能对比及常见陷阱。

    Python与C语言的性能差异及底层原理
    Python与C语言的性能差异及底层原理

    深入解析Python与C语言在执行效率上的数量级差异,从编译机制、变量内存布局、动态类型推断到GIL锁,系统阐明底层核心原理。

    Python和C语言哪个更适合编程入门
    Python和C语言哪个更适合编程入门

    客观对比Python与C语言在心智负担、底层机制与学习反馈上的核心差异,提供清晰有据的选择标准与切实的入门学习路径。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    langgraph python guide中文入门教程详解
    langgraph python guide中文入门教程详解

    本篇LangGraph Python中文入门教程详解,系统梳理StateGraph状态机定义、节点编写、边与条件路由、检查点持久化(MemorySaver)等核心机制,提供从环境安装到完整循环智能体构建的代码示例与实操指导。

    Windows 安装 Python:从官方入口到虚拟环境的可复现实践
    Windows 安装 Python:从官方入口到虚拟环境的可复现实践

    面向后端开发者,基于 Python 官方文档说明如何在 Windows 上安装 Python、创建 venv 虚拟环境及使用 pip 管理依赖。包含可复制命令、验证方法及工具选择边界,避免常见配置误区。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。