您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python+Pygame怎么實(shí)現(xiàn)24點(diǎn)游戲的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Python+Pygame怎么實(shí)現(xiàn)24點(diǎn)游戲文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。
(1)什么是24點(diǎn)游戲
棋牌類(lèi)益智游戲,要求結(jié)果等于二十四
(2)游戲規(guī)則
任意抽取4個(gè)數(shù)字(1——10),用加、減、乘、除(可加括號(hào))把出現(xiàn)的數(shù)算成24。每個(gè)數(shù)字必須用一次且只能用一次?!八?4點(diǎn)”作為一種鍛煉思維的智力游戲,還應(yīng)注意計(jì)算中的技巧問(wèn)題。計(jì)算時(shí),我們不可能把牌面上的4個(gè)數(shù)的不同組合形式——去試,更不能瞎碰亂湊。
例:3、8、8、9
答案:3×8÷(9-8)=24
1.定義游戲這部分代碼小寫(xiě)game.py文件
''' 定義游戲 ''' import copy import random import pygame ''' Function: 卡片類(lèi) 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 '''畫(huà)到屏幕上''' 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)) '''按鈕類(lèi)''' 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點(diǎn)游戲生成器''' 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 '''只剩下一個(gè)數(shù)字時(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 '''驗(yàn)證生成的數(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ù)時(shí)表達(dá)式重復(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 '''計(jì)算函數(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點(diǎn)小游戲') 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點(diǎn)游戲生成器 game24_gen = game24Generator() game24_gen.generate() # 精靈組 # --數(shù)字 number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now) # --運(yùn)算符 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) # 精靈都畫(huà)到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怎么實(shí)現(xiàn)24點(diǎn)游戲”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Python+Pygame怎么實(shí)現(xiàn)24點(diǎn)游戲”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。