我想将玩家统计数据保存在与游戏引擎运行的房间不同的模块中。问题是当我尝试从不同的模块设置Player
属性时,它不会保存新属性并实例化原始属性。
这是Player
模块中的entities
类
class Player(object):
def __init__(self):
self.name = ' '
self.hp = 0
self.current_hp = 0
self.strength = 0
self.dexterity = 0
self.constitution = 0
以下是我试图操纵和测试rooms
模块
class CharacterCreation(Scene):
def enter(self):
character = entities.Player()
character.hp = 10
print character.hp
return 'barracks'
class Barracks(Scene):
def enter(self):
character = entities.Player()
print character.hp
return 'shop'
当我用剩下的代码测试时,这就是我得到的。
-------------------------------------------------------------------------------
10
-------------------------------------------------------------------------------
0
-------------------------------------------------------------------------------
那我在这里错过了什么?我以为我可以使用=
设置该属性,但似乎我错了?我第一次这样做,它有效,但是我如何让python将hp
的新值设置为10?
答案 0 :(得分:2)
您在每个场景中创建一个新的Player对象,更改其属性,然后将其丢弃。
你应该明确地将一个单独的玩家传递到每个场景中:
def enter(self, player):
... do something with player ...
答案 1 :(得分:1)
您似乎在每个Player
方法上创建了一个新的enter
实例...
如果你在游戏中只有一个玩家,你可以把它作为一个全局变量(通常不是很好的主意),甚至更好,作为一个单例类: http://blog.amir.rachum.com/post/21850841339/implementing-the-singleton-pattern-in-python
我对代码进行了一些调整。它添加了PlayerPool
类(实际上更像是缓存)。它可能会给你一些想法:)
#!/usr/bin/env python
#http://stackoverflow.com/questions/14629710/python-setting-attributes-from-module-to-module/14629838#14629838
class Player(object):
def __init__(self):
self.name = ' '
self.hp = 0
self.current_hp = 0
self.strength = 0
self.dexterity = 0
self.constitution = 0
class PlayerPool(object):
_players = dict()
@classmethod
def getPlayerByName(cls, name):
if not name in cls._players:
newPlayer = Player()
newPlayer.name = name
cls._players[newPlayer.name] = newPlayer
return cls._players[name]
class Scene(object):
pass
class CharacterCreation(Scene):
def enter(self):
character = PlayerPool.getPlayerByName("foobar-hero")
character.hp = 10
print "%s has %s points of hp" % (character.name, character.hp)
return 'barracks'
class Barracks(Scene):
def enter(self):
character = PlayerPool.getPlayerByName("foobar-hero")
print "%s has %s points of hp" % (character.name, character.hp)
return 'shop'
if __name__ == "__main__":
step1 = CharacterCreation()
if step1.enter() == "barracks":
step2 = Barracks()
step2.enter()
输出:
borrajax@borrajax-comp:~/Tests/Python/Stack Overflow$ python ./players.py
foobar-hero has 10 points of hp
foobar-hero has 10 points of hp
欢迎使用python。我相信你会发现它有很酷的功能......例如返回函数的能力,或者将函数作为参数传递,检查任何模块中定义的类......看起来你觉得有用的东西。