-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathranking.py
More file actions
67 lines (55 loc) · 2.12 KB
/
Copy pathranking.py
File metadata and controls
67 lines (55 loc) · 2.12 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
from os import path
import datetime
import json
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
from configuration.setting import Settings
class Ranking:
def __init__(self):
root = Tk()
root.withdraw()
self.settings = Settings()
self.ranking_file = self.settings.ranking_file
self.max_ranking_list = self.settings.max_ranking_list
self.records = self.read_record()
def read_record(self):
if not path.exists(self.ranking_file):
return []
with open(self.ranking_file, 'r', encoding='utf-8') as fp:
records = json.load(fp)
return records
def get_ranking(self, new_score):
if not self.records:
return 1
score_list = []
for record in self.records:
score = record.get('score', None)
if score and score not in score_list:
score_list.append(score)
score_list.sort(reverse=True)
ranking = 1
for score in score_list:
if new_score >= score:
break
else:
ranking += 1
#
return ranking
def get_ranking_list(self):
sorted_records = sorted(self.records, key=lambda k: (k.get('score', 1)), reverse=True)
return sorted_records[:self.max_ranking_list]
def save_record(self, name, score):
new_record = {"name": name, "score": score, "date": datetime.datetime.now().strftime('%m-%d %H:%M')}
self.records.append(new_record)
with open(self.ranking_file, 'w', encoding='utf-8') as fp:
json.dump(self.records, fp, indent=4, ensure_ascii=False)
def add_new_record(self, score):
ranking = self.get_ranking(score)
prompt_string = "得分: " + str(score) + \
"\n排名: " + str(ranking) + \
"\n名字: "
name = simpledialog.askstring(title="保存记录", prompt=prompt_string, initialvalue="")
if name:
messagebox.showinfo(title="提示", message="感谢您的参与!")
self.save_record(name, score)