Memory Game Using Python: A Card Matching Game With Source Code

Introduction :

The Memory game, also known as Concentration, is a classic card game where players need to match pairs of cards. This project implements the Memory game in Python using the Simple GUI library, providing a fun and interactive way to enhance your programming skills. The game involves flipping over two cards at a time to find matching pairs. The challenge is to remember the positions of the cards and match them with the fewest number of turns.

Required Modules or Packages :-

To run the Memory game, you’ll need the simplegui library, which provides the graphical user interface for this project. The library handles creating the game window, drawing elements, and managing user interactions.

1. simplegui:

This library is used for creating the game window, handling mouse clicks, and drawing on the canvas. To install SimpleGUI, you can use the following command:

				
					pip install simplegui
				
			

If you encounter any issues with installing SimpleGUI, you might need to look for alternative libraries or environments that support SimpleGUI, as it is often included in specific educational platforms

How to Run the Code:-

1. Clone the Repository: [Insert your repository link here if applicable]
2. Navigate to the Project Directory: Use the command line to go to the directory where your code is saved.
3. Run the Code: Execute the script using Python.

				
					python memory_game.py
				
			

Code Explanation :-

Here’s a breakdown of the key components of the Memory game code:

Global Variables

				
					 WIDTH = 800 # width of canvas
 HEIGHT = 100 # height of canvas
 deck = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
 WIDTH_CARD = WIDTH / len(deck) # width of each card
 MARGIN = 2 # margin between the edge of card and the blue line
 turns = 0
 state_list = []
 previous_exposed_num =-1 #-1 means null
 previous_exposed_index =-1 #-1 means null
				
			

 ● deck:List of card values.
WIDTH_CARD: Width of each card calculated based on the total width and number of cards.
state_list: Tracks the state of each card (hidden, exposed, paired).

Helper Function to Initialize Globals

				
					 def new_game():
 global deck, turns, state_list, previous_exposed_num,
 previous_exposed_index
 random.shuffle(deck)
 turns = 0
 label.set_text("Turns = " + str(turns))
 state_list = ["hidden"] * len(deck)
 previous_exposed_num =-1
 previous_exposed_index =-1
				
			

 new_game(): Resets the game by shuffling the deck, resetting turns, and updating the state of each card..

 Event Handlers

				
					 def mouseclick(pos):
 global previous_exposed_num, previous_exposed_index,
 exposed_cards, turns
 on_click_card_index = pos[0] // WIDTH_CARD
 if state_list[on_click_card_index] == "hidden":
 if previous_exposed_num ==-1 and state_list.count("exposed")
 == 0:
 previous_exposed_num = deck[on_click_card_index]
 previous_exposed_index = on_click_card_index
 state_list[on_click_card_index] = "exposed"
 elif previous_exposed_num ==-1 and
 state_list.count("exposed") == 2:
 for n in range(len(state_list)):
 if state_list[n] == "exposed":
 state_list[n] = "hidden"
 previous_exposed_num = deck[on_click_card_index]
 previous_exposed_index = on_click_card_index
state_list[on_click_card_index] = "exposed"
 else:
 turns += 1
 label.set_text("Turns = " + str(turns))
 if previous_exposed_num == deck[on_click_card_index]:
 state_list[previous_exposed_index] = "paired"
 state_list[on_click_card_index] = "paired"
 previous_exposed_num =-1
 previous_exposed_index =-1
 else:
 previous_exposed_num =-1
 previous_exposed_index =-1
 state_list[on_click_card_index] = "exposed"
				
			

 ● mouseclick(pos): Handles mouse clicks to reveal cards and manage game logic
based on the state of the cards

Draw Handler :

				
					def draw(canvas):
 for n in range(len(deck)):
 if state_list[n] == "hidden":
 point_upper_left = (MARGIN + n * WIDTH_CARD, MARGIN)
 point_upper_right = (WIDTH_CARD- MARGIN + n * WIDTH_CARD,
 MARGIN)
 point_bottom_right = (WIDTH_CARD- MARGIN + n *
 WIDTH_CARD, HEIGHT- MARGIN)
 point_bottom_left = (MARGIN + n * WIDTH_CARD, HEIGHT
MARGIN)
 canvas.draw_polygon([point_upper_left, point_upper_right,
 point_bottom_right, point_bottom_left], 2, 'Blue')
 canvas.draw_line(point_upper_left, point_bottom_right, 2,
 'Yellow')
 canvas.draw_line(point_upper_right, point_bottom_left, 2,
 'Yellow')
 elif state_list[n] == "paired":
 canvas.draw_text(str(deck[n]), (5 + n * WIDTH_CARD, 80),
 80, 'Green')
else:
 canvas.draw_text(str(deck[n]), (5 + n * WIDTH_CARD, 80),
 80, 'White')
				
			

 ● draw(canvas): Renders the cards on the canvas, showing their state (hidden,
exposed, or paired).

Get Discount on Top Educational Courses

Brand NameDiscount InformationCoupon Codes Link
Educative.io20% discount on Educative courses and plans
W3Schools20% discount on W3Schools courses
KodeKloud10% discount on KodeKloud courses and plans
GeeksforGeeks30% discount on GeeksforGeeks courses
Target Test Prep20% discount on Target Test Prep
Coding Ninjas₹5000 discount on Coding Ninjas courses
Skillshare40% discount on Skillshare
DataCamp50% discount on DataCamp
365 Data Science57% discount on 365 Data Science Plans
Get SmarterFlat 20% discount on Get Smarter courses
SmartKeedaFlat 40% discount on SmartKeeda courses
StackSocial20% discount on StackSocial courses

Source Code :

				
					# Complete code for the Memory game
import simplegui
import random

# globals variables
WIDTH = 800  # width of canvas
HEIGHT = 100  # height of canvas
deck = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
WIDTH_CARD = WIDTH / len(deck)  # width of each card
MARGIN = 2  # margin between the edge of card and the blue line
turns = 0
state_list = []
previous_exposed_num = -1  # -1 means null
previous_exposed_index = -1  # -1 means null

# helper function to initialize globals
def new_game():
    global deck, turns, state_list, previous_exposed_num, previous_exposed_index
    random.shuffle(deck)
    turns = 0
    label.set_text("Turns = " + str(turns))
    state_list = ["hidden"] * len(deck)
    previous_exposed_num = -1
    previous_exposed_index = -1

# define event handlers
def mouseclick(pos):
    global previous_exposed_num, previous_exposed_index, turns
    on_click_card_index = pos[0] // WIDTH_CARD

    if state_list[on_click_card_index] == "hidden":
        if previous_exposed_num == -1 and state_list.count("exposed") == 0:
            previous_exposed_num = deck[on_click_card_index]
            previous_exposed_index = on_click_card_index
            state_list[on_click_card_index] = "exposed"
        elif previous_exposed_num == -1 and state_list.count("exposed") == 2:
            for n in range(len(state_list)):
                if state_list[n] == "exposed":
                    state_list[n] = "hidden"
            previous_exposed_num = deck[on_click_card_index]
            previous_exposed_index = on_click_card_index
            state_list[on_click_card_index] = "exposed"
        else:
            turns += 1
            label.set_text("Turns = " + str(turns))
            if previous_exposed_num == deck[on_click_card_index]:
                state_list[previous_exposed_index] = "paired"
                state_list[on_click_card_index] = "paired"
                previous_exposed_num = -1
                previous_exposed_index = -1
            else:
                previous_exposed_num = -1
                previous_exposed_index = -1
                state_list[on_click_card_index] = "exposed"

# cards are logically 50x100 pixels in size
def draw(canvas):
    for n in range(len(deck)):
        if state_list[n] == "hidden":
            point_upper_left = (MARGIN + n * WIDTH_CARD, MARGIN)
            point_upper_right = (WIDTH_CARD - MARGIN + n * WIDTH_CARD, MARGIN)
            point_bottom_right = (WIDTH_CARD - MARGIN + n * WIDTH_CARD, HEIGHT - MARGIN)
            point_bottom_left = (MARGIN + n * WIDTH_CARD, HEIGHT - MARGIN)
            canvas.draw_polygon([point_upper_left, point_upper_right, point_bottom_right, point_bottom_left], 2, 'Blue')
            canvas.draw_line(point_upper_left, point_bottom_right, 2, 'Yellow')
            canvas.draw_line(point_upper_right, point_bottom_left, 2, 'Yellow')
        elif state_list[n] == "paired":
            canvas.draw_text(str(deck[n]), (5 + n * WIDTH_CARD, 80), 80, 'Green')
        else:
            canvas.draw_text(str(deck[n]), (5 + n * WIDTH_CARD, 80), 80, 'White')

# create frame and add a button and labels
frame = simplegui.create_frame("Memory", WIDTH, HEIGHT)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(turns))

# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)

# get things rolling
new_game()
frame.start()

				
			

Output :

Find More Projects

3D Car Driving Game Using Html CSS And JavaScript Introduction Hello friends, welcome to today’s new blog post. Today we have created …

Dice Rolling Game Using HTML CSS And JavaScript Introduction Hey coders, welcome to another new blog. In this article we’ll build a …

Crossey Road Game Clone Using HTML CSS And JavaScript Introduction This is our HTML code which sets up the basic structure of …

Memory Card Game Using HTML CSS And JavaScript Introduction Hello coders, welcome to another new blog. Today in this article we’ll learn …

sudoku game using html CSS and JavaScript Introduction Hello friends, you all are welcome to today’s beautiful project. Today we have made …

Drawing Chhatrapati Shivaji Maharaj Using Python Chhatrapati Shivaji Maharaj, the legendary Maratha warrior and founder of the Maratha Empire, is an inspiration …

Get Huge Discounts
More Python Projects