首页 > 解决方案 > 我正在尝试在我的掷骰子游戏中实现排行榜系统,但我所有的尝试都失败了,有没有办法做到这一点?

问题描述

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 名的排行榜上。如果有人可以提供帮助,非常感谢。

标签: pythonpickleleaderboardshelve

解决方案


推荐阅读