欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python+Pygame實戰(zhàn)之24點游戲的實現(xiàn)

 更新時間:2022年04月29日 09:18:15   作者:木木子學(xué)python  
這篇文章主要為大家詳細介紹了如何利用Python和Pygame實現(xiàn)24點小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

導(dǎo)語

我第一次玩24點是初中的時候,那時候和堂弟表哥在堂妹家玩,堂妹提出玩24點游戲,堂妹比我們小三歲,可能正在上小學(xué)吧。

拿出一副撲克牌去掉大小怪和花牌,從剩下的牌里隨便找出四張,誰能先用加減乘除算出24就算贏。

如果大家都同意放棄或者有人計算出來就重新開始一局。結(jié)果是我們?nèi)齻€哥哥都輸多贏少,堂妹顯然是經(jīng)過了準備的。

其實24點小游戲除了能用來無聊的時候跟朋友與一起玩兒下,還能鍛煉思維能力,尤其是家里的小孩子提升數(shù)學(xué)能力

多鍛煉還是很有好處的,尤其是那些數(shù)學(xué)不好小孩子——可提高心算的速度和準確度,當(dāng)數(shù)學(xué)變成游戲之后孩子也更有興趣嘛~今天木木子就帶大家寫一款有界面的“24點小游戲”哦

游戲介紹

(1)什么是24點游戲

棋牌類益智游戲,要求結(jié)果等于二十四

(2)游戲規(guī)則

任意抽取4個數(shù)字(1——10),用加、減、乘、除(可加括號)把出現(xiàn)的數(shù)算成24。每個數(shù)字必須用一次且只能用一次。“算24點”作為一種鍛煉思維的智力游戲,還應(yīng)注意計算中的技巧問題。計算時,我們不可能把牌面上的4個數(shù)的不同組合形式——去試,更不能瞎碰亂湊。

例:3、8、8、9

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

實現(xiàn)代碼

1.定義游戲這部分代碼小寫game.py文件

'''

    定義游戲

'''
import copy
import random
import pygame


'''
Function:
    卡片類
Initial Args:
    --x,y: 左上角坐標(biāo)
    --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)
    '''根據(jù)button function執(zhí)行響應(yīng)操作'''
    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
    '''只剩下一個數(shù)字時檢查是否為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
    '''驗證生成的數(shù)字是否有答案'''
    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)
        # 避免有數(shù)字重復(fù)時表達式重復(fù)(T_T懶得優(yōu)化了)
        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
    '''計算函數(shù)'''
    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.游戲主函數(shù)

def main():
    # 初始化, 導(dǎo)入必要的游戲素材
    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()
    # 精靈組
    # --數(shù)字
    number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
    # --運算符
    operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
    # --按鈕
    button_sprites_group = getButtonSpritesGroup(BUTTONS)
    # 游戲主循環(huán)
    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)
        # 更新數(shù)字
        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)

游戲效果展示

到此這篇關(guān)于Python+Pygame實戰(zhàn)之24點游戲的實現(xiàn)的文章就介紹到這了,更多相關(guān)Python Pygame 24點游戲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python提取包含關(guān)鍵字的整行數(shù)據(jù)方法

    python提取包含關(guān)鍵字的整行數(shù)據(jù)方法

    今天小編就為大家分享一篇python提取包含關(guān)鍵字的整行數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python對象與json相互轉(zhuǎn)換的方法

    python對象與json相互轉(zhuǎn)換的方法

    這篇文章主要介紹了python對象與json相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Python 線程池用法簡單示例

    Python 線程池用法簡單示例

    這篇文章主要介紹了Python 線程池用法,結(jié)合簡單實例形式分析了Python線程池相關(guān)使用技巧與操作注意事項,需要的朋友可以參考下
    2019-10-10
  • Python GUI庫PyQt5圖形和特效樣式QSS介紹

    Python GUI庫PyQt5圖形和特效樣式QSS介紹

    這篇文章主要介紹了Python GUI庫PyQt5圖形和特效樣式QSS介紹,需要的朋友可以參考下
    2020-02-02
  • python如何做代碼性能分析

    python如何做代碼性能分析

    這篇文章主要介紹了python如何做代碼性能分析,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-04-04
  • 使用Django和Python創(chuàng)建Json response的方法

    使用Django和Python創(chuàng)建Json response的方法

    下面小編就為大家分享一篇使用Django和Python創(chuàng)建Json response的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié)

    python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié)

    數(shù)據(jù)類型轉(zhuǎn)換是常見的功能,本文主要介紹了python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié),文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • Python之pandas讀寫文件亂碼的解決方法

    Python之pandas讀寫文件亂碼的解決方法

    下面小編就為大家分享一篇Python之pandas讀寫文件亂碼的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • numpy中關(guān)于where函數(shù)的用法

    numpy中關(guān)于where函數(shù)的用法

    這篇文章主要介紹了numpy中關(guān)于where函數(shù)的用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • 利用Python繪畫雙擺操作分享

    利用Python繪畫雙擺操作分享

    這篇文章主要介紹了利用Python畫雙擺,繪畫雙擺的過程主要包括以下步驟,雙擺問題、運動過程及公式推導(dǎo)過程,下文詳細介紹,需要的小伙伴可以參考一下
    2022-04-04

最新評論