This is my battle system that I wrote in Lua. Bear with me on this one, this is my first real program that does something besides write hello world. If there is anything that I could have done differently, drop an answer down there and I will take your advice for my next program. Huge shoutout to Jakuje for helping me make this, he refined my code for me and told me how to do things correctly.
math.randomseed( os.time() )
math.random(); math.random(); math.random()
local function battle()
n = math.random(10) + 1 -- Everybody's HP, enemy HP randomly generated number from 10 to 100
enemyhp = 10*n
exp = enemyhp*0.5
g_herohp = 100
print("You have encountered an enemy!")
io.write("Your HP: ")
io.write(g_herohp)
io.write(" ")
io.flush()
io.write("Enemy HP: ")
io.write(enemyhp)
io.write(" ")
io.flush()
end
local function attack() -- Attacking the enemy or running away
print("|Attack|Flee| ")
input = io.read()
if input == "attack" then
attackdamage = math.random(51)
if attackdamage == 51 then
print("Critical Hit! 100 damage!")
enemyhp = enemyhp - 100
else
enemyhp = enemyhp - attackdamage
io.write("You dealt ")
io.write(attackdamage)
io.write(" damage!")
end
elseif input == "flee" then
escapechance = math.random(2)
if escapechance == 1 then
escape = true
end
end
end
local function enemyattack() -- Enemy attacks you with a random amount of damage
print(" Enemy is attacking!")
eattackdamage = math.random(40)
g_herohp = g_herohp - eattackdamage
io.write("Enemy dealt ")
io.write(eattackdamage)
io.write(" damage!")
end
local function battleinprogress() -- If I used battle then it would reset everyones health.
if g_herohp <= 0 then
print(" You have died!")
end
io.write(" Your HP: ")
io.write(g_herohp)
io.write(" ")
io.flush()
io.write("Enemy HP: ")
io.write(enemyhp)
io.write(" ")
io.flush()
if enemyhp <= 0 then
print("You won!")
end
if escape == true then
print("You have run away!")
end
end
battle()
repeat
attack()
enemyattack()
battleinprogress()
until g_herohp <= 0 or enemyhp <= 0 or escape == true
end