create a memory game
- User
create a memory game
- Assistant
create a memory game
Certainly! Below is a simple implementation of a memory matching game (also known as the "Concentration" game) using Python's tkinter module for the graphical user interface. In this game, players flip over pairs of cards to find matching pairs.
Note: Before running the code, ensure you have Python installed on your system. This code uses the standard tkinter library, which comes pre-installed with most Python distributions.
import tkinter as tk
import random
class MemoryGame:
def __init__(self, root):
self.root = root
self.root.title("Memory Game")
# Create a list of symbols (pairs)
self.symbols = ['🍎', '🍌', '🍓', '🍇', '🍒', '🍍', '🥝', '🍉'] * 2
random.shuffle(self.symbols)
self.buttons = []
self.first = None
self.lock = False # To prevent clicking during checks
self.create_widgets()
def create_widgets(self):
index = 0
for row in range(4):
for col in range(4):
button = tk.Button(self.root, text='', font=('Arial', 24), width=4, height=2,
command=lambda idx=index: self.on_button_click(idx))
button.grid(row=row, column=col)
self.buttons.append(button)
index += 1
def on_button_click(self, index):
if self.lock:
return
button = self.buttons[index]
if button['text'] == '': # If the button is not already revealed
button['text'] = self.symbols[index]
button.update_idletasks()
if self.first is None:
self.first = index
else:
if self.symbols[self.first] == self.symbols[index]:
# Match found
self.first = None
else:
# Not a match
self.lock = True
self.root.after(1000, self.hide_buttons, self.first, index)
self.first = None
def hide_buttons(self, idx1, idx2):
self.buttons[idx1]['text'] = ''
self.buttons[idx2]['text'] = ''
self.lock = False
def main():
root = tk.Tk()
game = MemoryGame(root)
root.mainloop()
if __name__ == '__main__':
main()
Explanation:
self.symbols: A list containing pairs of symbols (emojis in this case), which are shuffled randomly.self.buttons: A list to hold references to the button widgets.self.first: Keeps track of the first flipped card in a pair.self.lock: A boolean flag to prevent additional button clicks while checking for a match.How to Run the Game:
Copy the code into a file named memory_game.py.
Open a terminal or command prompt and navigate to the directory containing the file.
Run the game using the command:
python memory_game.py
Gameplay Instructions:
Customizations:
self.symbols list. You can use letters, numbers, or other emojis.create_widgets method to change the size of the game board. Remember to adjust the symbols list accordingly so that there are pairs for each button.Learning Outcomes:
Building this game helps you understand:
tkinter.Feel free to ask if you need further assistance or want to explore additional features!
Not yet included in a published release.