Python
Python

 

 

 

Introduction

The Memory Game is a fun and challenging game that tests your short-term memory. In this game, players are presented with a set of cards laid face down. The goal is to match pairs of cards by flipping them two at a time. Each card contains an image or a number, and players need to remember the location of the cards to match them correctly. This project is implemented using Python, and it provides an excellent opportunity for learning basic game development concepts.

Objective

The objective of this project is to create a memory matching game using Python. Players will try to match pairs of hidden cards by flipping them, and the game will track the number of attempts. The program will use a random arrangement of cards, and the user will interact with the game by selecting pairs of cards until all pairs are matched.

Code Implementation

Below is the Python code for the Memory Matching Game:

import random
import time

# Define the cards
cards = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
cards = cards + cards  # Duplicate to create pairs

# Shuffle the cards
random.shuffle(cards)

# Create the game board
board = ['*' for _ in range(len(cards))]
matched = [False for _ in range(len(cards))]

# Function to display the board
def display_board():
    print("Current board:")
    print(" ".join(board))

# Function to check if the game is over
def is_game_over():
    return all(matched)

# Main game loop
def play_game():
    attempts = 0

    while not is_game_over():
        display_board()
        try:
            # Player input for two card positions
            first_choice = int(input("Enter first card position (0-15): "))
            second_choice = int(input("Enter second card position (0-15): "))

            if first_choice == second_choice or first_choice < 0 or second_choice < 0 or first_choice >= len(cards) or second_choice >= len(cards):
                print("Invalid input, try again.")
                continue

            # If cards are a match
            if cards[first_choice] == cards[second_choice]:
                print(f"Match found: {cards[first_choice]}")
                matched[first_choice] = True
                matched[second_choice] = True
            else:
                print(f"No match: {cards[first_choice]} and {cards[second_choice]}")
                board[first_choice] = '*'
                board[second_choice] = '*'

            attempts += 1
        except ValueError:
            print("Invalid input. Please enter numbers only.")
        
    print(f"Congratulations! You've matched all the cards in {attempts} attempts.")

# Start the game
if __name__ == "__main__":
    print("Welcome to the Memory Matching Game!")
    time.sleep(1)
    play_game()

Program Structure

The program is divided into a few key components:

  • Card Setup: We create a list of unique cards (A to H), and then duplicate this list to create pairs. The cards are then shuffled randomly.
  • Display Function: A function is used to display the current state of the game board, which shows the face-down cards and the ones that have been matched.
  • Game Loop: The game runs in a loop, allowing players to choose two cards per turn. If the cards match, they are marked as matched; otherwise, the player tries again.
  • End Condition: The game continues until all cards are matched, and the number of attempts is tracked.

How to Run the Program

Follow these steps to run the Memory Matching Game:

  1. Ensure you have Python installed on your machine. You can download it from here.
  2. Copy the Python code provided above into a new file, for example, memory_game.py.
  3. Open a terminal or command prompt and navigate to the directory where the file is saved.
  4. Run the program by typing python memory_game.py and pressing enter.
  5. Follow the on-screen prompts to play the game and match pairs of cards!

 

© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)