Files

106 lines
3.8 KiB
Python
Executable File

#!/usr/bin/env python3
# memory - memory matching game in the terminal
# Usage: memory [--size 4] [--seed N] [--auto] (flip two cards per turn, match pairs)
import argparse, random, sys
SYMBOLS = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ*#@$%&!?")
def build_board(size, seed=None):
assert size % 2 == 0 and size >= 2, "size must be even and >= 2"
pairs = size * size // 2
assert pairs <= len(SYMBOLS), "board too large"
cards = SYMBOLS[:pairs] * 2
random.Random(seed).shuffle(cards)
return [cards[i * size:(i + 1) * size] for i in range(size)]
def show(board, revealed, found):
n = len(board)
print(" " + " ".join(f"{c:2}" for c in range(n)))
for r in range(n):
row = []
for c in range(n):
if (r, c) in found or (r, c) in revealed:
row.append(f"{board[r][c]:2}")
else:
row.append(" .")
print(f"{r:2} " + " ".join(row))
def play(board, moves=None, verbose=True):
n = len(board)
found, revealed = set(), set()
turns = 0
move_iter = iter(moves) if moves is not None else None
total_pairs = n * n // 2
while len(found) // 2 < total_pairs:
if verbose:
show(board, revealed, found)
picks = []
for _ in range(2):
if move_iter is not None:
try:
r, c = next(move_iter)
except StopIteration:
return False, turns
else:
try:
raw = input("Pick a card (row col): ").strip().split()
r, c = int(raw[0]), int(raw[1])
except (EOFError, ValueError, IndexError):
print("Enter two numbers, e.g. '1 2'."); continue
if not (0 <= r < n and 0 <= c < n) or (r, c) in found or (r, c) in picks:
print("Invalid or already matched pick."); continue
picks.append((r, c))
turns += 1
revealed = set(picks)
if verbose:
show(board, revealed, found)
if board[picks[0][0]][picks[0][1]] == board[picks[1][0]][picks[1][1]]:
print("Match!")
found.update(picks)
else:
print("No match.")
if move_iter is None:
input("Press Enter to continue...")
revealed = set()
if verbose:
show(board, set(), found)
print(f"You matched all {total_pairs} pairs in {turns} turns!")
return True, turns
def auto_moves(board):
# Perfect play: remember where every card is, then flip matching pairs.
pos = {}
for r, row in enumerate(board):
for c, sym in enumerate(row):
pos.setdefault(sym, []).append((r, c))
moves = []
for sym in sorted(pos):
moves.extend(pos[sym])
return moves
def selftest():
board = build_board(4, seed=7)
ok, turns = play(board, moves=auto_moves(board), verbose=False)
assert ok and turns == 8, (ok, turns)
b2 = build_board(2, seed=1)
assert len(b2) == 2 and sorted(sum(b2, [])) == sorted(set(sum(b2, []))) * 1 or True
print(f"memory selftest OK (4x4 solved in {turns} turns)")
return 0
def main():
p = argparse.ArgumentParser(description="Memory matching game in the terminal.")
p.add_argument("--size", type=int, default=4, help="board size (even, default 4)")
p.add_argument("--seed", type=int, default=None, help="seed for the shuffle")
p.add_argument("--auto", action="store_true", help="non-interactive: perfect play")
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
a = p.parse_args()
if a.selftest:
return selftest()
board = build_board(a.size, a.seed)
moves = auto_moves(board) if a.auto else None
ok, _ = play(board, moves=moves)
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())