In the previous lesson, we displayed the High Score on the game screen.
There is one small problem. If you close the game and open it again, the High Score becomes 0. This happens because variables store data only while the program is running. Professional games solve this problem by saving important information in a file. In this lesson, you will learn how to save the High Score in a text file and load it automatically whenever the game starts.
After completing this lesson, your High Score will not disappear even if you close the game.
What You’ll Build Today
At the end of this lesson,
✔ High Score will be saved automatically.
✔ High Score will load automatically when the game starts.
✔ Your game will remember the best score.
Before You Start
Create a new file inside your project folder.
Name the file:
highscore.txt
Open the file and write:
0
Save the file.
Your project folder should look like this.
Game Project
│
├── game.py
├── highscore.txt
│
├── images
│ ├── background.png
│ ├── player.png
│ ├── enemy.png
│ └── coin.png
│
└── sounds
├── coin.wav
├── gameover.wav
└── background.mp3
Step 1 : Read the High Score
When the game starts, we need to read the saved High Score.
Add this code before the game loop.
file = open("highscore.txt", "r")
high_score = int(file.read())
file.close()
Run the program.
Nothing new appears on the screen.
That’s okay.
The program has already read the High Score from the file.
How Does This Code Work?
open("highscore.txt", "r")
opens the file in Read Mode.
file.read()
reads everything stored inside the file.
Our file contains:
0
The value is read as text.
So we convert it into a number.
int(file.read())
Now our High Score becomes an integer.
Step 2 : Save a New High Score
Find this code.
if score > high_score:
high_score = score
Replace it with this.
if score > high_score:
high_score = score
file = open("highscore.txt", "w")
file.write(str(high_score))
file.close()
Now run the game.
Collect a few coins.
Create a new High Score.
Close the game.
Run the game again.
Your High Score is still there.
Congratulations!
You have successfully saved data in a file.
Understanding the Code
This line opens the file.
file = open("highscore.txt","w")
The letter w means Write Mode.
This line saves the High Score.
file.write(str(high_score))
Remember,
write() can save only text.
That’s why we convert the number into a string using str().
Finally,
file.close()
closes the file.
Always close the file after reading or writing.
Complete Working Program
Replace your previous program with the following code.
import pygame
import random
pygame.init()
pygame.mixer.init()
# Window
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Save High Score")
# Images
background = pygame.image.load("images/background.png")
player = pygame.image.load("images/player.png")
enemy = pygame.image.load("images/enemy.png")
coin = pygame.image.load("images/coin.png")
# Sounds
coin_sound = pygame.mixer.Sound("sounds/coin.wav")
gameover_sound = pygame.mixer.Sound("sounds/gameover.wav")
pygame.mixer.music.load("sounds/background.mp3")
pygame.mixer.music.play(-1)
# Fonts
font = pygame.font.Font(None,36)
big_font = pygame.font.Font(None,72)
# Read High Score
file = open("highscore.txt","r")
high_score = int(file.read())
file.close()
score = 0
player_x = 350
player_y = 250
player_speed = 5
enemy_x = 0
enemy_y = 100
enemy_speed = 3
coin_x = random.randint(0,736)
coin_y = random.randint(0,536)
game_over = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not game_over:
screen.blit(background,(0,0))
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and player_x < 736:
player_x += player_speed
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_UP] and player_y > 0:
player_y -= player_speed
if keys[pygame.K_DOWN] and player_y < 536:
player_y += player_speed
enemy_x += enemy_speed
if enemy_x > 800:
enemy_x = -64
player_rect = player.get_rect(topleft=(player_x,player_y))
enemy_rect = enemy.get_rect(topleft=(enemy_x,enemy_y))
coin_rect = coin.get_rect(topleft=(coin_x,coin_y))
if player_rect.colliderect(coin_rect):
coin_sound.play()
score += 1
if score > high_score:
high_score = score
file = open("highscore.txt","w")
file.write(str(high_score))
file.close()
coin_x = random.randint(0,736)
coin_y = random.randint(0,536)
if player_rect.colliderect(enemy_rect):
pygame.mixer.music.stop()
gameover_sound.play()
game_over = True
screen.blit(player,(player_x,player_y))
screen.blit(enemy,(enemy_x,enemy_y))
screen.blit(coin,(coin_x,coin_y))
score_text = font.render(
"Score : " + str(score),
True,
(255,255,255)
)
high_score_text = font.render(
"High Score : " + str(high_score),
True,
(255,255,0)
)
screen.blit(score_text,(10,10))
screen.blit(high_score_text,(10,45))
else:
screen.fill((25,25,25))
game_text = big_font.render(
"GAME OVER",
True,
(255,0,0)
)
screen.blit(game_text,(180,220))
pygame.display.update()
pygame.quit()
How This Program Works
Ab tak humne sirf code likha tha. Ab samajhte hain ki program background me kya karta hai.
Game start hote hi sabse pehle ye line chalti hai.
file = open("highscore.txt","r")
Ye highscore.txt file ko open karti hai.
Uske baad ye line chalti hai.
high_score = int(file.read())
Ye file me likhi value ko read karti hai.
Agar file me likha hai:
15
to variable ban jayega.
high_score = 15
Ab game ko pata hai ki player ka best score 15 hai.
High Score Kab Save Hota Hai?
Ye code dekhiye.
if score > high_score:
high_score = score
file = open("highscore.txt","w")
file.write(str(high_score))
file.close()
Yahan program ek simple question puchta hai.
Kya current score High Score se bada hai?
Agar answer Yes hai, to:
- High Score update hota hai.
- New High Score file me save ho jata hai.
Agar answer No hai,
to purana High Score hi rahta hai.
Isi wajah se player ka best record kabhi delete nahi hota.
Example
Suppose,
Current High Score hai:
20
Player ne collect kiye:
25 Coins
Program check karega.
25 > 20
Answer:
True
Ab file update hogi.
25
Agli baar game open karoge,
High Score automatically 25 load ho jayega.
Output
Agar sab kuch sahi hua, to game me kuch is tarah dikhai dega.
Score : 8
High Score : 25
Game close kijiye.
Dobara run kijiye.
Output fir bhi hoga.
High Score : 25
Ab aapka High Score permanently save ho chuka hai.
Common Errors
Error 1
FileNotFoundError
Problem
FileNotFoundError:
Reason
highscore.txt file nahi mili.
Solution
Check kijiye ki file project folder ke andar hai.
Error 2
ValueError
Problem
ValueError
Reason
File ke andar number ki jagah text likha hua hai.
Wrong
Twenty
Correct
20
Error 3
High Score Save Nahi Ho Raha
Check kijiye ki ye code likha hua hai.
file.write(str(high_score))
Aur uske baad.
file.close()
Agar file close nahi hogi,
to kabhi-kabhi data save nahi hota.
Teacher’s Tip
Ek common mistake beginners karte hain.
Wo har baar game restart hone par ye likh dete hain.
high_score = 0
Isse High Score delete ho jayega.
Restart hone par sirf ye reset hona chahiye.
score = 0
High Score ko kabhi reset mat kijiye.
Did You Know?
Humne file ko is tarah open kiya.
file = open("highscore.txt","r")
Ye beginner-friendly method hai.
Professional Python programmers aksar ye syntax use karte hain.
with open("highscore.txt","r") as file: high_score = int(file.read())
Iska advantage ye hai ki file automatically close ho jati hai.
Abhi ke liye pehla method hi use kijiye.
Future lessons me hum with open() detail me seekhenge.
Practice Challenge
Challenge 1
Create a new file.
playername.txt
Usme apna naam save kijiye.
Challenge 2
Change the High Score manually.
Open
highscore.txt
Replace
18
with
100
Run the game.
Kya High Score 100 dikh raha hai?
Challenge 3
Display this message whenever a new High Score is created.
🎉 New High Score!
Hint:
Create another text using font.render().
Mini Project
Improve your game by adding:
- Current Score
- High Score
- Game Over
- Restart Game
- Saved High Score
Congratulations!
Your game now remembers the player’s best performance.
What You Learned Today
Aaj humne seekha.
- Python me file kaise open karte hain.
- File se data kaise read karte hain.
- File me data kaise save karte hain.
- High Score permanently kaise store karte hain.
- Professional games High Score kaise save karte hain.
Frequently Asked Questions
How do I save the High Score in Pygame?
Create a text file, read the saved score when the game starts, and update the file whenever the player achieves a new High Score.
Why does my High Score become zero after closing the game?
Variables are stored in memory and are removed when the program closes. Save the High Score in a file if you want to keep it.
Which file is used to save the High Score?
For beginner projects, a simple text file such as highscore.txt is enough.
Why do we use str() while writing the High Score?
The write() function saves text, so we convert the number into a string using str().
Why do we use int() while reading the High Score?
The value read from a file is text. We use int() to convert it into a number so we can compare scores.
Can I save player names and game levels in a file?
Yes. You can save many types of information, such as player names, game levels, settings, achievements, and unlocked stages.
Summary
Today, you added one of the most useful features found in real games.
Your game can now:
- Save the High Score
- Load the High Score automatically
- Keep the player’s best score even after closing the game
This is an important step towards building professional games with Python and Pygame.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.
