In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use Python to make 24:00 Mini Game". In daily operation, I believe many people have doubts about how to use Python to produce 24:00 Mini Game. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use Python to make Mini Game at 24:00". Next, please follow the editor to study!
Rules of the game
Four numbers are randomly selected from the ten numbers 1-10 (repeatable), and the four numbers are calculated by addition, subtraction, multiplication, division and parentheses to get 24. Each number must be used once, but cannot be reused.
Implementing Step1 step by step: making 24:00 Generator
Since it is 24:00 Mini Game, of course, you have to define a 24:00 game generator first. The main idea is to randomly generate 4 numbers with solutions, and the range is between 1 and 10. The code is implemented as follows:
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
In verifying whether the four numbers have a solution and finding all the solution parts, I directly violently enumerate and then repeat them, and the interested students can optimize the solution algorithm by themselves (when the numbers are repeated). My code is shown in the following figure, which is actually recursively enumerating all the sorts and verifying whether there is a solution one by one:
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:] NMel 1): 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 resStep2: define game genie classes
Because players need to manipulate the card with a mouse click, some collision detection is involved. So first define some necessary game genie classes.
① card class
The definition of the card class is also simple, displaying itself on the screen according to the assigned attribute value. Of course, you also need to change these attribute values (content, color, font, etc.) according to the user's operation and change the display state on the screen according to the change of the attribute. Specifically, the code implementation is as follows:
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
The button class is similar to the card class, except that when the user clicks the button, it needs to respond to the user's click according to the function of the button (that is, to implement the function once). So you just need to inherit the card class and then define a callback function that responds to the user's click on the button. The code is implemented as follows:
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, expect, or.'% (self.attribute, 'NEXT',' RESET' 'ANSWERS') return sprites_groupStep3: implement the main cycle of the game
First think about how to design the main interface of the game. The personal simple design sketches are as follows (not particularly popular design sketches):
OK, do it. First initialize, load the necessary material and define the necessary variables, the code implementation is as follows:
# initialization Import the necessary game materials pygame.init () pygame.mixer.init () screen = pygame.display.set_mode (SCREENSIZE) pygame.display.set_caption ('24 point-Wechat official account: Charles's Pikachu') 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 cycle clock = pygame.time.Clock () selected_numbers = [] selected_operators = [] selected_buttons = [] is_win = False
The main cycle of the game is mainly divided into three parts, the first is button detection:
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')
Update the card status and some variables according to the test results:
'' check whether the control is clicked''def checkClicked (group, mouse_pos) Group_type='NUMBER'): selected = [] # Digital card / operator card if group_type= = GROUPTYPES [0] or group_type= = GROUPTYPES [1]: max_selected = 2 if group_type= = GROUPTYPES [0] else 1 num_selected = 0 for each in group: num_selected + = int (each.is_selected) for each in group: if each.rect.collidepoint (mouse_pos): if each.is_selected: each.is_selected = not each.is_selected num_ Selected-= 1 each.select_order = None else: if num_selected < max_selected: each.is_selected = not each.is_selected Num_selected + = 1 each.select_order = str (num_selected) if each.is_selected: selected.append (each.attribute) # Button Card elif group_type = = GROUPTYPES [2 ]: for each in group: if each.rect.collidepoint (mouse_pos): each.is_selected = True selected.append (each.attribute) # throw exception else: raise ValueError ('checkClicked.group_type unsupport Expect, or...'% (group_type, * GROUPTYPES)) return selected
When two numbers and an operator are clicked, the clicked number 1 {+ /-/ × / /} clicked number 2 is performed (the numbers 1 and 2 are determined according to the click order), and the card properties and some necessary variables are further updated:
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 Expect or...'% 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)
Finally, each card is displayed on the screen according to the properties of each card. if the game wins / fails, the game victory / failure prompt box is displayed at the same time:
# all elves are 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) so far The study on "how to make 24:00 Mini Game with Python" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.