Simple python rng game

python

#1

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)


#2

we could get the returned health:

goblin  = attack(goblin)

then print it:

goblin  = attack(goblin)
print(goblin) 

#3

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.


#4

can’t we do something along the lines of:

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()

i am not really a big fan of using global


#5

Nicer, for sure. And it does not pollute the global namespace.


#6

exactly, maybe not perfect yet but i think its an improvement.


#7

thanks guys, appreciate it


#8

i inserted a main function (this is pretty common), the action function sorts of acts like a menu now (assuming that is where you want to go)

I simply printed the new health after dealing the hit (quit effective), but i also made sure the health is returned


#9

Thank you very much :slight_smile:


#10

Note the use of .format() to simplify string interpolation. Extremely useful and readable, as well as configurable.

https://pyformat.info/