Creating a high score

Creating a high score Titelbild

Highscore

Imagine you just played the perfect round of snake and want to live in that glory forever. Or maybe at the minimum you just want to save some data and information more permanently with the option to close your Python program and have that data readily available next time you start your program. Unfortunately we can’t use variables and lists to accomplish this task, but there is a library available in Python3 that can help us gain this ability. This library is called shelve (yes like the furniture in which you can put books). We can use this library to temporarily save data in a .txt file. With this functionality at our disposal, we really are able to close the Python program and retrieve the data the next time we open our program. To demonstrate how this works we have prepared a highscore program below to teach you how to implement this into your programs:

highscore.py

import shelve

scoreFile = shelve.open('score.txt')

def updateScore(newScore):
  if('score' in scoreFile):
    score = scoreFile['score']
    if(newScore not in score):
      score.insert(0, newScore)

    score.sort()
    ranking = score.index(newScore)
    ranking = len(score)-ranking
  else:
    score = [newScore]
    ranking = 1

  print(score)
  print(ranking)
  scoreFile['score'] = score
  return ranking

newScore = int(input("New HighScore: \n"))
updateScore(newScore)

After executing the program you can enter a new highscore which you will be able to see in a highscore list outputted in the terminal. We recommend you repeat that a few times and take notice of how the program handles the saved inputs. You will notice you not only can see your previous scores, but that the program is also ordering the inputs like a true highscore list.

Step for Step

In line 1 we are importing the shelve* library. In line 3 we use this library for the first time with.open(‘score.txt’)` and are defining the location we want to save all of the information we have. This is the .txt file we mentioned previously. You can also erase all data by deleting this file.

In lines 5-22 we are creating a new function with the name updateScore(). The purpose of this function is to change the score data. The only parameter for this function is the new entry for the score file, with the return value being the new ranking file.

Using this function, we first test if the list score already exists in the file in line 6. This is done using the following line of code: ’score’ in scoreFile. This basically means that when there is a variable with the name x in y, then the expression evaluates to true. If you want to find out the exact opposite then you can use not in instead of in. We need this check if we are saving values for the first time. First we save everything from the shelve in the Variable score . This will make our work with the data much more easier. In line 8 we are checking if there is already a high score with the number of points we want to enter. This method should already be familiar as it is the same construct as in line 6. If this is not the case, we will add the new score to the list. Then we need to check the ranking of the high score values. For this we first sort all numbers in the list with the function .sort(). With the function .index() we can find out where a certain element of the list is. Because this function starts counting at the wrong direction of the high score list, we also need to change that and use for this the code in line 13. .len() returns the length of a list.

In lines 15 and 16 we are dealing with the case where there is no score in the shelve. For this situation we are create the list with the name score and save to it the value of the parameter newScore in the list. Because this is the first entry, we know for sure that it is at the first position.

To check how the program is evaluating the scores for accuracy, we print the variable score and the variable ranking before we the end of the function. When you use this code in production you may remove the two lines of code.

In line 20 we are saving everything to the shelve. To do this we simply save the new content which is in the variable score to scoreList[‘score’]. After this we print the ranking in line 21.

In line 23 we are setting the Variable newScore with the input function in the terminal. The function is then called in line 24 and the parameter is the user input.

This is the end of your first shelveprogram but hopefully only the beginning of a lot of future projects in which you now have the knowledge to be able to save your data!

Highscore in Snake

A high score without a game or a competition is quite boring. It is great for a game like snake which we just built. With this the player can easily track his progress with the game and how good his score is compared to others. To implement this you first need to remove lines 18,19,23 and 24 in the highscore.py file.

In the snake.py file, you need to add the import of the highscore module in line 5.

from highscore import updateScore

And add the following code in lines 59 - 60.

ranking = updateScore(points)
matrix.show_message(str(ranking))

You may use this file and modify it as needed to also save the rankings from other games on your Pi!

Noch Fragen oder Feedback?

Bevor du eine Frage stellen kannst musst du dich zuerst Anmelden oder Regestrieren!