Games are the best way to learn programming! Let’s walk through how to build your first game.
🎯 What makes a game a game?
Every game has:
1. Rules — what you can and can’t do
2. Goal — what you’re trying to achieve
3. Feedback — the player sees the result of their actions
4. Replayability — you can play again
🚀 Step 1: A simple text game
“Guess the Number” game
import random
# Setup
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print('🎯 GUESS THE NUMBER')
print(f'You have {max_attempts} attempts!\n')
# Main game loop
while attempts < max_attempts:
guess = int(input(f'Attempt {attempts + 1}/{max_attempts}: '))
attempts += 1
# Game logic
if guess == secret:
print(f'\n🎉 YOU WIN in {attempts} attempts!')
break
elif guess < secret:
print('↗️ Higher!')
else:
print('↘️ Lower!')
# Check if out of attempts
if attempts == max_attempts:
print(f'\n💀 Game over! The number was: {secret}')
What this has:
- ✅ Rules (guess the number in 7 attempts)
- ✅ Goal (guess the number)
- ✅ Feedback (higher/lower)
- ✅ Replayability (can run again)
🎲 Step 2: Add functions
Break the game into pieces:
import random
def start_game():
"""Start a new game"""
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print('🎯 GUESS THE NUMBER')
print(f'You have {max_attempts} attempts!\n')
return secret, attempts, max_attempts
def get_player_input(current_attempt, max_attempts):
"""Get input from the player"""
while True:
try:
guess = int(input(f'Attempt {current_attempt}/{max_attempts}: '))
if 1 <= guess <= 100:
return guess
else:
print('Number must be between 1 and 100!')
except ValueError:
print('Enter a number!')
def check_guess(guess, secret):
"""Check the guess"""
if guess == secret:
return 'win'
elif guess < secret:
return 'higher'
else:
return 'lower'
def play_game():
"""Main game function"""
secret, attempts, max_attempts = start_game()
while attempts < max_attempts:
attempts += 1
guess = get_player_input(attempts, max_attempts)
result = check_guess(guess, secret)
if result == 'win':
print(f'\n🎉 YOU WIN in {attempts} attempts!')
return
elif result == 'higher':
print('↗️ Higher!')
else:
print('↘️ Lower!')
print(f'\n💀 Game over! The number was: {secret}')
# Run
if __name__ == '__main__':
play_game()
Benefits of using functions:
- Code is easier to read
- Parts can be reused
- Easier to test
- Easier to add new features
💪 Step 3: Add features
Difficulty levels
def choose_difficulty():
"""Choose difficulty"""
print('Choose difficulty:')
print('1 - Easy (1–50, 10 attempts)')
print('2 - Medium (1–100, 7 attempts)')
print('3 - Hard (1–200, 5 attempts)')
choice = input('\nYour choice: ')
if choice == '1':
return 1, 50, 10
elif choice == '2':
return 1, 100, 7
elif choice == '3':
return 1, 200, 5
else:
return 1, 100, 7 # Default
Score system
def calculate_score(attempts, max_attempts):
"""Calculate score"""
# Fewer attempts = more points
base_score = 1000
penalty = (attempts - 1) * 100
score = max(base_score - penalty, 100)
return score
High score table
records = []
def save_record(name, score):
"""Save a record"""
records.append({'name': name, 'score': score})
# Sort by score descending
records.sort(key=lambda x: x['score'], reverse=True)
def show_records():
"""Show top 5"""
print('\n🏆 HIGH SCORES')
for i, record in enumerate(records[:5], 1):
print(f'{i}. {record["name"]}: {record["score"]} points')
🎨 Step 4: Polish the interface
Add colors (if the terminal supports it)
# ANSI escape codes
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
def print_colored(text, color):
"""Print colored text"""
print(f'{color}{text}{Colors.RESET}')
# Usage
print_colored('✅ Correct!', Colors.GREEN)
print_colored('❌ Wrong!', Colors.RED)
Animated effects
import time
def loading_animation(text, duration=2):
"""Loading animation"""
chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
end_time = time.time() + duration
i = 0
while time.time() < end_time:
print(f'\r{chars[i % len(chars)]} {text}', end='', flush=True)
time.sleep(0.1)
i += 1
print('\r' + ' ' * (len(text) + 3), end='\r') # Clear line
# Usage
loading_animation('Preparing game', 1)
🔄 Step 5: Game menu
def show_menu():
"""Main menu"""
while True:
print('\n' + '='*40)
print('🎮 GUESS THE NUMBER')
print('='*40)
print('1. 🎯 Play')
print('2. 🏆 High Scores')
print('3. ℹ️ Rules')
print('4. 🚪 Quit')
choice = input('\nChoose an action: ')
if choice == '1':
play_game()
elif choice == '2':
show_records()
elif choice == '3':
show_rules()
elif choice == '4':
print('\nThanks for playing! 👋')
break
else:
print('❌ Invalid choice!')
def show_rules():
"""Show rules"""
print('\n' + '='*40)
print('📜 RULES')
print('='*40)
print('1. The computer picks a number')
print('2. Guess it within the attempt limit')
print('3. After each guess you get a hint')
print('4. Fewer attempts = more points!')
input('\nPress Enter to continue...')
🎮 Full example: Advanced game
import random
import time
class Game:
def __init__(self):
self.records = []
self.difficulty_settings = {
'1': {'min': 1, 'max': 50, 'attempts': 10, 'name': 'Easy'},
'2': {'min': 1, 'max': 100, 'attempts': 7, 'name': 'Medium'},
'3': {'min': 1, 'max': 200, 'attempts': 5, 'name': 'Hard'}
}
def play(self):
# Choose difficulty
settings = self.choose_difficulty()
# Game session
secret = random.randint(settings['min'], settings['max'])
attempts = 0
print(f"\n🎯 Starting! Difficulty: {settings['name']}")
print(f"Number between {settings['min']} and {settings['max']}")
print(f"Attempts: {settings['attempts']}\n")
# Game loop
while attempts < settings['attempts']:
attempts += 1
guess = self.get_input(attempts, settings['attempts'])
if guess == secret:
score = self.calculate_score(attempts, settings['attempts'])
print(f"\n🎉 YOU WIN! Score: {score}")
self.save_result(score)
return
self.give_hint(guess, secret)
print(f"\n💀 Out of attempts! The number was: {secret}")
def choose_difficulty(self):
print('\nChoose difficulty:')
for key, settings in self.difficulty_settings.items():
print(f"{key} - {settings['name']}")
choice = input('\nYour choice: ')
return self.difficulty_settings.get(choice, self.difficulty_settings['2'])
def get_input(self, current, maximum):
while True:
try:
guess = int(input(f'Attempt {current}/{maximum}: '))
return guess
except ValueError:
print('❌ Enter a number!')
def give_hint(self, guess, secret):
diff = abs(secret - guess)
if diff > 50:
print('🥶 Very cold!')
elif diff > 20:
print('❄️ Cold')
elif diff > 10:
print('🌡️ Warm')
elif diff > 5:
print('🔥 Hot!')
else:
print('🔥🔥 Very hot!')
if guess < secret:
print('↗️ Higher')
else:
print('↘️ Lower')
def calculate_score(self, attempts, max_attempts):
return max(1000 - (attempts - 1) * 100, 100)
def save_result(self, score):
name = input('\nYour name: ')
self.records.append({'name': name, 'score': score})
self.records.sort(key=lambda x: x['score'], reverse=True)
# Run
game = Game()
game.play()
📚 What’s next?
Easy improvements:
- Sound effects (
playsoundlibrary) - Save high scores to a file
- Different game modes
More ambitious projects:
- Text-based RPG
- ASCII art game
- Game with Pygame (graphics!)
🎓 Tips for making games
- Start simple — get a basic version working first
- Add one feature at a time — test after each addition
- Use functions — break the code into small pieces
- Test often — check every change
- Get feedback — let friends play it
💡 Practice ideas
Try adapting “Guess the Number” into:
- A trivia quiz
- A treasure hunt
- A word-guessing game
- A math game
The main thing — start coding! 🚀
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!