Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using a global variable before and within a function in python

I am making a text style adventure game and don’t have too much knowledge with python. I am trying to use my (enemyHealth) which has a random integer assigned to it. I’ve set this variable to be global and I want to use it within my function. But before the function is created I want to print out the variable outside of the function. I am wanting these to be the same value and am unsure what I am supposed to do. The function I am referring to is my (attack_function()).

Heres’s a section of my code.

    #enemy
enemyEasy = ["goblin archer", "thieves", "ghouls", "goblin swordsman"]
encounter = random.choice(enemyEasy)
global enemyHealth
enemyHealth = random.randint(9, 13)

#attack functions
attackLow = ("attack")
pursuadeDown = ("pursuade")
fleeDown = ("flee")
options = ["Attack", "Pursuade", "Flee"]

#conditions for correct grammar
if (encounter == enemyEasy[1]) or (encounter == enemyEasy[2]):
    print ("\nYou walk down a path isolated when you are approached by a group of figures in the distance")
    time.sleep(2)
    print ("\nThe figures is a group of " + encounter + "!")
    time.sleep(2)

else:
    print ("\nYou walk down a path isolated when you are approached by a figure in the distance")
    time.sleep(2)
    print ("\nThe figure is a " + encounter + "!")
    time.sleep(2)

#first encounter
print ("\nEnemy Health:", enemyHealth)
time.sleep(1)
print("\nWhat do you do?: ")
print (options)
action = input()

#attack function
def attack_function():
    while (enemyHealth > 0):
    
        if (enemyHealth > 0):
        
            #miss function
            missChance = random.randint(1,8)
        
            if (missChance > 6):
                print ("You attack the enemy and miss\n")
                time.sleep(3)

            else:
                #random user damage from 1 - 6
                userDamage = random.randint(1, 6)
                print ("You attack the", encounter, "and did", userDamage, "damage!")
                enemyHealth = (enemyHealth - userDamage)
                print ("Enemy Health:", enemyHealth, "\n")
                time.sleep(2)
            
                if (enemyHealth > 0):
                    missChance = random.randint(1,8)
                
                    if (missChance > 6):               
                        print("The enemy attacks you and misses\n")
                        time.sleep(3)

                    else:
                        #random enemy damage from 3 - 4
                        enemyDamage = random.randint(3, 4)
                        print ("The enemy attacked you and did", enemyDamage, "damage!")
                        health = (health - enemyDamage)
                        print ("Health:", health, "\n")
                        time.sleep(3)

                else:
                    #XP System
                    xpGain = random.randint(2, 4)
                    XP = (XP + xpGain)

                    #enemy defeat
                    print ("\nYou defeated the enemy!")
                    print ("You gained", xpGain, "XP!")
                    if (XP == 10):
                        level = (level + 1)
                        print("you are now level 2")
                        userDamage = (random.randint(1, 6) + 3)

                    print ("XP:",XP)
                    break
            
#if action is to attack use attack function
if (action == options[0]) or (action == attackLow):
    attack_function()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Might I suggest using classes?

import random

class Enemy:
    def __init__(self) -> None:
        self.type = random.choice(["goblin archer", "thieves", "ghouls", "goblin swordsman"])
        self.health = random.randint(9, 13)

You can then replace your first 4 lines (everything under #enemy) with:

enemy = Enemy()

This assumes you’ve either imported Enemy from another file or put the Enemy class at the very top. You can then access, update, etc., the health with enemy.health

Edit: as an FYI, you should not need to use the global keyword here, as long as you define enemy in the top-most scope (outside all your functions).

Edit:
self refers to the object. You only use self in the __init__ function and then use whatever variable name you want outside of that. For your case:

import random

class Enemy:
    def __init__(self) -> None:
        self.type = random.choice(["goblin archer", "thieves", "ghouls", "goblin swordsman"])
        self.health = random.randint(9, 13)
enemy = Enemy()
#attack functions
attackLow = ("attack")
pursuadeDown = ("pursuade")
fleeDown = ("flee")
options = ["Attack", "Pursuade", "Flee"]```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading