我将不胜感激我的家庭作业 - 这是一个简单的课程程序,应该检查文件,如果它存在,它会读取文件,并将数据加载到程序中,这样你就可以列出分数,并添加更多。它应该只保留前5名的分数。
然后,当您关闭程序(通过选择选项 0)时,它应该将前 5 个分数写入scores.txt
文件。我想我让它正常工作,我只是无法让程序scores
正确读取和填充文件。
到目前为止,这是我的代码:
scores = []
#Check to see if the file exists
try:
file = open("scores.txt")
for i in range(0, 5):
name = file.readline()
score = file.readline()
entry = (score, name)
scores.append(entry)
scores.sort()
scores.reverse()
scores = scores[:5]
file.close()
except IOError:
print "Sorry could not open file, please check path."
choice = None
while choice != "0":
print """
High Scores 2.0
0 - Quit
1 - List Scores
2 - Add a Score
"""
choice = raw_input("Choice: ")
print ""
# exit
if choice == "0":
print "Good-bye."
file = open("scores.txt", "w+")
#I kinda sorta get this now... kinda...
for entry in scores:
score, name = entry
file.write(name)
file.write('\n')
file.write(str(score))
file.write('\n')
file.close()
# display high-score table
elif choice == "1":
print "High Scores\n"
print "NAME\tSCORE"
for entry in scores:
score, name = entry
print name, "\t", score
# add a score
elif choice == "2":
name = raw_input("What is the player's name?: ")
score = int(raw_input("What score did the player get?: "))
entry = (score, name)
scores.append(entry)
scores.sort()
scores.reverse()
scores = scores[:5] # keep only top 5 scores
# some unknown choice
else:
print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")