-1

我正在制作一个系统,当用户玩我的游戏时,它会使用用户名和密码将他们的分数与他们之前的分数进行比较。信息以以下格式存储在文本文件中:score*username*password. 我试图将它们放入不同的变量中,以便我可以将它们与其他变量进行检查。这是我正在使用的代码。问题是变量的分配不起作用,我不知道为什么

username = "hello"
password = "1234"
player_score = 40

file = open("yahtzee high scores.txt", "r")
lines = file.readlines()
file.close()
highscore = 0
highUser = ""

print(lines)
for line in lines:
    score = ""
    name = ""
    passw = ""
    findingScore = True
    findingName = False
    findingPass = False
    for i in line:
        if i != "*" and findingScore:
            score += i
        elif i != "*" and findingName:
            name += i
        elif i != "*" and findingPass:
            passw += i
        else:
            print(name)
            if findingScore:
                findingName = True
                findingScore = False
            elif findingName:
                findingName = False
                findingPass = True
            elif findingPass:
                findingPass = False
            if int(score) > highscore:

                highscore = int(score)
                highUser = name
                highPass = passw
                print(highscore)
                print(highUser)
4

2 回答 2

2

使用 json 更有效(也更容易)

使用以下作为file.json

{
    "user1": {"password":"password","high score":50},
    "user2": {"password":"password","high score":30}
}
import json

data = json.load(open('file.json', "r"))

print(data["user1"]["high score"])

#assign new score
data["user1"]["high score"] = 60

# add new user

password = "user3Password123"
score = 30

data["user3"] = {
    "password": password,
    "high score": score
}

json.dump(data, open('file.json', "w"))

该文件现在

{
    "user1": {"password":"password","high score":60},
    "user2": {"password":"password","high score":30},
    "user3": {"password": "user3Password123", "high score": 30}

}
于 2020-10-26T01:18:29.413 回答
0

原来有一个函数string.split("*")可以列出其中包含密码和用户名的列表。附言。不确定 split 函数的确切语法,但它确实存在

于 2020-11-20T15:19:34.757 回答