In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the Python+Pygame how to achieve 24:00 game related knowledge, the content is detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone after reading this Python+Pygame how to achieve 24:00 game article will have a harvest, let's take a look at it.
Introduction to the game
(1) what is an 24:00 game
Chess and card puzzle games that require a result equal to 24
(2) rules of the game
Take 4 numbers at random (1murmur10) and use addition, subtraction, multiplication and division (can add parentheses) to calculate the number that appears to be 24. Each number must be used once and only once. "calculate 24:00" as a kind of mental game to exercise thinking, we should also pay attention to the skills in calculation. When calculating, it is impossible for us to try the different combinations of the four numbers on the card, let alone mess around.
Example: 3, 8, 8, 9
Answer: 3 × 8 / (9-8) = 24
Implementation code
1. Define this part of the game code lowercase game.py file
'' define the game''import copyimport randomimport pygame'''Function: card class Initial Args:-- XQuery y: upper left corner coordinates-- width: width-- height: height-- text: text-- font: [font path Font size]-- font_colors (list): font color-- bg_colors (list): background color''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''draw to the screen 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)) 'button class' '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)''perform response operations according to 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 ='[% dash% d]:'% (game24_gen.answers_idx+1, len (game24_gen.answers)) + game24_ gen.promoters [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 point game generator' 'class game24Generator (): def _ _ init__ (self): self.info =' game24Generator' generator''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''when there is only one number left, check whether it is 24' def check (self): if len (self.numbers_now) = = 1 and float (self.numbers) _ now [0]) = = self.target: return True return False''reset' def _ reset (self): self.answers = [] self.numbers_ori = [] self.numbers_now = [] self.target = 24. Self.answers_idx = 0''verify whether the generated number has an answer' '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 (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_ / [3]) solution = dict () solution.update (solution1) solution.update (solution2) for key Value in solution.items (): if float (value) = = self.target: answers.append (key) # avoid repetition of expressions when there are numeric repeats (too lazy to optimize) answers = list (set (answers)) return answers' recursive enumeration''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:], nMur1): yield [item] + each 'Computing function' '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
two。 Game main function
Def main (): # initialization Import the necessary game materials pygame.init () pygame.mixer.init () screen = pygame.display.set_mode (SCREENSIZE) pygame.display.set_caption ('24:00 Mini Game') 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 24:00 Game Generator game24_gen = game24Generator () game24_gen.generate () # Elvist Group #-- numeric number_sprites_group = getNumberSpritesGroup (game24_gen.numbers_now) #-- operator operator_sprites_group = getOperatorSpritesGroup (OPREATORS) #-- Button button_sprites_group = getButtonSpritesGroup (BUTTONS) # Game main loop 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) # Update numeric 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 = =' 1regions: Selected_number1 = each.attribute elif each.select_order = = '2regions: 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) # Spirits are all painted on 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 () # Game Victory if is_win: showInfo ('Congratulations', screen) # Game failure if not is_win and len (game24_gen.numbers_now) = = 1: showInfo (' Game Over', screen) pygame.display.flip () clock.tick (30) Game effect display
This is the end of the article on "how to achieve 24:00 games on Python+Pygame". Thank you for your reading. I believe that everyone has a certain understanding of the knowledge of "how to achieve 24:00 games in Python+Pygame". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.