Write Your First Python Battle in 30 Lines (No Experience Needed)
Most beginner Python tutorials start with temperature converters and shopping lists. Those work, but they are easy to forget. In this post we will build something a bit more fun: a tiny turn-based monster battle that runs in your terminal. It only needs four ideas: variables, if/else, a while loop and a function.
You can follow along in any Python 3 installation, or in an online editor.
Step 1: Give your monster some stats
A variable is a name tag for a value. Our monster needs a name, health points and an attack strength:
my_name = "Pyrocub"
my_hp = 30
my_attack = 6
enemy_name = "Bristusk"
enemy_hp = 24
enemy_attack = 4
Text goes inside quotes. Numbers do not.
Step 2: Make one attack happen
An attack is just subtraction. We take the attacker's strength away from the target's HP and print what happened:
enemy_hp = enemy_hp - my_attack
print(my_name, "attacks! Enemy HP:", enemy_hp)
Run it and you should see Pyrocub attacks! Enemy HP: 18.
Step 3: Turn it into a function
We will attack many times, so we wrap the idea in a function. A function takes inputs and gives back a result with return:
def hit(hp, damage):
hp = hp - damage
if hp < 0:
hp = 0
return hp
The if makes sure HP never goes below zero. Notice the 4 spaces of indentation: in Python, indentation is how you say "this line belongs inside".
Step 4: Keep fighting with a while loop
A while loop repeats as long as its condition is true. Here, the battle continues while both monsters are still standing:
turn = 1
while my_hp > 0 and enemy_hp > 0:
print("--- Turn", turn, "---")
enemy_hp = hit(enemy_hp, my_attack)
print(my_name, "attacks!", enemy_name, "HP:", enemy_hp)
if enemy_hp > 0:
my_hp = hit(my_hp, enemy_attack)
print(enemy_name, "strikes back!", my_name, "HP:", my_hp)
turn = turn + 1
Step 5: Announce the winner
After the loop ends, one monster has 0 HP. An if/else tells us who won:
if my_hp > 0:
print(my_name, "wins!")
else:
print(enemy_name, "wins!")
Put steps 1, 3, 4 and 5 in one file and run it (step 2 was just a warm-up). That is a complete game loop in about 30 lines.
Try these changes
- Change
my_attackto 3. Who wins now? - Use
import randomandrandom.randint(3, 7)to make each attack a little different. - Add a
defend()turn that halves the next hit.
Each change practises one idea: variables, modules, then functions again.
Why this works for beginners
A game gives every line of code a visible result. When the enemy's HP drops, you know your subtraction worked. When the loop never ends, you immediately see the bug. That quick feedback is what keeps new programmers going past the first week.
If you would like to keep learning this way, I have been building Code Monsters Academy, a free browser game where you pick a monster partner and write real Python to train it and win battles. There is nothing to install, and each level takes a few minutes.
Happy coding!