Hi, I’m trying to make a simple rng game in python, and I want the health of the goblin to be displayed, but I can’t figure out how to do it, can anyone help me?
from random import randint
print("Oh no! It's a goblin!")
goblin = 20
def attack(x):
damage = randint(1,6)
x = x - damage
print("Nice, you dealt ", damage, " damage!")
if x > 0:
print("****! The goblin is still not dead!")
else:
print("Congratulations! You killed the goblin!")
return x
def action():
user_answer = input("What do you want to do?(type 'a' to attack.")
if user_answer == "a":
attack(goblin)
else:
print("nah")
action()
print(goblin)
As @stetim94 points out, we need to assign a new value to goblin.
from random import randint
print ("Oh no! It's a goblin!")
goblin = 20
def attack(x):
damage = randint(1,6)
x = x - damage
print ("Nice, you dealt {} damage!".format(damage))
if x > 0:
print ("****! The goblin is still not dead!")
else:
print ("Congratulations! You killed the goblin!")
return x
def action():
global goblin
user_answer = input("What do you want to do? (type 'a' to attack.)")
if user_answer == "a":
goblin = attack(goblin)
else:
print ("nah")
action()
print(goblin)
Note the use of global. When only retrieving a global we can access it directly, but when we wish to set a global, we need the bridge else the left side is perceived as local.
from random import randint
print ("Oh no! It's a goblin!")
def attack(x):
damage = randint(1,6)
x = x - damage
print ("Nice, you dealt {} damage!".format(damage))
if x > 0:
print ("****! The goblin is still not dead!")
print("the goblin has {} health left".format(x))
else:
print ("Congratulations! You killed the goblin!")
return x
def action(x):
user_answer = input("What do you want to do? (type 'a' to attack.)")
if user_answer == "a":
return attack(x)
else:
print ("nah")
def main():
goblin = 20
goblin = action(goblin)
main()