Part 6 mini-project: Monster Battle
The second Part 6 project is a tiny turn-based fight: two instances
of the same class, each with its own health, taking turns until one
falls. It pulls in classes, methods, a while loop, and a
little randomness.
What to build
A program that, when run:
- Defines a
Monsterclass with a name, hit points, and attack strength. - Creates two monsters — say a Hero and a Goblin — each with their own numbers.
- Loops: while both are alive, the first hits the second, then (if it still stands) the second hits back. Each hit does random damage up to the attacker's strength.
- Stops when one monster's HP reaches
0, and prints the winner.
A sample round:
-- Round 3 --
Hero hits Goblin for 5. Goblin has 4 HP left.
Goblin hits Hero for 2. Hero has 19 HP left.
What to build it from
The Monster class needs:
Monster.new(name, hp, attack)— the constructor.:isAlive()— returnstruewhilehp > 0.:hit(other)— dealsmath.random(1, self.attack)damage to the other monster, never below0, and prints the result.
The battle is a while both are alive loop; the win check
is one if.
Files
Both versions are in projects/monster-battle/:
starter.lua— TODO comments for the class, the two monsters, the loop, and the result.finished.lua— a working version to compare against afterward.
Run with:
lua projects/monster-battle/starter.lua
Hints
- Random damage means each run plays out differently — but it always ends, because each hit lowers HP and HP never goes back up.
- Have the second monster hit back only
if other:isAlive(), so one that just fainted gets no free swing. - Clamp HP with
if other.hp < 0 then other.hp = 0 endso the printed HP never goes negative.
A bigger challenge (optional)
- A party. Put three monsters in a list and have each attack the next, using the "many objects" pattern from Chapter 28.
- Critical hits. One time in five
(
math.random(1, 5) == 1), double the damage and printCritical!.
Neither is required to finish the project.
Done?
When two monsters fight to a finish and the right winner is announced, Part 6 is complete. Move on to Chapter 31 — From Lua to Luau, the bridge to Roblox.