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
|
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
|