-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_tk.py
More file actions
348 lines (297 loc) · 10.3 KB
/
memory_tk.py
File metadata and controls
348 lines (297 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#memory_tk.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
This game is inspired by Simon.
Multilingual version
The game first shows a sequence of colors
The player try to reproduce in the same order
Each round adds a new color to the sequence (increasing the difficulty)
The player makes a mistake
Finally, a message shows the correct last color
'''
# Modules
import tkinter as tk
import random
import time
import threading
# Colors
COLORS = {
"green": "#00A74A",
"red": "#9F0F17",
"yellow": "#CCA707",
"blue": "#094A8F",
}
# Bright colors
BRIGHT = {
"green": "#00FF7F",
"red": "#FF4C4C",
"yellow": "#FFFF66",
"blue": "#4C8CFF",
}
# Name of colors in Spanish and English
COLOR_NAMES = {
"es": {
"green": "VERDE",
"red": "ROJO",
"yellow": "AMARILLO",
"blue": "AZUL",
},
"en": {
"green": "GREEN",
"red": "RED",
"yellow": "YELLOW",
"blue": "BLUE",
},
"it": {
"green": "VERDE",
"red": "ROSSO",
"yellow": "GIALLO",
"blue": "BLU",
},
"pt": {
"green": "VERDE",
"red": "VERMELHO",
"yellow": "AMARELO",
"blue": "AZUL",
}
}
# Messages and their translation
TEXT = {
"es": {
"start": "Iniciar",
"try_again": "Reintentar",
"watch": "Observa la secuencia...",
"your_turn": "Tu turno: repite la secuencia",
"good": "¡Bien hecho!",
"score": "Puntuación",
"game_over": "Fin del juego",
"correct_color": "El color correcto era:",
"language": "Idioma",
},
"en": {
"start": "Start",
"try_again": "Try Again",
"watch": "Watch the sequence...",
"your_turn": "Your turn: repeat the sequence",
"good": "Well done!",
"score": "Score",
"game_over": "Game Over",
"correct_color": "The correct color was:",
"language": "Language",
},
"it": {
"start": "Inizia",
"try_again": "Riprova",
"watch": "Guarda la sequenza…",
"your_turn": "Il tuo turno: ripeti la sequenza",
"good": "Ben fatto!",
"score": "Punteggio",
"game_over": "Fine del gioco",
"correct_color": "Il colore corretto era:",
"language": "Lingua",
},
"pt": {
"start": "Iniciar",
"try_again": "Tentar novamente",
"watch": "Observe a sequência…",
"your_turn": "Sua vez: repita a sequência",
"good": "Muito bem!",
"score": "Pontuação",
"game_over": "Fim de jogo",
"correct_color": "A cor correta era:",
"language": "Idioma",
}
}
class MemoryGame:
def __init__(self, root):
self.root = root
self.root.title("Memory Game")
# Minimum size and resizable window
self.root.minsize(350, 580)
self.root.resizable(True, True)
# Default language
self.lang = "en"
self.sequence = []
self.user_index = 0
self.is_playing = False
self.score = 0
# Select a language
self.lang_var = tk.StringVar(value="es")
lang_frame = tk.Frame(root)
lang_frame.pack(pady=5)
self.lang_label = tk.Label(lang_frame, text="")
self.lang_label.pack(side="left", padx=5)
self.radio_es = tk.Radiobutton(
lang_frame, text="Español",
variable=self.lang_var, value="es",
command=self.apply_language
)
self.radio_en = tk.Radiobutton(
lang_frame, text="English",
variable=self.lang_var, value="en",
command=self.apply_language
)
self.radio_it = tk.Radiobutton(
lang_frame, text="Italiano",
variable=self.lang_var, value="it",
command=self.change_language
)
self.radio_pt = tk.Radiobutton(
lang_frame, text="Português",
variable=self.lang_var, value="pt",
command=self.change_language
)
self.radio_es.pack(side="left")
self.radio_en.pack(side="left")
self.radio_it.pack(side="left")
self.radio_pt.pack(side="left")
# Buttons
self.buttons = {}
self.create_buttons()
# Score
self.score_label = tk.Label(root, text="", font=("Arial", 16))
self.score_label.pack(pady=10)
# Status
self.status_label = tk.Label(root, text="", font=("Arial", 14))
self.status_label.pack(pady=5)
# Second line of (game over) status
self.correct_label = tk.Label(root, text="", font=("Arial", 14))
self.correct_label.pack(pady=5)
# Start button
self.start_button = tk.Button(
root, text="", font=("Arial", 16),
command=self.start_game
)
self.start_button.pack(pady=20)
# Apply language
self.apply_language()
def apply_language(self):
self.lang = self.lang_var.get()
self.start_button.config(text=TEXT[self.lang]["start"])
self.lang_label.config(text=f"{TEXT[self.lang]['language']}:")
self.update_score()
def disable_language_selector(self):
'''Disable selector when the game is on'''
self.radio_es.config(state="disabled")
self.radio_en.config(state="disabled")
def enable_language_selector(self):
'''Enable selector when the game has started or over'''
self.radio_es.config(state="normal")
self.radio_en.config(state="normal")
def create_buttons(self):
'''Create buttons'''
frame = tk.Frame(self.root)
frame.pack(expand=True, fill="both", padx=10, pady=10)
for i in range(2):
frame.rowconfigure(i, weight=1)
frame.columnconfigure(i, weight=1)
self.buttons["green"] = tk.Button(
frame, bg=COLORS["green"],
command=lambda: self.user_press("green")
)
self.buttons["red"] = tk.Button(
frame, bg=COLORS["red"],
command=lambda: self.user_press("red")
)
self.buttons["yellow"] = tk.Button(
frame, bg=COLORS["yellow"],
command=lambda: self.user_press("yellow")
)
self.buttons["blue"] = tk.Button(
frame, bg=COLORS["blue"],
command=lambda: self.user_press("blue")
)
# Set buttons on grid
self.buttons["green"].grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
self.buttons["red"].grid(row=0, column=1, sticky="nsew", padx=5, pady=5)
self.buttons["yellow"].grid(row=1, column=0, sticky="nsew", padx=5, pady=5)
self.buttons["blue"].grid(row=1, column=1, sticky="nsew", padx=5, pady=5)
# Start of the game
def start_game(self):
if self.is_playing:
return
self.sequence = []
self.user_index = 0
self.score = 0
self.update_score()
self.status_label.config(text="")
self.correct_label.config(text="")
self.is_playing = True
# Enable language selector
self.enable_language_selector()
self.next_round()
def update_score(self):
self.score_label.config(text=f"{TEXT[self.lang]['score']}: {self.score}")
def next_round(self):
self.user_index = 0
self.sequence.append(random.choice(list(COLORS.keys()))) # random color to use
self.score = len(self.sequence) - 1
self.update_score()
self.status_label.config(text=TEXT[self.lang]["watch"], fg="black")
self.correct_label.config(text="")
# Enable language selector
self.enable_language_selector()
threading.Thread(target=self.play_sequence).start()
def play_sequence(self):
# Disable language selector
self.disable_language_selector()
time.sleep(1) # Waiting time
for color in self.sequence:
self.flash(color)
time.sleep(0.5)
self.status_label.config(text=TEXT[self.lang]["your_turn"], fg="blue")
def flash(self, color):
btn = self.buttons[color]
btn.config(bg=BRIGHT[color])
self.root.update()
time.sleep(0.3) # Time to change from bright into normal color
btn.config(bg=COLORS[color])
self.root.update()
def user_press(self, color):
if not self.is_playing:
# User is not playing right now
return
self.flash(color)
if color == self.sequence[self.user_index]:
# Right color
self.user_index += 1
if self.user_index == len(self.sequence):
self.status_label.config(text=TEXT[self.lang]["good"], fg="green")
self.root.after(600, self.next_round)
else:
self.game_over(correct_color=self.sequence[self.user_index])
# Game over
def game_over(self, correct_color):
self.is_playing = False # User is not playing right now
self.start_button.config(text=TEXT[self.lang]["try_again"])
# First line: Game Over / Fin del juego
self.status_label.config(
text=TEXT[self.lang]["game_over"],
fg="red"
)
# Second line of Game Over message
translated = COLOR_NAMES[self.lang][correct_color]
self.correct_label.config(
text=f"{TEXT[self.lang]['correct_color']} {translated}",
fg="red"
)
self.flash_all() # All colours are flashing after losing
# Enable language selector
self.enable_language_selector()
def flash_all(self):
'''All colours are flashing after losing'''
for _ in range(2):
for color in COLORS:
self.buttons[color].config(bg=BRIGHT[color])
self.root.update()
time.sleep(0.3)
for color in COLORS:
self.buttons[color].config(bg=COLORS[color])
self.root.update()
time.sleep(0.3)
### Main ###
if __name__ == "__main__":
root = tk.Tk()
game = MemoryGame(root)
root.mainloop()