Program to Create Memory Game in Python

Write a program to create memory game in python.

Here is a step by step guide to create Memory game in Python.

Memory games are a classic way to test and improve your memory skills. They have been around for a long time and have been enjoyed by people of all ages. In this tutorial we will show you how to create memory game in Python. This game will consist of grid of cards where each card has a hidden image. The player needs to find matching pairs of cards by clicking on them.

To build this game we will use the Python programming language and the Pygame library. Pygame is a cross-platform set of Python modules that is used to create video games. It is ideal for creating simple games like the memory game that we will be building.

Let’s get started!

Step 1: Installing Pygame

Before we begin we need to install Pygame. To install Pygame open your terminal (or command prompt) and enter the following command:

pip install pygame

Step 2: Creating the Grid

Our memory game will be a grid of cards where each card will have a hidden image. We will use a 4×4 grid of cards for this game. We will use Pygame library to create the grid.

First let’s create Pygame window. We will also set window’s dimensions and title:

import pygame
pygame.init()

# Set up the Pygame window
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Memory Game")

Now, let’s create grid. We will create a list of 16 cards where each card is a dictionary that contains the card’s image and whether it is currently hidden or revealed:

cards = []
for i in range(16):
    card = {"image": None, "is_hidden": True}
    cards.append(card)

Next we will create a function that will draw grid onto the Pygame window. We will also load the card images and draw the hidden cards:

def draw_grid():
    card_width = 100
    card_height = 100
    margin = 10
    x = margin
    y = margin
    for card in cards:
        if card["is_hidden"]:
            pygame.draw.rect(screen, (255, 255, 255), (x, y, card_width, card_height))
        else:
            screen.blit(card["image"], (x, y))
        x += card_width + margin
        if x > WINDOW_WIDTH - card_width - margin:
            x = margin
            y += card_height + margin

    pygame.display.update()

# Load the card images
card_images = []
for i in range(8):
    image = pygame.image.load(f"images/{i}.png")
    card_images.append(image)

# Draw the hidden cards
for i in range(16):
    card = cards[i]
    image = card_images[i // 2]
    card["image"] = image
draw_grid()

This code will draw the grid onto the Pygame window and load the card images.

Step 3: Adding Interactivity

Now let’s add interactivity to the game. When player clicks on a hidden card we want to reveal it. If player clicks on two cards that have same image we want to keep them revealed. If the player clicks on two cards that have different images we want to hide them again.

To do this we will create a function that will handle the card clicks. We will also create a variable to keep track of the currently selected card:

selected_card = None

def handle_card_click(pos):
    global selected_card
    x, y = pos

    # Calculate the clicked card's index
    card_width = 100
    card_height = 100
    margin = 10
    row = (y - margin) // (card_height + margin)
    col = (x - margin) // (card_width + margin)
    index = row * 4 + col

    card = cards[index]
    if card["is_hidden"]:
        # If the card is hidden, reveal it
        card["is_hidden"] = False
        draw_grid()
        if selected_card is None:
            # If this is the first card clicked, remember it
            selected_card = card
        else:
            # If this is the second card clicked, check if it matches the first card
            if card["image"] == selected_card["image"]:
                # If the cards match, keep them revealed
                selected_card = None
            else:
                # If the cards don't match, hide them again
                pygame.time.wait(1000)
                card["is_hidden"] = True
                selected_card["is_hidden"] = True
                selected_card = None
            draw_grid()

This code will handle card clicks and keep track of currently selected card. It will also check if the two selected cards match and keep them revealed if they do.

Now we need to modify our main game loop to call the handle_card_click function when player clicks on a card:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            handle_card_click(pos)

This code will call the handle_card_click function when player clicks on a card. It will also handle case when the player closes the game window.

Step 4: Adding a Game Over Screen

Now that we have added interactivity to our memory game last step is to add a game over screen that will be displayed when player has found all matching pairs of cards.

To do this we will modify our draw_grid function to check if all cards have been revealed. If so we will display game on the screen which will congratulate the player on their victory.

Here’s the modified draw_grid function:

def draw_grid():
    all_revealed = True
    for card in cards:
        if card["is_hidden"]:
            all_revealed = False
            break

    if all_revealed:
        # Display the game over screen
        font = pygame.font.Font(None, 36)
        text = font.render("You won!", True, (0, 0, 0))
        text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
        screen.blit(text, text_rect)
    else:
        # Draw the grid and hidden cards
        # ... previous code

    pygame.display.update()

We first loop through all cards to check if all revealed. If not we will continue to draw grid and hidden cards as before. If all cards have been revealed we display game over screen by rendering message using a font and centering it on screen.

And thats all You now have a fully functional memory game in Python.

Here is the complete code:

import pygame
import sys

pygame.init()

WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500

screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Memory Game")

card_images = [    pygame.image.load("card1.png"),    pygame.image.load("card2.png"),    pygame.image.load("card3.png"),    pygame.image.load("card4.png"),    pygame.image.load("card5.png"),    pygame.image.load("card6.png"),    pygame.image.load("card7.png"),    pygame.image.load("card8.png")]

cards = []
for i in range(8):
    cards.append({"image": card_images[i], "is_hidden": True})
    cards.append({"image": card_images[i], "is_hidden": True})

pygame.display.update()

selected_card = None

def handle_card_click(pos):
    global selected_card
    x, y = pos

    card_width = 100
    card_height = 100
    margin = 10
    row = (y - margin) // (card_height + margin)
    col = (x - margin) // (card_width + margin)
    index = row * 4 + col

    card = cards[index]
    if card["is_hidden"]:
        card["is_hidden"] = False
        draw_grid()
        if selected_card is None:
            selected_card = card
        else:
            if card["image"] == selected_card["image"]:
                selected_card = None
            else:
                pygame.time.wait(1000)
                card["is_hidden"] = True
                selected_card["is_hidden"] = True
                selected_card = None
            draw_grid()

def draw_grid():
    all_revealed = True
    for card in cards:
        if card["is_hidden"]:
            all_revealed = False
            break

    if all_revealed:
        font = pygame.font.Font(None, 36)
        text = font.render("You won!", True, (0, 0, 0))
        text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
        screen.blit(text, text_rect)
    else:
        card_width = 100
        card_height = 100
        margin = 10
        for i, card in enumerate(cards):
            if card["is_hidden"]:
                row = i // 4
                col = i % 4
                x = margin + col * (card_width + margin)
                y = margin + row * (card_height + margin)
                card_rect = pygame.Rect(x, y, card_width, card_height)
                pygame.draw.rect(screen, (255, 255, 255), card_rect)
            else:
                row = i // 4
                col = i % 4
                x = margin + col * (card_width + margin)
                y = margin + row * (card_height + margin)
                screen.blit(card["image"], (x, y))

    pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            handle_card_click(pygame.mouse.get_pos())

    draw_grid()

Make sure to save the images

card1.png, card2.png, card3.png, card4.png, card5.png, card6.png, card7.png, and card8.png

in the same directory as the Python file before running the program.

With this code you can create a fun memory game that tests your memory skills. The game is very simple but it can be challenging to remember where all the cards are located. To play the game simply run the Python file and start clicking on cards to reveal them. If you find two matching cards they will stay revealed. Otherwise they will hide again after a short delay.

To customize the game you can modify the images used for the cards. Make sure to keep the file names consistent with the code, or update the code to match the file names you want to use. You can also modify the size of the game window and the size of the cards, as well as the margin between cards.

This simple memory game is a great starting point for developing your own games in Python. You can experiment with adding more features such as a scoring system, different levels of difficulty, or even sound effects. With the power of Python and the flexibility of Pygame the possibilities are endless!

I hope you enjoyed this tutorial on how to create a memory game in Python. If you have any questions or feedback feel free to leave a comment below.