pygame - 观察者模式错误

时间:2013-03-02 18:26:35

标签: pygame observer-pattern

我正在使用我正在制作的游戏中的观察者模式进行测试。但是我遇到了一些问题。我的代码以及错误如下,有人可以帮忙吗?

错误:

File "C:\Users\Administrator\PycharmProjects\untitled\Level.py", line 112, in update
    w.update()
  File "C:\Users\Administrator\PycharmProjects\untitled\Entity.py", line 13, in update
    self.notifyObservers()
  File "C:\Users\Administrator\PycharmProjects\untitled\Observable.py", line 15, in notifyObservers
    observer.update(self)
TypeError: unbound method update() must be called with Player instance as first argument (got WorldController instance instead)

级别文件:

self.world = [WorldController()]
for w in self.world:
            w.update()

实体文件:

class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

class Entity(Observer, pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity, Observer):
    def __init__(self, x, y):
        super(Observer, self).__init__()
        Entity.__init__(self)
    def update(self, observable):
        print "works!"

可观察文件:

class Observable(object):
    def __init__(self, **kwds):
        super(Observable, self).__init__(**kwds)
        self._observers = []
    def addObserver(self, observer):
        if not observer in self._observers:
            self._observers.append(observer)
    def removeObserver(self, observer):
        try:
            self._observers.remove(observer)
        except ValueError:
            pass
    def notifyObservers(self):
        for observer in self._observers:
            observer.update(self)

class Observer(object):
    def __init__(self, **kwds):
        super(Observer, self).__init__(**kwds)
    def update(self, observable):
        pass

1 个答案:

答案 0 :(得分:1)

class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

应该是:

class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player())
        self.notifyObservers()

否则,当您调用Player.update(self)时,您正在调用静态方法而不是Player类的实例方法