|
| 1 | +import random |
| 2 | +import os |
| 3 | + |
| 4 | + |
| 5 | +def clear_screen(): |
| 6 | + """Clear the terminal screen.""" |
| 7 | + os.system('cls' if os.name == 'nt' else 'clear') |
| 8 | + |
| 9 | + |
| 10 | +def create_board(pairs=8): |
| 11 | + """Create a board with matching pairs.""" |
| 12 | + symbols = list(range(1, pairs + 1)) * 2 |
| 13 | + random.shuffle(symbols) |
| 14 | + return symbols, [False] * len(symbols) |
| 15 | + |
| 16 | + |
| 17 | +def display_board(symbols, revealed, selected): |
| 18 | + """Display the current board state.""" |
| 19 | + clear_screen() |
| 20 | + print("\nMemory Card Pairs - Match all pairs!\n") |
| 21 | + for i in range(len(symbols)): |
| 22 | + if revealed[i] or i in selected: |
| 23 | + print(f"[{symbols[i]:2}]", end=" ") |
| 24 | + else: |
| 25 | + print(f"[{i:2}]", end=" ") |
| 26 | + if (i + 1) % 4 == 0: |
| 27 | + print() |
| 28 | + print() |
| 29 | + |
| 30 | + |
| 31 | +def get_input(prompt, max_val): |
| 32 | + """Get valid input from user.""" |
| 33 | + while True: |
| 34 | + try: |
| 35 | + val = int(input(prompt)) |
| 36 | + if 0 <= val < max_val: |
| 37 | + return val |
| 38 | + print(f"Enter a number between 0 and {max_val - 1}") |
| 39 | + except ValueError: |
| 40 | + print("Invalid input. Please enter a number.") |
| 41 | + |
| 42 | + |
| 43 | +def play_game(): |
| 44 | + """Main game logic.""" |
| 45 | + symbols, revealed = create_board() |
| 46 | + attempts = 0 |
| 47 | + matches = 0 |
| 48 | + |
| 49 | + while matches < len(symbols) // 2: |
| 50 | + display_board(symbols, revealed, []) |
| 51 | + print(f"Attempts: {attempts} | Matches: {matches}/{len(symbols) // 2}") |
| 52 | + |
| 53 | + first = get_input("Select first card: ", len(symbols)) |
| 54 | + while revealed[first]: |
| 55 | + print("Card already matched! Choose another.") |
| 56 | + first = get_input("Select first card: ", len(symbols)) |
| 57 | + |
| 58 | + display_board(symbols, revealed, [first]) |
| 59 | + |
| 60 | + second = get_input("Select second card: ", len(symbols)) |
| 61 | + while second == first or revealed[second]: |
| 62 | + if second == first: |
| 63 | + print("Choose a different card!") |
| 64 | + else: |
| 65 | + print("Card already matched! Choose another.") |
| 66 | + second = get_input("Select second card: ", len(symbols)) |
| 67 | + |
| 68 | + display_board(symbols, revealed, [first, second]) |
| 69 | + attempts += 1 |
| 70 | + |
| 71 | + if symbols[first] == symbols[second]: |
| 72 | + print("\nMatch found! ✓") |
| 73 | + revealed[first] = revealed[second] = True |
| 74 | + matches += 1 |
| 75 | + else: |
| 76 | + print("\nNo match. Try again.") |
| 77 | + |
| 78 | + input("Press Enter to continue...") |
| 79 | + |
| 80 | + display_board(symbols, revealed, []) |
| 81 | + print(f"\nCongratulations! You won in {attempts} attempts!") |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + play_game() |
0 commit comments