我正在研究一个非常简单的基于文本的冒险游戏。我已经能够做到玩家可以从一个房间移动到另一个房间的基础知识。为了增强游戏,我想要一个简单的战斗系统但是我在实施一个能保持玩家健康得分的系统时遇到了麻烦。我提供了代码目前的样本并添加了注释。
def update_score(x): #after the player has a combat round the variable 'a'is updated with remianing hit points
a = []
a.append(x)
def hit_points(): #when the player is in combat and takes a hit, 2 points are deducted and it is passed to the updated score function
y -= 2
updated_score(y)
def Continue():
#how can i then reference the updated score in another function. If the player goes into another battle, the remaining battle points will have to be used and deducted from
我刚刚开始掌握函数,并想知道是否可以将updated_score函数中的更新值传递给其他函数,或者再次调用命中点函数。
我试图避免使用全局变量。
任何帮助非常感谢
尝试使用课程
class Player:
def __init__(self):
self.hit_points = 100
def take_hit(self):
self.hit_points -= 2
p = Player()
print(p.hit_points)
>>> 100
p.take_hit()
print(p.hit_points)
>>> 98
写一堂课。考虑:
class GameState:
score = 0
life = 10
def update_score(self, x):
self.score += x # you can use negative values here too and perform various checks etc.
def hit_points(self):
self.life -= 2
您的数据存储在类中,您可以使用这些方法对其进行操作。没有污染全球范围的问题。
我假设您的变量y
是您将来需要更新和再次访问的变量。但由于y
的类型为int
,因此无法通过引用函数传递,这意味着除非将其定义为global
,否则无法访问它的更新值。这是全局变量的一个很好的介绍
https://www.geeksforgeeks.org/global-local-variables-python/
这里有一个非常详细的帖子,关于哪些变量按值传递,哪些变量在python中引用
https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/
在您的情况下,您应该在hit_points
的定义中进行以下更改
def hit_points():
global y
y -= 2
updated_score(y)
但是,对于一个大项目,我不建议使用global
。这是一个典型的情况,你应该定义一个类,并使y
成为一个成员变量
class Game:
def __init__(self):
self._y = 0
def hit_point(self):
self._y -= 2