Implementing Game Logic
Let’s build the brain of a game! When you play your favorite video game, it decides what happens when you jump, collect a coin, or lose a life. This decision-making is called game logic. We’ll learn how to write game logic using Python, with examples and fun exercises.
What is Game Logic?
Imagine you’re playing a treasure hunt game:
- If you step on a trap, you lose a life.
- If you find a treasure chest, you get coins.
- If you collect all treasures, you win!
These rules that decide how the game behaves are its logic.
How to Write Game Logic
Game logic is made of:
- Variables to store the game’s state (like score or health).
- Conditions to check what’s happening.
- Actions that happen when conditions are met.
Example 1: A Simple Coin Collector Game
Let’s make a tiny game:
- You have a score.
- If you find a coin, your score increases by 10.
- If your score reaches 50, you win.
Here’s how to write it in Python:
# Game state
score = 0
while score < 50: # Game continues until score reaches 50
print(f"Your score: {score}")
action = input("Type 'coin' to collect a coin or 'quit' to exit: ")
if action == "coin":
score += 10 # Add 10 to the score
print("You collected a coin!")
elif action == "quit":
print("Game over! Goodbye.")
break
else:
print("Invalid action. Try again.")
if score >= 50:
print("Congratulations! You win!")
How It Works
- We start with
score = 0
. - The game asks you to collect a coin by typing “coin”.
- Each time you collect a coin, the score increases by 10.
- When the score reaches 50, the game congratulates you.
Example 2: Avoiding Obstacles
Now, let’s make it exciting! Add a trap:
- If you step on a trap, you lose 20 points.
- If your score drops below 0, you lose.
Here’s the updated logic:
# Game state
score = 0
while score >= 0: # Game continues as long as score is non-negative
print(f"Your score: {score}")
action = input("Type 'coin' to collect a coin, 'trap' to step on a trap, or 'quit' to exit: ")
if action == "coin":
score += 10
print("You collected a coin!")
elif action == "trap":
score -= 20
print("Oh no! You stepped on a trap!")
elif action == "quit":
print("Game over! Goodbye.")
break
else:
print("Invalid action. Try again.")
if score < 0:
print("You lost! Better luck next time!")
Adding Levels
What if the game had levels? For example:
- In Level 1, you need 50 points to win.
- In Level 2, you need 100 points.
Here’s how to add levels:
# Game state
score = 0
level = 1
while level <= 2: # Two levels in the game
print(f"Level {level} - Your score: {score}")
action = input("Type 'coin' to collect a coin, 'trap' to step on a trap, or 'quit' to exit: ")
if action == "coin":
score += 10
print("You collected a coin!")
elif action == "trap":
score -= 20
print("Oh no! You stepped on a trap!")
elif action == "quit":
print("Game over! Goodbye.")
break
else:
print("Invalid action. Try again.")
if level == 1 and score >= 50:
print("Congratulations! You've cleared Level 1!")
level += 1 # Move to the next level
elif level == 2 and score >= 100:
print("Congratulations! You've cleared Level 2 and won the game!")
break
if level <= 2 and score < 0:
print("You lost! Better luck next time!")
Practice Questions
- Create a Timer
- Add a timer that decreases by 1 second each turn.
- The game ends when the timer reaches 0.
- Add a Treasure Chest
- If the player finds a treasure chest, they get 50 points.
- The treasure chest appears randomly (hint: use Python’s
random
module).
- Multiple Levels
- Make a 3-level game.
- In each level, the points required to win increase (e.g., 50, 100, 200).
Solutions
1. Create a Timer
Here’s how to add a countdown timer:
import time # For adding delays
# Game state
score = 0
timer = 10 # Timer starts at 10 seconds
while timer > 0:
print(f"Your score: {score}, Time left: {timer} seconds")
action = input("Type 'coin' to collect a coin or 'quit' to exit: ")
if action == "coin":
score += 10
print("You collected a coin!")
elif action == "quit":
print("Game over! Goodbye.")
break
else:
print("Invalid action. Try again.")
timer -= 1 # Decrease timer by 1 second
time.sleep(1) # Wait 1 second
if timer == 0:
print("Time's up! Game over!")
2. Add a Treasure Chest
Use the random
module to decide if the treasure chest appears:
import random
score = 0
while score < 100:
print(f"Your score: {score}")
chest = random.choice([True, False]) # Randomly decide if chest appears
if chest:
print("A treasure chest appeared! Type 'chest' to open it.")
action = input("Type 'coin' to collect a coin, 'chest' to open a treasure, or 'quit' to exit: ")
if action == "coin":
score += 10
print("You collected a coin!")
elif action == "chest" and chest:
score += 50
print("Wow! You found 50 points in the treasure chest!")
elif action == "quit":
print("Game over! Goodbye.")
break
else:
print("Invalid action. Try again.")
if score >= 100:
print("Congratulations! You win!")
Game logic is all about:
- Making rules (conditions).
- Deciding actions (what happens when rules are met).
- Tracking progress (using variables like score and level).
With Python, you can build games that are as simple or as complex as you want. Now, it’s your turn to get creative and make your own games! 🎮