简体   繁体   中英

How can I permanently alter a global variable in python from within a function?

I'm trying to create a text-based adventure game in python, in which there will be fights with monsters and shops in which you can increase your health and damage. I realize that using global variables in functions isn't advised, but I haven't been able to find another way of implementing what I want to do. The fights and shops appear at multiple points in the game, so I thought defining them would be the best way to use them repeatedly. Here is a small section referring to an item available in a shop:

import random

own_health = 15
gold = 10
helmet = False

def helmet():
    global own_health
    global gold
    global helmet
    health_boost = random.randint(2,5)
    cost = random.randint(7,10)
    print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
    buy = input("Would you like to buy and equip the helmet? (y/n): ")
    if buy == "y":
        if gold - cost > -1 and helmet == False:
            gold -= cost
            own_health += health_boost
            helmet = True
        elif gold - cost < 0:
            print("You don't have enough money to buy this helmet.")
        elif helmet == True:
            print("You are already wearing a helmet.")
    elif buy == "n":
        print("You didn't buy the helmet.")
    else:
        print("Invalid input.")

helmet()
print(own_health)
print(gold)
print(helmet)

The results of this code are that own_health, gold and helmet are set back to the original values that they had before the function helmet() were carried out. Is there a way to fix this so that the global variables are set permanently once the function has been carried out? If not, I am eager to hear any different ways that I could code the program.

if gold - cost > -1 and helmet == False:

This condition will never succeed, because helmet is never False inside the function. The helmet you create just below own_health and gold gets overwritten when you define a function with the same name. Try giving your function a different name, for example get_helmet . Then your globals should update as desired:

c:\Users\Kevin\Desktop>test.py
There is a helmet that costs 7 and will increase your health by 2
Would you like to buy and equip the helmet? (y/n): y
17
3
True

Global variables should indeed be avoided. Passing them as arguments would be preferred.

You have multiple instances of the same variables. Your global variables should not be declared within the function, but rather somewhere externally. If the globals are used outside of the file in which they are declared, import that file and append the file name to the beginning of the global variable.

import fileName

fileName.gold ...

I would create a class:

import random

class myClass:

    def __init__(self, own_health, gold, helmet):
        self.own_health = own_health
        self.gold = gold
        self.helmet = helmet

    def buyHelmet(self):
        health_boost = random.randint(2,5)
        cost = random.randint(7,10)
        print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
        buy = input("Would you like to buy and equip the helmet? (y/n): ")
        if buy == "y":
            if self.gold - cost > -1 and self.helmet == False:
                self.gold -= cost
                self.own_health += health_boost
                self.helmet = True
            elif self.gold - cost < 0:
                print("You don't have enough money to buy this helmet.")
            elif self.helmet == True:
                print("You are already wearing a helmet.")
        elif buy == "n":
            print("You didn't buy the helmet.")
        else:
            print("Invalid input.")

kbball = myClass(15, 10, False)

print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)

kbball.buyHelmet()

print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)

#output

15
10
False
There is a helmet that costs 10 and will increase your health by 2
17
0
True

One way you can solve this problem is by using OOP.

class Game():
    def __init__(self):
        self.own_health = 15
        self.gold = 10
        self.helmet = 5

    def helmet(self):
        health_boost = random.randint(2,5)
        cost = random.randint(7,10)
        print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
        buy = input("Would you like to buy and equip the helmet? (y/n): ")
        if buy == "y":
            if self.gold - cost > -1 and self.helmet == False:
                self.gold -= cost
                self.own_health += health_boost
                self.helmet = True
            elif self.gold - cost < 0:
                print("You don't have enough money to buy this helmet.")
            elif self.helmet == True:
                print("You are already wearing a helmet.")
        elif buy == "n":
            print("You didn't buy the helmet.")
        else:
            print("Invalid input.")

And then define some functions that returns you the values of the global variables.

   def get_own_health(self):
       return self.own_health

Now you can check the variable values as follows:

game = Game() 
game.helmet()
print(game.get_own_health())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM