如果你能帮我完成家庭作业,我会很感激的-这是一个简单的班级程序,它应该检查一个文件,如果它存在,它会读取文件,并将数据加载到程序中,这样你就可以列出分数,并添加更多的分数。它应该只保留前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.")