我目前正在编写一段代码,用户根据他们在游戏中的表现得分,并且我被卡住了。任何人都可以提供一些关于如何在用户计算机上创建本地文件并检索它以便配置新的高分(如果有的话)的建议然后打印最高三个并删除其他文件以节省空间。
这是我目前的代码,但它非常需要改进:
print("Yore score is", score, "/30")
if sthighscore < score:
sthighscore = score
sthighscorename = name
print("NEW 1st HIGH SCORE: ")
print('1: ',sthighscorename, '-', sthighscore)
print("2: ", ndhighscorename, '-', ndhighscore)
print('3: ', rdhighscorename, '-', rdhighscore)
elif sthighscore >= score > ndhighscore:
ndhighscore = score
ndhighscorename = name
print("NEW 2nd HIGH SCORE: ")
print('1: ', sthighscorename, '-', sthighscore)
print("2: ", ndhighscorename, '-', ndhighscore)
print('3: ', rdhighscorename, '-', rdhighscore)
elif ndhighscore >= score > rdhighscore:
rdhighscore = score
rdhighscorename = name
print("NEW 3rd HIGH SCORE: ")
print('1: ',sthighscorename, '-', sthighscore)
print("2: ", ndhighscorename, '-', ndhighscore)
print('3: ', rdhighscorename, '-', rdhighscore)
else:
print("NO NEW HIGH SCORES :( ")
print('1: ',sthighscorename, '-', sthighscore)
print("2: ", ndhighscorename, '-', ndhighscore)
print('3: ', rdhighscorename, '-', rdhighscore)
正如您所看到的,代码还没有存储任何东西。请帮忙。
答案 0 :(得分:0)
要创建本地文件,您可以使用open()函数。您可以存储这样的分数。
print("Yore score is", score, "/30")
if sthighscore < score:
sthighscore = score
sthighscorename = name
print("NEW 1st HIGH SCORE: ")
print('1: ',sthighscorename, '-', sthighscore)
print("2: ", ndhighscorename, '-', ndhighscore)
print('3: ', rdhighscorename, '-', rdhighscore)
f=open('score.txt','w') # This will create score.txt text file
f.write('%s\n%s\n%s'%('1: '+sthighscorename+ '-'+ str(sthighscore),"2: "+ ndhighscorename+ '-'+ str(ndhighscore), '3: '+ rdhighscorename+ '-'+ str(rdhighscore)))
f.close()
您可以使用相同的步骤存储其他值。 要检索你可以使用,
f=open('score.txt','r')
data=f.read().split('\n')
print data
sthighscore=int(data[0].split()[1].split('-')[1])
sthighscorename=data[0].split()[1].split('-')[0]
ndhighscore=int(data[1].split()[1].split('-')[1])
ndhighscorename=data[1].split()[1].split('-')[0]
rdhighscore=int(data[2].split()[1].split('-')[1])
rdhighscorename=data[2].split()[1].split('-')[0]