Hi I am having a strange problem with my leaderboard in Python. I have the player score variable being written to the file, this usually works however sometimes it just writes 0 instead of the number they scored. This only happens occasionally but it needs fixed. I think it has something to do with the delay used before setting playerscore = 0 but I am not sure what to change to fix it. Code below.
with open('Leaderboard.csv', 'a', newline='') as filepath:
a = csv.writer(filepath, delimiter=',')
data = [[PlayerScore, player_name]]
a.writerows(data)
f = open('Leaderboard.csv')
csv_f = csv.reader(f)
name = []
for row in csv_f:
name.append(row)
f.close()
print(PlayerScore)
# set PlayerScore to 0
pygame.time.delay(100)
PlayerScore = 0
Try this:
import csv
PlayerScore = 25
player_name = 'Fry'
# Append to the csv.
with open('Leaderboard.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow((PlayerScore, player_name))
# Read the csv.
with open('Leaderboard.csv', 'r', newline='') as file:
score_list = list(csv.reader(file))
for row in score_list:
print(row)
# Afterwards reset the score and name if you have to.
PlayerScore = 0
player_name = ''
Don't forget to convert the scores from strings to ints (or floats) if you want to sort them correctly, otherwise they would get sorted lexicographically.