Leaderboard

leaderboard-mario

Before completing this challenge you will need to make sure you have already completed a game or a quiz in Python with a scoring system.

You will then add a leaderboard functionality to your existing game or quiz in order to:

  • Store the player score at the end of the game,
  • Add an option for the player to view the leaderboard showing the ten highest scores sorted in descending order.

For this challenge you will create a leaderboard using a text file. The leaderboard.txt file will use the following format:

player_name;score;

You can download this example file:

TextFileleaderboard.txt

In order to complete this challenge you can read more about file handling techniques using Python, including how to append data at the end of a text file and how to read and extract data from a text file.

Storing New Scores

Our first step, is to store a new leaderboard entry at the end of the text file. This could would be needed once the player has completed the game/quiz.

The following code would be used to append the username and the score at the end of the leaderboard.txt file.

import random
username = input("Enter username:")
score = random.randint(0,2000) #Here we don't have a game or a quiz, so let's generate a random score instead.

file = open("leaderboard.txt","a")  
file.write(username + ";"+str(score)+";"+"\n")  
file.close()  

Reading, Sorting and Displaying the Leaderboard

Before displaying the leaderboard on screen, we need to sort it in descending order of scores (highest to lowest). To do so we will first extract all the entries from the leaderboard.txt file and store these into a list using the following code:

file = open("leaderboard.txt","r")  
#Prepare the list (empty list to start with)  
scores = []  
  
#Read through the text file line by line  
for eachLine in file:  
   #Extract the data from the text file  
   splitData=eachLine.split(";")  
   if len(splitData)==3:  
      username = splitData[0]  
      userscore = int(splitData[1])  
      #Append this data to the list of scores  
      scores.append([username,userscore])  
  
file.close()  

Now that we have loaded all the entries from the leaderboard.txt file into a list called scores, we can sort this list in descending order of scores, using the following code:

#Sort the list of scores in DESCENDING order  
sortedScores = sorted(scores,key=lambda sort: sort[1], reverse=True)  

To only keep the top 10 scores we will slice the sorted list to the top 10 scores.

#only keep the top 10 scores:  
del sortedScores[10:] 

The final step is to display these 10 top scores on screen:

#Output top 10 scores  
for score in sortedScores:  
   print(score[0] + ": " + str(score[1])) 

Python Code

Let’s test this code. To make our program easier to read we have used the code provided below to create our own functions storeScore() to append a new score to the leaderboard file and displayLeaderboard() to extract data from the learberoard.txt file, sort all entries in descending order of score, and display the top 10 scores.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 3.8 / 5. Vote count: 13

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: ,