summaryrefslogtreecommitdiff
path: root/src/sliceitoff/hiscores
diff options
context:
space:
mode:
authorViljami Ilola <+@hix.fi>2024-03-28 13:54:00 +0200
committerViljami Ilola <+@hix.fi>2024-03-28 13:54:00 +0200
commitf502b21183d307fcab9b353aa18609d15c3547f1 (patch)
treed071b60ce9893ebc3086cee73f64e17774ad2c7b /src/sliceitoff/hiscores
parentda2bb3d8e7dcd7f7f0a0c2d2e214b422350d1993 (diff)
hiscores: loading, saving, screen
Diffstat (limited to 'src/sliceitoff/hiscores')
-rw-r--r--src/sliceitoff/hiscores/__init__.py1
-rw-r--r--src/sliceitoff/hiscores/hiscores.py55
2 files changed, 56 insertions, 0 deletions
diff --git a/src/sliceitoff/hiscores/__init__.py b/src/sliceitoff/hiscores/__init__.py
new file mode 100644
index 0000000..f3d7811
--- /dev/null
+++ b/src/sliceitoff/hiscores/__init__.py
@@ -0,0 +1 @@
+from .hiscores import HiScores
diff --git a/src/sliceitoff/hiscores/hiscores.py b/src/sliceitoff/hiscores/hiscores.py
new file mode 100644
index 0000000..098f0e3
--- /dev/null
+++ b/src/sliceitoff/hiscores/hiscores.py
@@ -0,0 +1,55 @@
+import os
+
+MAX_HIGHSCORES = 20
+
+class HiScores:
+ def __init__(self):
+ self.table=[]
+ self.config_filename = os.path.join(
+ os.getenv('HOME'),
+ ".config",
+ "sliceitoffrc")
+ if not os.path.isfile(self.config_filename):
+ self.table=[(0,"") for _ in range(MAX_HIGHSCORES)]
+ return
+ with open(self.config_filename, "r") as config_file:
+ for line in config_file:
+ option, value = line.split('=')
+ if option == 'hiscore':
+ score, name = value.split('!')
+ self.add(int(score.strip()),name.strip())
+ if len(self.table)<MAX_HIGHSCORES:
+ self.table+=[(0,"") for _ in range(MAX_HIGHSCORES-len(self.table))]
+
+ def add(self, score, initials):
+ self.table.append( (score, initials) )
+ self.table.sort(reverse=True)
+ self.table = self.table[:MAX_HIGHSCORES]
+
+ def high_enough(self, score):
+ return self.table[-1][0] < score
+
+ def __del__(self):
+ oldlines=[]
+
+ if os.path.isfile(self.config_filename):
+ with open(self.config_filename, "r") as config_file:
+ for line in config_file:
+ option, _ = line.split('=')
+ if option != 'hiscore':
+ oldlines.append(line)
+
+ with open(self.config_filename, 'w') as config_file:
+ config_file.writelines(oldlines)
+ for score, name in self.table:
+ config_file.write(f"hiscore={score}!{name}\n")
+
+ def __str__(self):
+ text = " HIGH SCORES!!\n\n"
+ half = len(self.table)//2
+ for i in range(half):
+ text += (
+ f"{self.table[i][1]:<4s} {self.table[i][0]:08} "
+ f"{self.table[i+half][1]:<4s} "
+ f"{self.table[i+half][0]:08}\n")
+ return text