Pair Match: a memory game
Flip two cards at a time and find all eight pairs in as few moves as possible. Plays with the mouse or the keyboard.
- Difficulty
- Beginner
- Source size
- 200 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Mouse click Flip a card
- Arrow keys + Space Enter Move the cursor and flip
- R Deal again
On this page
What you'll learn#
- Shuffling and laying out a grid
- Turn logic: first card, second card, compare
- Timed events without blocking the game loop
- Supporting both mouse and keyboard input
- Drawing card faces with code
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download memory_game.py into any folder.
- Open a terminal in that folder and run
python memory_game.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Dealing#
The eight symbols are duplicated, shuffled with random.shuffle, and laid out in a 4 × 4 grid. Each card stores its symbol and its rectangle on screen, so clicks can be matched to cards with collidepoint.
Flipping without freezing#
When two cards don't match they must stay visible briefly. Instead of time.sleep(), which would freeze the window, the game sets wait to 0.8 seconds and counts it down in update(). While it is above zero, further clicks are ignored; when it reaches zero the two cards turn back over.
Accessible controls#
A cursor index moves with the arrow keys and wraps around the edges, and Space or Enter flips the selected card. Clicking a card also moves the cursor there, so both methods stay in sync.
Complete source code#
"""Pair Match - a Pygame.net game project (a memory card game).
Flip two cards at a time and find all eight matching pairs in as few moves
as possible. The card faces are shapes drawn with pygame.draw.
Run it: pip install pygame-ce (or: pip install pygame)
python memory_game.py
Controls: Click a card, or use the arrow keys and Space/Enter. R deals again.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import math
import random
import pygame
WIDTH, HEIGHT = 640, 480
FPS = 60
COLS, ROWS = 4, 4
CARD_W, CARD_H, GAP = 110, 92, 14
LEFT = (WIDTH - (COLS * CARD_W + (COLS - 1) * GAP)) // 2
TOP = 70
REVEAL_TIME = 0.8 # seconds a mismatched pair stays face up
BG = (16, 26, 48)
BACK = (36, 87, 166)
FACE = (240, 244, 250)
INK = (21, 35, 63)
WHITE = (230, 236, 247)
CURSOR = (244, 197, 49)
SYMBOLS = [
("circle", (232, 93, 82)), ("square", (91, 147, 230)), ("triangle", (90, 170, 90)), ("diamond", (240, 140, 64)),
("star", (200, 160, 20)), ("ring", (170, 120, 230)), ("cross", (40, 160, 170)), ("bars", (200, 80, 140)),
]
def draw_symbol(surface, kind, color, center, size=26):
x, y = center
if kind == "circle":
pygame.draw.circle(surface, color, center, size)
elif kind == "square":
pygame.draw.rect(surface, color, (x - size, y - size, size * 2, size * 2), border_radius=4)
elif kind == "triangle":
pygame.draw.polygon(surface, color, [(x, y - size), (x + size, y + size), (x - size, y + size)])
elif kind == "diamond":
pygame.draw.polygon(surface, color, [(x, y - size), (x + size, y), (x, y + size), (x - size, y)])
elif kind == "star":
pts = []
for i in range(10):
r = size if i % 2 == 0 else size * 0.45
a = math.pi / 2 + i * math.pi / 5
pts.append((x + math.cos(a) * r, y - math.sin(a) * r))
pygame.draw.polygon(surface, color, pts)
elif kind == "ring":
pygame.draw.circle(surface, color, center, size, 8)
elif kind == "cross":
pygame.draw.line(surface, color, (x - size, y - size), (x + size, y + size), 10)
pygame.draw.line(surface, color, (x + size, y - size), (x - size, y + size), 10)
elif kind == "bars":
for i in range(3):
pygame.draw.rect(surface, color, (x - size, y - size + i * 19, size * 2, 11), border_radius=3)
class Card:
def __init__(self, symbol, rect):
self.symbol = symbol
self.rect = rect
self.face_up = False
self.matched = False
class Game:
def __init__(self, seed=None):
self.rng = random.Random(seed)
self.font = pygame.font.Font(None, 32)
self.big = pygame.font.Font(None, 56)
self.best = None
self.deal()
def deal(self):
symbols = SYMBOLS * 2
self.rng.shuffle(symbols)
self.cards = []
for i, sym in enumerate(symbols):
c, r = i % COLS, i // COLS
rect = pygame.Rect(LEFT + c * (CARD_W + GAP), TOP + r * (CARD_H + GAP), CARD_W, CARD_H)
self.cards.append(Card(sym, rect))
self.open = [] # indexes of face-up, unmatched cards
self.wait = 0.0
self.moves = 0
self.cursor = 0
self.time = 0.0
self.won = False
def flip(self, index):
card = self.cards[index]
if self.won or card.face_up or card.matched or self.wait > 0 or len(self.open) == 2:
return
card.face_up = True
self.open.append(index)
if len(self.open) == 2:
self.moves += 1
a, b = (self.cards[i] for i in self.open)
if a.symbol == b.symbol:
a.matched = b.matched = True
self.open.clear()
if all(c.matched for c in self.cards):
self.won = True
self.best = self.moves if self.best is None else min(self.best, self.moves)
else:
self.wait = REVEAL_TIME
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for i, card in enumerate(self.cards):
if card.rect.collidepoint(event.pos):
self.cursor = i
self.flip(i)
elif event.type == pygame.KEYDOWN:
c, r = self.cursor % COLS, self.cursor // COLS
if event.key == pygame.K_LEFT:
c = (c - 1) % COLS
elif event.key == pygame.K_RIGHT:
c = (c + 1) % COLS
elif event.key == pygame.K_UP:
r = (r - 1) % ROWS
elif event.key == pygame.K_DOWN:
r = (r + 1) % ROWS
elif event.key in (pygame.K_SPACE, pygame.K_RETURN):
if self.won:
self.deal()
return
self.flip(self.cursor)
elif event.key == pygame.K_r:
self.deal()
return
self.cursor = r * COLS + c
def update(self, dt):
if not self.won:
self.time += dt
if self.wait > 0:
self.wait -= dt
if self.wait <= 0:
for i in self.open:
self.cards[i].face_up = False
self.open.clear()
self.wait = 0.0
def draw(self, surface):
surface.fill(BG)
surface.blit(self.font.render(f"Moves {self.moves}", True, WHITE), (LEFT, 24))
best = "-" if self.best is None else str(self.best)
info = self.font.render(f"Time {int(self.time)}s Best {best}", True, WHITE)
surface.blit(info, (WIDTH - LEFT - info.get_width(), 24))
for i, card in enumerate(self.cards):
if card.face_up or card.matched:
pygame.draw.rect(surface, FACE, card.rect, border_radius=10)
draw_symbol(surface, card.symbol[0], card.symbol[1], card.rect.center)
if card.matched:
pygame.draw.rect(surface, (90, 170, 90), card.rect, 3, border_radius=10)
else:
pygame.draw.rect(surface, BACK, card.rect, border_radius=10)
pygame.draw.rect(surface, (91, 147, 230), card.rect.inflate(-14, -14), 2, border_radius=6)
if i == self.cursor:
pygame.draw.rect(surface, CURSOR, card.rect.inflate(8, 8), 3, border_radius=12)
if self.won:
shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
shade.fill((0, 0, 0, 160))
surface.blit(shade, (0, 0))
t = self.big.render(f"All pairs in {self.moves} moves!", True, CURSOR)
surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 16)))
h = self.font.render("Press Space to deal again", True, WHITE)
surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 34)))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pair Match - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = clock.tick(FPS) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Add a 6 × 6 board option with more symbols.
- Add a two-player mode where players take turns and score pairs.
- Animate card flips by scaling the card's width down and up.
- Show a star rating based on the number of moves.
- Use your own pixel art for card faces.