0

I am working on a simple leaderboard for a game I am making in Python 3. Below is a simplification of my problem:

I have 2 lists:

names = []
scores = []

My code asks the user for their name, which is added to names list. The score, calculated elsewhere, is added to scores list. Then I have:

leaderboardList = sorted(zip(scores, names), reverse=True)[:3]
for item in leaderboardList:
    print(item[1],":",item[0])

Which combines, sorts, and prints the top three names and scores.

for example, if I had:

names =["A","B","C","D"]
scores = [1,2,3,4]

I would get:

D : 4
C : 3
B : 2

My issue here is keeping the names and scores in the list. When the game starts, I I want it to work so that one person can play the game, and then later another person can play, and both people's scores will appear in the leaderboard.

Right now, the leaderboard only displays the person who just added their name. This is because I have defined names and scores lists as empty lists before the game starts, but if I do not do so, I get an error, as expected.

Essentially, I want the names and scores lists to not be cleared each time the program is stopped and started, so that the leaderboard keeps everyone on it. I did some research into pickle function, but I don't think that is quite the solution here and I am stuck.

rpanai
  • 12,515
  • 2
  • 42
  • 64
cal26
  • 9
  • Hi, you are looking for the ability to write the scores to non volatile memory (i.e. the disk). Look up file handling in python. The `pickle` module is of special interest to you, allowing the storage of data structures (your lists) from memory directly to the file system. Write to the file after every updation, read the file whenever your program starts up. – Aayush Mahajan Apr 12 '20 at 01:30
  • You can save the lists to a file and check for its existence when the script starts (and read them back in if it does). See [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence/4529901#4529901). – martineau Apr 12 '20 at 01:33
  • Great, I will check those out. Thanks! – cal26 Apr 12 '20 at 01:55

0 Answers0