Usually in multiplayer games , Every player has his own score , The highest score will be the best record of the game . This article , Learn how to record the highest score :( To simplify the code , In this paper, the method of file is adopted , Only local score is recorded , After understanding the principle , You can save scores in the cloud or in a database , It's possible to support more players ).

In the first Create a new constant in :

HIGH_SCORE_FILE = "../data/high_score.txt"

The directory structure is shown in the figure below :

then in , Define a load_data function , Load the contents of this file :

 def load_data(self):
# Highest score of loading history
file_path = path.join(self.dir, HIGH_SCORE_FILE)
if path.exists(file_path):
with open(file_path, "r") as f:
self.high_score = int(
self.high_score = 0

Pay attention to exception handling here ( Because files can be locked , Or not )

On initialization , Call this function , Load the highest score in history :

 def __init__(self):
self.screen = pg.display.set_mode(SIZE)
self.clock = pg.time.Clock()
self.running = True
self.playing = False
self.font_name = FONT_NAME
# The highest score
self.high_score = 0
self.score = 0
self.dir = path.dirname(__file__)
# Load the highest score in history

Start screen , Plus the highest score in history :

 def show_start_screen(self):
self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT * 0.4)
self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH / 2, HEIGHT * 0.55)
self.draw_text("Press a key to play", 20, WHITE, WIDTH / 2, HEIGHT * 0.7)
# Show the highest score
self.draw_text("High Score: " + str(self.high_score), 20, WHITE, WIDTH / 2, 15)

At the end of the game , If there's a new score record , Save to file :

 def show_go_screen(self):
self.draw_text("GAME OVER", 48, WHITE, WIDTH / 2, HEIGHT * 0.4)
self.draw_text("Score: " + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT * 0.55)
self.draw_text("Press a key to play again", 20, WHITE, WIDTH / 2, HEIGHT * 0.7)
# If there's a new score , preserved
if self.score > self.high_score:
self.high_score = self.score
self.draw_text("New High Score: " + str(self.high_score), 28, WHITE, WIDTH / 2, 25)
with open(path.join(self.dir, HIGH_SCORE_FILE), "w") as f:
self.draw_text("High Score: " + str(self.high_score), 20, WHITE, WIDTH / 2, 15) pg.display.update()

github Source code address :

pygame-KidsCanCode series jumpy-part8- Record more related articles with the highest score in history

  1. Map Tool series -06- A historical data processing tool for replacing business tax with value-added tax

    all cs The end tool integrates a tool panel - open (IE) Map Tool series -01-Map Code generation tool description Map Tool series -02- Data migration tool instructions Map Tool series -03- Code generation BySQl Instructions for use of tools Map ...

  2. history Clear history or history Don't record historical commands

    # vi ~/.bash_history Clear the records , And exit the current shell # exit( Be sure to exit the current shell) # history 1 vi ~/.bash_history 2 histor ...

  3. Windows7 Unable to run history command. Problem solved

    Windows7 Unable to run history command , Every time you need to manually type the command , The solution is as follows : 1. Right click in the taskbar , choice " attribute " menu : 2. In the pop-up box "[ Start ] menu " The privacy area of the tab ...

  4. be based on jquery Can query multi-level select Control ( Can record historical choices )

    One . Function and use The company has functional requirements , And a control introduced by the code , It's hard to find a control that completely matches on the Internet , It's better to write one yourself than to spend time searching , So I wrote one in my spare time   Control function :1. You can enter the query manually , You can also click the drop-down box to query , ...

  5. Python+Django+SAE Series of tutorials 13-----MySQL Addition of records \ Delete \ Change

    After building the database , Let's make a simple watch (person_classroom) The addition of . Delete . The operation of the change . First of all, we set up a template for the added page Classroom_Add.html( Join the form ) And put it in Bid ...

  6. STM32F Series MCU Debug record

    1.RTC To configure Adjust one RTC, At first, it was running normally , The set time is the same as the read time . But a new chip appeared to read the wrong year , Debugging found that it is RTC When setting, some parameters are left out . T_S32 DRIVER_ ...

  7. Imitate the lottery turntable , And use cookie Record the number of times in history

    I made a small game to imitate the lottery turntable , Simple code , The rule is that there are only three draws , And the browser will record the number of sweepstakes , The code is as follows <!DOCTYPE html> <html> <head ...

  8. C# 9.0 New features detailed explanation Series 5 : Record (record) and with expression

    1 Background and motivation The core idea of traditional object-oriented programming is that an object has a unique identifier , The representation is object reference , Encapsulates the state of attributes that can be changed at any time , If you change the state of an attribute , This object is still the same object , The object reference does not change because of the state change , ...

  9. zookeeper The second series —zookeeper history

    Zookeeper What is it? ? Zookeeper It's a distributed one , Open source distributed application coordination service , yes Google Of Chubby An open source version of . It is software that provides consistent services for distributed applications , The features provided include : Configuration service ...

Random recommendation

  1. Regular expressions preg_replace In the middle of danger /e Security vulnerabilities caused by modifiers

    mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit]) /e To make preg_rep ...

  2. JavaScript Grammatical norms

    The recommended JavaScript Coding standards read 247  Comment on 0  like 0 As a front-end developer , I believe everyone uses the original more or less JavaScript, It's just because there are so many people using it , The coding styles are various , And irregular ...

  3. BZOJ 4423: [AMPPZ2013]Bytehattan

    Sol Dual graphs + Union checking set . Very good thinking , Convert a grid graph into a dual graph , Delete an edge from the original image , It's equivalent to connecting an edge in a dual graph ( In fact, the grid points are connected to each other ), Every time you add a border, you can use it and check and maintain it . Oh, yes. , Also note that the boundary is just outside the mesh ...

  4. Unity UGUI RectTransform The illustration

    UGUI RectTransform.Unity RectTransform Detailed explanation The first:look look API. ...

  5. JSON turn Model Internal implementation parsing

    One . Ideas : 1. Get all the attributes and their types through the model type 2. To get json To deal with . Type processing 3. Consider the inconsistency between dictionary key values and model attribute names 4. add to code For filing 5. Add JSON Turn Dictionary . Dictionary transfer JSON. ...

  6. Ubuntu Set to command line login

    root@ubuntu:~# vi /etc/default/grub Change : #GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" GRUB_CMD ...

  7. OpenStack Operation and maintenance ( Two ):OpenStack Fault and maintenance of computing nodes

    1. Planned maintenance give an example : You need to upgrade the hardware configuration of a computing node , It is necessary to migrate the virtual machine on the computing node and then operate it , There are two cases . 1.1 The cloud system uses shared storage a. Get the list of virtual machines :nova list --ho ...

  8. Statemnet and PerparedStstemnent What are the differences

    Statement and PreparedStatement The relationship and difference between .      Relationship :PreparedStatement Inherited from Statement, It's all interfaces      difference :PreparedStat ...

  9. sed and awk brief introduction

    What is? sed and awk         sed and awk yes Linux Data processing tools in the environment , It can complete the function of adding, deleting, modifying and querying data .         sed It is processed in line end units ,awk Data is processed in fields . se ...

  10. nginx.conf Reading

    Usually we need to configure nginx.conf Or configure the configuration file of the subproject , So we need to understand the meaning of each parameter in it , Let's take an example ( There are notes ) # Run the user user www-data; # Start the process , Usually set to and ...