I am making a system in which when a user plays my game, it compares their score to what they have scored before by using a username and password. the info is stored in text file in the format: score*username*password
. I am trying to get those into different variables so that I can check them against other variables. this is the code I’m using. the problem is that the assigning of the variables doesn’t work and I cant work out why
JavaScript
x
43
43
1
username = "hello"
2
password = "1234"
3
player_score = 40
4
5
file = open("yahtzee high scores.txt", "r")
6
lines = file.readlines()
7
file.close()
8
highscore = 0
9
highUser = ""
10
11
print(lines)
12
for line in lines:
13
score = ""
14
name = ""
15
passw = ""
16
findingScore = True
17
findingName = False
18
findingPass = False
19
for i in line:
20
if i != "*" and findingScore:
21
score += i
22
elif i != "*" and findingName:
23
name += i
24
elif i != "*" and findingPass:
25
passw += i
26
else:
27
print(name)
28
if findingScore:
29
findingName = True
30
findingScore = False
31
elif findingName:
32
findingName = False
33
findingPass = True
34
elif findingPass:
35
findingPass = False
36
if int(score) > highscore:
37
38
highscore = int(score)
39
highUser = name
40
highPass = passw
41
print(highscore)
42
print(highUser)
43
Advertisement
Answer
Its much more efficient (and easy) to use json
using the following as file.json
JavaScript
1
5
1
{
2
"user1": {"password":"password","high score":50},
3
"user2": {"password":"password","high score":30}
4
}
5
JavaScript
1
21
21
1
import json
2
3
data = json.load(open('file.json', "r"))
4
5
print(data["user1"]["high score"])
6
7
#assign new score
8
data["user1"]["high score"] = 60
9
10
# add new user
11
12
password = "user3Password123"
13
score = 30
14
15
data["user3"] = {
16
"password": password,
17
"high score": score
18
}
19
20
json.dump(data, open('file.json', "w"))
21
the file is now
JavaScript
1
7
1
{
2
"user1": {"password":"password","high score":60},
3
"user2": {"password":"password","high score":30},
4
"user3": {"password": "user3Password123", "high score": 30}
5
6
}
7