Pygame actual combat: what about poor memory? Don't worry, here's a memory enhancing game for you ~ [the more you play, the more addictive]

Introduction

Hello! Hello, I'm kimiko.

Today's game update series is coming. Do you want to know what type of game today is? Arrange it right away——

As we get older, we begin to forget things and forget things. Our memory is getting worse and worse!

This is not only the memory decline of adults with age, but also many children~

Do many parents often complain:

"My children recite the text very slowly. They often can't recite it dozens of times. Last night, they recited more than a little, and I was going to collapse;

After tutoring the children with homework, they fill in the blanks with very simple ancient poems. The child's first reaction is to open the book and copy it. If they don't turn over the textbook, they can't write it for half a day;

Last night, I memorized the words well. When I checked the next morning, I made 8 mistakes in 10 words and forgot everything. "

​...............................................................................................................................

Here are some ways to improve your memory - write a little game to improve your memory. I hope it can help you! The game is easier for everyone to accept~

text

The game module Pygame goes online - first install the corresponding environment and module, or which environment of the game was written before ha! ill-defined

Go and read the previous game articles~

Rules of the game: complete the memory within the specified time, turn out the corresponding pictures and eliminate them. You can only have three cards at a time, completely by remembering

Memory to complete this small game, increase the flexibility of the brain, use the brain more and exercise.

First, prepare the corresponding pictures: here.

These are also very cute: random ha, you can choose more than these ha! The background music must also be set, huh~

Official start——

Main game code:

class FlipCardByMemory():
    def __init__(self):
        # Play background music
        self.playbgm()
        # Load music after scoring
        self.score_sound = pygame.mixer.Sound(cfg.AUDIOPATHS['score'])
        self.score_sound.set_volume(1)
        # Card picture path
        self.card_dir = random.choice(cfg.IMAGEPATHS['carddirs'])
        # Main interface handle
        self.root = Tk()
        self.root.wm_title('Artifact baby - memory card games ')
        # Card dictionary in game interface
        self.game_matrix = {}
        # background image 
        self.blank_image = PhotoImage(data=cfg.IMAGEPATHS['blank'])
        # Back of 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)
        # Display the back of all cards on the interface
        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('<Button-1>', self.clickcallback)
                self.game_matrix[position].grid(row=r, column=c)
        # The front card has been displayed
        self.shown_cards = []
        # Number of cards in the field
        self.num_existing_cards = len(cards_list)
        # Show game time remaining
        self.num_seconds = 30
        self.time = Label(self.root, text=f'Time Left: {self.num_seconds}')
        self.time.grid(row=6, column=3, columnspan=2)
        # Center display
        self.root.withdraw()
        self.root.update_idletasks()
        x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2
        y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2
        self.root.geometry('+%d+%d' % (x, y))
        self.root.deiconify()
        # time
        self.tick()
        # Display main interface
        self.root.mainloop()

Play background music at the beginning of the game:

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

Set callback function to compare three cards:

 def clickcallback(self, event):
        card = event.widget
        if card.show: return
        # No card has been 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 card now
            if self.shown_cards[0].file == card.file:
                def delaycallback():
                    self.shown_cards[0].configure(image=self.blank_image)
                    self.shown_cards[0].blank_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].blank_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 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].blank_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(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 cards opened before are different from those 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', 'victory, You win, Do you want to do it again?')
            if is_restart: self.restart()
            else: self.root.destroy()

Time out, that is, the game is not completed. Pop up and select:

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've timed out. You need to do it again?')
            if is_restart: self.restart()
            else: self.root.destroy()

As shown in the figure below:

The overall effect of the game is as follows:

summary

Therefore, if you have a bad memory, you don't have to be pessimistic. You can improve and improve it through learning and training the day after tomorrow. Da ~ hey, hey, give it a try~

Your support is my biggest motivation!! Remember the third consecutive oh ~mua, welcome to read the previous articles~

💦 Free source code collection: Didi, I can~

Or take it from my home page (pc side)!

Your support is my biggest motivation!! Remember the third consecutive oh ~mua# welcome to read the previous articles~

💨 Previous reading recommendations——

Project 0.0 Merry Christmas! ❤

[Merry Christmas] I smell the smell of Christmas, and my favorite festivals are coming slowly ~ I wish you Merry Christmas.

Item 1.0 Merry Christmas 🎄 Yours 🎁 Delivered!

[Merry Christmas] Ding Dong, it doesn't matter if no one gives you a Christmas present. You can come to me? As long as you speak, I won't~

Item 1.1: Brick playing games

Program O takes you to recall the classic: developing a brick playing game with native Python~

🍓 Article summary——

Item 1.0 Python-2021 | summary of existing articles | continuously updated. It's enough to read this article directly

(more content + source code are summarized in the article!! welcome to read ~)

​​

Keywords: Python pygame

Added by pyr02k1 on Mon, 20 Dec 2021 21:20:26 +0200