我正在编写一个高分系统,用户将输入一个名称和一个分数,然后程序将测试分数是否大于 high_scores 中的最低分数。如果是,将写入分数并删除最低分数。一切正常,但我注意到了一些事情。high_scores.txt
文件是这样的:
PL1 50
PL2 50
PL3 50
PL4 50
PL5 50
PL1 是添加的第一个分数,PL2 是第二个,PL3 是第三个,依此类推。然后我尝试添加另一个分数,高于所有其他分数(PL6 60),结果是程序将 PL1 指定为最低分数。添加了 PL6,删除了 PL1。这正是我想要的行为,但我不明白它是如何发生的。字典是否跟踪分配项目的时间点?这是代码:
MAX_NUM_SCORES = 5
def getHighScores(scores_file):
"""Read scores from a file into a list."""
try:
cache_file = open(scores_file, 'r')
except (IOError, EOFError):
print("File is empty or does not exist.")
return []
else:
lines = cache_file.readlines()
high_scores = {}
for line in lines:
if len(high_scores) < MAX_NUM_SCORES:
name, score = line.split()
high_scores[name] = int(score)
else:
break
return high_scores
def writeScore(file_, name, new_score):
"""Write score to a file."""
if len(name) > 3:
name = name[0:3]
high_scores = getHighScores(file_)
if high_scores:
lowest_score = min(high_scores, key=high_scores.get)
if new_score > high_scores[lowest_score] or len(high_scores) < 5:
if len(high_scores) == 5:
del high_scores[lowest_score]
high_scores[name.upper()] = int(new_score)
else:
return 0
else:
high_scores[name.upper()] = int(new_score)
write_file = open(file_, 'w')
while high_scores:
highest_key = max(high_scores, key=high_scores.get)
line = highest_key + ' ' + str(high_scores[highest_key]) + '\n'
write_file.write(line)
del high_scores[highest_key]
return 1
def displayScores(file_):
"""Display scores from file."""
high_scores = getHighScores(file_)
print("HIGH SCORES")
if high_scores:
while high_scores:
highest_key = max(high_scores, key=high_scores.get)
print(highest_key, high_scores[highest_key])
del high_scores[highest_key]
else:
print("No scores yet.")
def resetScores(file_):
open(file_, "w").close()