python - 我正在尝试在我的掷骰子游戏中实现排行榜系统,但我所有的尝试都失败了,有没有办法做到这一点?
问题描述
import shelve
import pickle
scoreFile = shelve.open('score.txt')
username = 'User1'
def updateScore(newScore):
if('score' in scoreFile):
score = scoreFile['score']
if(newScore not in score):
score.insert(0, newScore)
score.sort()
ranking = score.index(newScore)
ranking = len(score)-ranking
else:
score = [newScore]
ranking = 1
if len(score) >5:
del(score[0])
else:
pass
print(score)
print(ranking)
scoreFile['score'] = score
places = {'first':'user',
'second': 'user',
'third': 'user',
'fourth': 'user',
'fifth' : 'user'
}
if ranking ==1:
places['first']= username
elif ranking==2:
places['second'] = username
elif ranking ==3:
places['third'] = username
elif ranking == 4:
places['fourth'] = username
elif ranking ==5:
places['fifth'] = username
else:
print("not on leaderboard")
filename = "names.txt"
file = open(filename, 'wb')
pickle.dump(places, file)
return ranking
newScore = int(input("New HighScore: \n"))
updateScore(newScore)
正如您在上面看到的,我尝试使用 pickle 和 shelve 但 dict 不保存,我相信有更好的方法来解决这个问题。我需要做的就是将获胜者的积分和用户的位置以及用户的姓名一次性关联到前 5 名的排行榜上。如果有人可以提供帮助,非常感谢。
解决方案
推荐阅读
- arrays - 为什么新项目没有出现?
- html - 变换旋转(-90度)改变左边的位置
- wix - 属性初始化顺序在 WiX 中不起作用
- python - 升级 scikit-image 版本的问题
- kubernetes - 将用户平衡到 Kubernetes 中的同一节点
- reactjs - 如何在反应中使用来自 react-router dom 的 history.push?
- ruby-on-rails - Rails 6 - 开发和生产之间的 Nokogiri LoadError 冲突(x86_64-darwin 和 x86_64-linux)
- java - Jenkins 构建中嵌入式 Mongo DB 测试的 UnknownHostException
- python - 是否可以配置 AWS CodeArtifact PyPi 存储库以在 AWS MWAA 中使用?
- node.js - 多次打开和关闭队列时节点崩溃