Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to write a memory flip game

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to use Python to write a memory flip game", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use Python to write a memory flip game" this article.

Development tools

Python version: 3.7.4

Related modules:

Pygame module

Tkinter module

Pillow module

And some modules that come with python.

Environment building

Install Python and add it to the environment variable, and pip installs the relevant modules you need.

be all eagerness to see it

Run the following command on the terminal:

Python Game27.py

The effect is as follows:

Video link

Brief introduction of principle

Ok, let's give a brief introduction to the implementation principle of the game.

First of all, let's play one of our favorite background music with the help of pygame:

'' play background music''def playbgm (self): pygame.init () pygame.mixer.init () pygame.mixer.music.load (cfg.AUDIOPATHS [' bgm']) pygame.mixer.music.play (- 1,0.0)

Then, let's initialize the main interface of tkinter:

# main interface handle self.root = Tk () self.root.wm_title ('Flip Card by Memory-- Charles's Pikachu')

And 16 cards that have not been turned over are displayed on the main interface:

# Card dictionary in the game interface self.game_matrix = {} # background image self.blank_image = PhotoImage (data=cfg.IMAGEPATHS ['blank']) # back of the card self.cards_back_image = PhotoImage (data=cfg.IMAGEPATHS [' cards_back']) # Index of all cards cards_list = list (range (8)) + list (range (8)) random.shuffle (cards_list) # displays the backs of all cards on the interface Face for r in range (4): for c in range (4): position = f'{r} _ {c} 'self.game_ matrix [position] = Label (self.root) Image=self.cards_back_image) self.game_ matrix [position] .back _ image=self.cards_back_image self.game_ matrix [position] .file = str (cards_ list [r * 4 + c]) self.game_ matrix [position] .show = False self.game_ matrix [position] .bind (', self.clickcallback) self.game_ matrix [position] .grid (row=r, column=c)

These 16 cards contain 8 completely different images, and the goal of our game is to pair 16 cards with the same image in a limited time. The rule of matching is that the mouse clicks on two cards successively. If the image on the back of the card is the same, the match is successful, otherwise the match fails. The game mainly examines the player's memory, because the game also stipulates that the number of cards opened by the game is at most two, otherwise the card that was clicked and opened at the beginning will be covered again (if the card does not match successfully).

Next, let's define some useful variables:

# the card on the front has been displayed self.shown_cards = [] # the number of cards on the field self.num_existing_cards = len (cards_list) # shows the remaining time in the game self.num_seconds = 30self.time = Label (self.root, text=f'Time Left: {self.num_seconds}') self.time.grid (row=6, column=3, columnspan=2)

And let the interface appear in the center of the computer screen at first:

# centered display self.root.withdraw () self.root.update_idletasks () x = (self.root.winfo_screenwidth ()-self.root.winfo_reqwidth ()) / 2y = (self.root.winfo_screenheight ()-self.root.winfo_reqheight ()) / 2self.root.geometry ('+% dashes% d'% (x, y)) self.root.deiconify ()

Since the matching of all the cards is completed in a limited time, let's write a timing function and update the remaining time of the current game in real time:

Def tick (self): if self.num_existing_cards = = 0: return if self.num_seconds! = 0: self.num_seconds-= 1 self.time ['text'] = f'Time Left: {self.num_seconds}' self.time.after (1000, self.tick) else: is_restart = messagebox.askyesno ('Game Over',' You fail since time up, do you want to play again?') If is_restart: self.restart () else: self.root.destroy ()

Finally, when we click on the card with the left mouse button, we use the code to define the response rules of the game to achieve the function we want:

Def clickcallback (self, event): card = event.widget if card.show: return # No cards were opened before if len (self.shown_cards) = 0: self.shown_cards.append (card) image = ImageTk.PhotoImage (Image.open (os.path.join (self.card_dir) (card.file+'.png')) card.configure (image=image) card.show_image = image card.show = True # only one card was opened before elif len (self.shown_cards) = = 1: #-the card opened before is the same as the current card if self.shown_cards [0] .file = = card.file: def delaycallback ( ): self.shown_cards [0]. Configure (image=self.blank_image) self.shown_cards [0]. Compare _ image=self.blank_image card.configure (image=self.blank_image) card.blank_image = self.blank_image self.shown_cards.pop (0) self.score_sound. Play () self.num_existing_cards-= 2 image = ImageTk.PhotoImage (Image.open (os.path.join (self.card_dir) (card.file+'.png')) card.configure (image=image) card.show_image = image card.show = True card.after (300, delaycallback) #-the card opened before is different from the card now else: self.shown_cards.append (card) image= ImageTk.PhotoImage (Image.open (os.path.join (self.card_dir) Card.file+'.png')) card.configure (image=image) card.show_image = image card.show = True # two cards were opened before elif len (self.shown_cards) = = 2: #-the first card opened before is the same as the current card if self.shown_cards [0] .file = = card.file: Def delaycallback (): self.shown_cards [0] .configure (image=self.blank_image) self.shown_cards [0] .compare _ image=self.blank_image card.configure (image=self.blank_image) card.blank_image = self.blank_image self.shown_cards.pop (0) Self.score_sound.play () self.num_existing_cards-= 2 image = ImageTk.PhotoImage (Image.open (os.path.join (self.card_dir) Card.file+'.png')) card.configure (image=image) card.show_image = image card.show = True card.after Delaycallback) #-the second card opened before is the same as the current card elif self.shown_cards [1] .file = = card.file: def delaycallback (): self.shown_cards [1] .configure (image=self.blank_image) self.shown_cards [1] .cards _ image=self.blank_image card.configure (image=self.blank_image) card.blank_image = self.blank_image self.shown_cards.pop (1) self.score_sound.play () self.num_existing_cards-= 2 image= ImageTk.PhotoImage (Image.open (self.card_dir) Card.file+'.png')) card.configure (image=image) card.show_image = image card.show = True card.after Delaycallback) #-the cards opened before are different from the cards now else: self.shown_cards.append (card) self.shown_cards [0] .configure (image=self.cards_back_image) self.shown_cards [0] .show = False self.shown_cards.pop (0) image= ImageTk.PhotoImage (Image) .open (os.path.join (self.card_dir) Card.file+'.png')) self.shown_cards [- 1] .configure (image=image) self.shown_cards [- 1] .show _ image=image self.shown_cards [- 1] .show = True # judge whether the game has won if self.num_existing_cards = 0: is_restart = messagebox.askyesno ('Game Over',' Congratulations, you win, do you want to play again?') If is_restart: self.restart () else: self.root.destroy () these are all the contents of this article entitled "how to write a memory flipping game with Python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report