如何为一个单人游戏的文本文件中的前5名玩家创建一个简单的有序排行榜

时间:2019-01-24 13:40:41

标签: python

我要进行1个玩家测验,并且需要实施一个高分系统,该系统记录前5名得分高手的得分以及适合得分手的玩家姓名。应将其写入文本文件(.txt),如果得分更高(从1.最高得分到5.最低得分排序),则应将其覆盖。如果有人可以共享一些代码,那么我可以在我的高分系统中使用它,那将真的很有帮助。

应将经过n轮比赛的玩家从最高n分降到最低n分。它应该在txt文件中具有前5个n得分,按顺序排列。

我已经看了好几个小时的论坛,无法实现在代码中找到的代码。旁注:我根本不知道该怎么做

counter = 0
print("The songs' initials are " ,initialsofsong, " and the name of the artist is " ,randomartist)
print (randomsong)
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while counter < 3 and songnameguess != randomsong :
        songnameguess = input("Nope! Try again!")
        counter = counter + 1
if songnameguess == randomsong:
    print ("Well done!")
    if counter == 2:
        score = score + 1
    elif counter == 1:
        score = score + 3

elif counter >=3 and songnameguess != randomsong:
    print ("Sorry, you've had two chances. Come back soon!")
    print ("Game over.")
    print (score)

2 个答案:

答案 0 :(得分:2)

您可以用多种格式存储乐谱,因为json是可读且内置的,因此我将继续使用它。

score_file = r"/pat/to/score/file.json"

# at the beginning of your script: load the current scores
try:
    with open(score_file, 'r') as f:
        scores = json.load(f)
except FileNotFoundError:
    scores = {}

# (...)

# during your script: update the scores with the player's new
scores[player_name] = new_score

# (...)

# at the end of your script: store the new scores
with open(score_file, 'w+') as f:
    json.dump(scores, f)

要打印排序的分数:

scores_sorted = sorted([(p, s) for p, s in scores.items()], reverse=True, key=lambda x: x[1])
for player, score in scores_sorted:
    print(player, score)

答案 1 :(得分:0)

您可以实现一个类似的类(如果多个用户的分数相同,那么他们都在高分榜上,请参见示例):

import json

class Highscore:
    def __init__(self):
        self.highscores = None
        self.load()

    def load(self):
        """Loads highscores from a file called 'highscores.txt'"""
        try:
            with open('highscores.txt', 'r') as handle:
                text = handle.read()
                if text:
                    self.highscores = json.loads(text)
                    return
        except FileNotFoundError:
            pass
        self.highscores = {}

    def update(self, name, score):
        """Update current highscore for user and keep only top 5 users"""
        self.highscores[name] = max(score, self.highscores.get(name, 0))
        self.highscores = {n: s for n, s in self.highscores.items()
                           if s in sorted(self.highscores.values(), reverse=True)[:5]}
    def save(self):
        """Saves highscores to a file called 'highscores.txt'"""
        with open('highscores.txt', 'w') as handle:
            json.dump(self.highscores, handle)

    def clear(self):
        """Remves highscores (in memory, save is needed to clear record)"""
        self.highscores = {}

    def __str__(self):
        """Return highscores as a string"""
        return '\n'.join(
            f'{name}: {score}'
            for name, score in
            sorted(self.highscores.items(), key=lambda x: x[1], reverse=True)
        ) or 'No highscores!'

示例:

import random

highscores = Highscore()  # Loads the current highscores
highscores.clear()  # Removes them
highscores.save()  # Saves to file
highscores.load()  # Loads from file again (to make sure save worked)
print(highscores)  # prints: "No highscores!"

# Generate random scores:
for i in range(10):
    highscores.update(f'name{i}', random.randint(10, 100))

print(highscores)
# prints:
# name9: 94
# name8: 79
# name1: 62
# name6: 57
# name0: 48 Same score as below so both are kept...
# name4: 48 Same score as above so both are kept...