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).
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
Bank Management System Using Python Django Introduction The Bank Management System V2.0.2 is a feature-rich online banking solution built using the Python …
Pharmacy Management System Using Python Django Introduction The Pharmacy Dispensing Management System is a robust and user-friendly software solution developed using Python …
Build a Quiz Game Using HTML CSS and JavaScript Introduction Hello coders, you might have played various games, but were you aware …
Emoji Catcher Game Using HTML CSS and JavaScript Introduction Hello Coders, Welcome to another new blog. In this article we’ve made a …
Typing Challenge Using HTML CSS and JavaScript Introduction Hello friends, all you developer friends are welcome to our new project. If you …
Breakout Game Using HTML CSS and JavaScript With Source Code Introduction Hello friends, welcome to today’s new blog post. All of you …