簡體   English   中英

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''

使用sdl2.ext進行基於組件的設計的文檔中, Entity類型是特殊的,並且不遵循常規的Python習慣用法。 特別是,您不能僅僅創建任意屬性。 您只能創建其值是組件類型且名稱是該類型的小寫版本的屬性:

Entity對象定義應用程序內對象,並且僅包含基於組件的屬性

Entity還要求將其屬性准確命名為其組件類名稱,但要使用小寫字母。

因此,當您嘗試添加名為forward_tick的屬性時,這將導致Entity.__setattr__繼續在世界上的組件類型中查找名為Forward_Tick的類。 它顯然是通過查找self._world._componentypes[name] ,這實際上是引發異常的行,如您在回溯中所見。


除了您展示給我們的那小片段之外,對您的代碼和設計一無所知,我無法告訴您如何解決此問題。 但最有可能是以下之一:

  1. 您實際上想創建一個Component ,而不是Entity
  2. 您想將forward_tick包裝為該Entity可以包含的Component類型,或者
  3. 您一開始就不需要面向Component的設計。

無論如何,正如文檔所說:

如果您只是從這種[面向組件]設計開始,建議通讀The Pong Game教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM