脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python+Pygame实战之24点游戏的实现

Python+Pygame实战之24点游戏的实现

2022-12-12 10:44木木子学python Python

这篇文章主要为大家详细介绍了如何利用Python和Pygame实现24点小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

导语

我第一次玩24点是初中的时候,那时候和堂弟表哥在堂妹家玩,堂妹提出玩24点游戏,堂妹比我们小三岁,可能正在上小学吧。

拿出一副扑克牌去掉大小怪和花牌,从剩下的牌里随便找出四张,谁能先用加减乘除算出24就算赢。

如果大家都同意放弃或者有人计算出来就重新开始一局。结果是我们三个哥哥都输多赢少,堂妹显然是经过了准备的。

其实24点小游戏除了能用来无聊的时候跟朋友与一起玩儿下,还能锻炼思维能力,尤其是家里的小孩子提升数学能力

多锻炼还是很有好处的,尤其是那些数学不好小孩子——可提高心算的速度和准确度,当数学变成游戏之后孩子也更有兴趣嘛~今天木木子就带大家写一款有界面的“24点小游戏”哦

游戏介绍

(1)什么是24点游戏

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

(2)游戏规则

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

例:3、8、8、9

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

实现代码

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
'''
 
    定义游戏
 
'''
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.游戏主函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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点游戏的实现

到此这篇关于Python+Pygame实战之24点游戏的实现的文章就介绍到这了,更多相关Python Pygame 24点游戏内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7091641208207835173

延伸 · 阅读

精彩推荐
  • PythonDjango中FilePathField字段的用法

    Django中FilePathField字段的用法

    这篇文章主要介绍了Django中FilePathField字段的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    菲宇9122020-05-21
  • Pythonpython中for用来遍历range函数的方法

    python中for用来遍历range函数的方法

    今天小编就为大家分享一篇python中for用来遍历range函数的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    H3D9jg15612021-03-02
  • PythonPython多重继承的方法解析执行顺序实例分析

    Python多重继承的方法解析执行顺序实例分析

    这篇文章主要介绍了Python多重继承的方法解析执行顺序,结合实例形式分析了Python多重继承时存在方法命名冲突情况的解析执行顺序与相关原理,需要的朋友...

    很长很长的名字7322021-02-25
  • Python详解python中的异常捕获

    详解python中的异常捕获

    这篇文章主要介绍了python中的异常捕获的相关资料,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下...

    the3times4792021-08-14
  • Python详解用Python处理HTML转义字符的5种方式

    详解用Python处理HTML转义字符的5种方式

    本文介绍了详解用Python处理HTML转义字符的5种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    liuzhijun10022020-12-29
  • PythonPython动态语言与鸭子类型详解

    Python动态语言与鸭子类型详解

    这篇文章主要介绍了Python动态语言与鸭子类型详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参...

    FOOFISH-PYTHON之禅5052021-07-27
  • Python对pytorch中不定长序列补齐的操作

    对pytorch中不定长序列补齐的操作

    这篇文章主要介绍了对pytorch中不定长序列补齐的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    XJTU-Qidong12612021-11-17
  • PythonPython内存读写操作示例

    Python内存读写操作示例

    这篇文章主要介绍了Python内存读写操作,结合实例形式分析了Python常见内存读写操作使用方法及相关注意事项,需要的朋友可以参考下...

    笨鸟可以先飞呀10992021-03-18