-- Monster Battle -- finished version. -- Two monsters trade blows until one faints. -- Run with: lua projects/monster-battle/finished.lua local Monster = {} Monster.__index = Monster function Monster.new(name, hp, attack) return setmetatable({ name = name, hp = hp, attack = attack }, Monster) end function Monster:isAlive() return self.hp > 0 end function Monster:hit(other) local damage = math.random(1, self.attack) other.hp = other.hp - damage if other.hp < 0 then other.hp = 0 end print(self.name .. " hits " .. other.name .. " for " .. damage .. ". " .. other.name .. " has " .. other.hp .. " HP left.") end local hero = Monster.new("Hero", 30, 8) local goblin = Monster.new("Goblin", 25, 6) local round = 1 while hero:isAlive() and goblin:isAlive() do print("-- Round " .. round .. " --") hero:hit(goblin) if goblin:isAlive() then goblin:hit(hero) end round = round + 1 end if hero:isAlive() then print(hero.name .. " wins!") else print(goblin.name .. " wins!") end