我一直在python中使用全局变量进行一个小文本游戏,并且遇到了很多说全局变量在python中是不允许的文章。我一直试图了解如何得到我下面(只是一个健康变量,能够改变它和打印它)使用类工作,但我很困惑我如何能转换这样的东西在一个类。任何帮助,例如,指出正确的方向将是伟大的。
下面是我使用变量的一个例子。
import sys
import time
health = 100
b = 1
def intro():
print("You will die after two moves")
def exittro():
time.sleep(1)
print("Thanks for playing!")
sys.exit()
def move():
global health
global b
health -= 50
if health <= 51 and b >0:
print("almost dead")
b = b - 1
def death():
if health == 0 or health <= 0:
print("...")
time.sleep(1)
print("You diedn")
time.sleep(2)
print("Dont worry, this game sucks anywayn")
exittro()
intro()
a = 1
while a == 1:
input("Press Enter to move")
move()
death()
谢谢
编辑:这是我一直在尝试做的事情…
class Test:
def __init__(self):
number = 100
def __call__(self):
return number
def reduceNum(self):
number -=10
def printNum(self):
print(number)
a = 1
while a == 1:
input("Enter")
Test.self.reduceNum()
Test.self.printNum()
我会避免使用类,因为类通常比较慢。您可以使该函数返回health
变量的新值。
我还建议制作一个主控制器函数来获取返回值并将其应用于其他函数。这可以防止全局变量在函数作用域之外。
import time
def intro():
print("You will die after two moves")
def outro():
time.sleep(1)
print("Thanks for playing!")
# sys.exit() # You can avoid this now by just stopping the program normally
def move(health):
health -= 50
if health <= 51:
print("almost dead")
return health # Return the new health to be stored in a variable
def death(health):
if health <= 0:
print("...")
time.sleep(1)
print("You diedn")
time.sleep(2)
print("Dont worry, this game sucks anywayn")
return True # Died
return False # Didn't die
def main():
health = 100 # You start with 100 health
intro()
while not death(health):
# While the death function doesn't return `True` (i.e., you didn't die) ...
input("Press enter to move")
health = move(health) # `health` is the new health value
outro()
如果你想使用类,你需要通过执行instance = Test()
实际实例化类(从它创建一个新对象)。您还需要将变量存储为self(因此self.number = number
)的属性,因为任何局部变量都是彼此不同的。
class Test:
def __init__(self):
self.number = 100
def __call__(self):
return self.number
def reduceNum(self):
self.number -= 10
def printNum(self):
print(self.number)
a = 1
game = Test()
while a == 1:
input("Enter")
game.reduceNum()
game.printNum()
# Or:
print(game())
# As you've changed `__call__` to return the number as well.