sdl2 实体的错误设置属性

Error setting attribute of an sdl2 Entity

我正在使用 pysdl2 库。 self.velocity 将打印,但 self.forward_tick 会抛出一个键错误。

是什么导致只分配了部分自我属性。我认为这与继承有关。

class Robot(sdl2.ext.Entity):
    def __init__(self, world, sprite, posx=0, posy=0):
        self.sprite = sprite
        self.sprite.position = posx, posy
        self.velocity = Velocity()
        self.forward_tick = 0
        self.go_forward = 0
        self.unit_forward = (1,0)
        print(self.velocity)
        print(self.forward_tick)

这是输出:

Collins-MacBook-Air:soccer_bots collinbell$ python test_simulation_world.py 
<simulation_world.Velocity object at 0x108ecb5c0>
Traceback (most recent call last):
  File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 53, in __getattr__
    ctype = self._world._componenttypes[name]
KeyError: 'forward_tick'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_simulation_world.py", line 3, in <module>
    world = Simulation_World("Test Simulation", 1080, 720)
  File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 100, in __init__
    self.player1 = Robot(self.world, sp_paddle1, 0, 250)
  File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 22, in __init__
    print(self.forward_tick)
  File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 56, in __getattr__
    (self.__class__.__name__, name))
AttributeError: object ''Robot'' has no attribute ''forward_tick''

根据 component-based design with sdl2.ext 上的文档,Entity 类型很特殊,不遵循正常的 Python 习语。特别是,您不能只创建任意属性;您只能创建值为组件类型且名称是该类型的小写版本的属性:

Entity objects define the in-application objects and only consist of component-based attributes.

The Entity also requries its attributes to be named exactly as their component class name, but in lowercase letters.

因此,当您尝试添加名为 forward_tick 的属性时,会导致 Entity.__setattr__ 在世界组件类型中寻找名为 Forward_Tick 的 class。它显然是通过查找 self._world._componentypes[name] 来实现的,这是实际引发异常的行,正如您在回溯中看到的那样。


除了你向我们展示的小片段之外,我对你的代码和设计一无所知,我无法告诉你如何解决这个问题。但最有可能的是以下之一:

  1. 您实际上想创建一个 Component,而不是 Entity
  2. 您想将 forward_tick 包装成此 Entity 可以包含的 Component 类型,或者
  3. 您一开始并不想要面向 Component 的设计。

无论如何,正如文档所说:

If you are just starting with such a [component-oriented] design, it is recommended to read through the The Pong Game tutorial.