Skip to content

Commit a353270

Browse files
committed
fix: add win detection for 2048 game
1 parent 7303e3c commit a353270

1 file changed

Lines changed: 35 additions & 2 deletions

File tree

games/2048-Game/2048-Game.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ def __init__(self, root):
8787
self.board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
8888

8989
self.game_over_label = None
90+
self.win_label = None
91+
self.game_won = False
9092

9193
self.create_grid()
9294
self.start_new_game()
@@ -146,6 +148,7 @@ def start_new_game(self):
146148
self.board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
147149
self.score = 0
148150
self.moves_left = TOTAL_MOVES
151+
self.game_won = False
149152

150153
self.add_new_tile()
151154
self.add_new_tile()
@@ -261,6 +264,9 @@ def check_game_over(self):
261264

262265
return True
263266

267+
def check_win(self):
268+
return any(2048 in row for row in self.board)
269+
264270
def handle_keypress(self, event):
265271
key = event.keysym.lower() if len(event.keysym) == 1 else event.keysym
266272
move_map = {
@@ -284,11 +290,32 @@ def handle_keypress(self, event):
284290

285291
self.update_grid()
286292

287-
# FIXED BUG:
288-
# Game over is now checked even when no movement happens
293+
if not self.game_won and self.check_win():
294+
self.you_win()
295+
return
296+
297+
# Check for game over even if no movement happens
289298
if self.check_game_over() or self.moves_left <= 0:
290299
self.game_over()
291300

301+
def you_win(self):
302+
303+
if self.game_won:
304+
return
305+
306+
self.game_won = True
307+
308+
self.root.unbind("<Key>")
309+
310+
self.win_label = tk.Label(
311+
self.root,
312+
text="🎉 YOU WIN! 🎉",
313+
font=("Arial", 24, "bold"),
314+
fg="green"
315+
)
316+
317+
self.win_label.grid(pady=10)
318+
292319
def game_over(self):
293320

294321
# Prevent duplicate labels
@@ -314,6 +341,11 @@ def restart_game(self):
314341
self.game_over_label.destroy()
315342
self.game_over_label = None
316343

344+
# Remove old win label
345+
if self.win_label is not None:
346+
self.win_label.destroy()
347+
self.win_label = None
348+
317349
self.start_new_game()
318350

319351
# Re-enable keyboard controls
@@ -325,5 +357,6 @@ def main():
325357
game = Game2048(root)
326358
root.mainloop()
327359

360+
328361
if __name__ == "__main__":
329362
main()

0 commit comments

Comments
 (0)