Part 17: Store scores!

17_gamescoresaved

How do you store scores of the game for deciding who is the winner post all the levels have been won against many players? You can use text files to store the scores on the hard disk.

The only change for this is in the code where the game over screen code is. We do this because we save only the number of footballs that disappear when the game is over, which is incidentally the number of walls we create.
This is just to illustrate creating and saving files and is a silly example for scores.
Code (the changes are in BOLD):

GAMEOVER = "Game Over"
    FONTNAME = 'freesansbold.ttf'
    GAMEOVERTXTCOLOR = (150, 150, 150)
    CENTERSCREENPOS = (250, 250)
    SCOREFILENAME = "gamescores.txt"
    FILEMODE = "w"
    FILETEXT = "Cannons burst = {}"
    ERRORMSG = "could not handle file"
    if(len(wall_group.sprites()) == 0):
        print("game over")
        try:
            #delete the file
            save_file = open(SCOREFILENAME, FILEMODE)
            save_file.write(FILETEXT.format(NOOFWALLS))
            save_file.close()
        except IOError:
            print(ERRORMSG)
        SCREEN.fill(BLACK)
        font = pygame.font.Font(FONTNAME, 30)
        text_surface = font.render(GAMEOVER, True, GAMEOVERTXTCOLOR)
        text_rect = text_surface.get_rect()
        text_rect.center = CENTERSCREENPOS
        SCREEN.blit(text_surface, text_rect)
        pygame.display.update()
        pygame.time.wait(5000)
        pygame.quit()
        sys.exit()

Explanation:

  • The “try/catch” is for exception handling. Means, when there is an error in the code, in the creation of the file etc, instead of the code crashing, the control of the code is passed to the “catch” block and the code there is executed.
  • Then we open the file in “w” mode – if the file is not present it creates it and if it does, overwrite it. Write the required text into the file and close the file.
    Cannons burst = 4
     save_file = open(SCOREFILENAME, FILEMODE)
                save_file.write(FILETEXT.format(NOOFWALLS))
                save_file.close

Next challenge. For some fun, let’s add some music!Yay! Now for the last 2 to cover all aspects of pygame !