Skip to content

Commit b104bcd

Browse files
Merge pull request #254 from Kunal241207/fix/2048-high-score-path
Fix 2048 high score file path handling
2 parents e2c2457 + 51357e7 commit b104bcd

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

games/2048-Game/2048-Game.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import tkinter as tk
22
import random
33
import os
4+
from pathlib import Path
45

56
GRID_SIZE = 4
67
CELL_SIZE = 100
@@ -37,6 +38,7 @@
3738
}
3839

3940
HIGH_SCORE_FILE = "highscore.txt"
41+
HIGH_SCORE_PATH = Path(__file__).with_name(HIGH_SCORE_FILE)
4042

4143

4244
class Game2048:
@@ -76,14 +78,15 @@ def __init__(self, root):
7678
self.root.bind("<Key>", self.handle_keypress)
7779

7880
def load_high_score(self):
79-
if os.path.exists(HIGH_SCORE_FILE):
80-
with open(HIGH_SCORE_FILE, "r") as file:
81-
return int(file.read())
81+
if HIGH_SCORE_PATH.exists():
82+
try:
83+
return int(HIGH_SCORE_PATH.read_text().strip() or 0)
84+
except ValueError:
85+
return 0
8286
return 0
8387

8488
def save_high_score(self):
85-
with open(HIGH_SCORE_FILE, "w") as file:
86-
file.write(str(self.high_score))
89+
HIGH_SCORE_PATH.write_text(str(self.high_score))
8790

8891
def create_grid(self):
8992
for row in range(GRID_SIZE):

0 commit comments

Comments
 (0)