2017-04-11 64 views
0

我想用Python和Kivy做一個Pong遊戲,但是我不能改變球的位置。每當我嘗試時,除非我在課堂內調用我不想做的方法,否則球不會改變。如何從Python中的另一個類的另一個類訪問方法以編輯Kivy對象?

的Python:

#Imported everything 

    class PongGame(Widget): 
     ball = ObjectProperty() 

     def update(self): 
      self.ball.pos = (1200, 1200) 


    class PongBall(Widget): 
     pass 

    class PongApp(App): 
     def build(self): 
      PongGame().update() #Doesn't work (doesn't do anything) 
      print(PongGame().ball.pos)) #Not even printing right coordinates 
      return PongGame() 

    if __name__ = "__main__": 
     PongApp().run() 

的Kv:

<PongGame>: 
    ball: pball 

    PongBall: 
     id: pball 
     pos: (root.center_x - (root.width * 0.05), root.center_y * (1/12)) 
     size: (root.height * (1/20), root.height * (1/20)) 

<PongBall>: 
    canvas: 
     Color: 
      rgb: [1, 1, 1] 
     Ellipse: 
      pos: self.pos 
      size: self.size 
+0

嘗試去除高清更新(個體經營)自我? – Stephan

+0

那麼我會如何訪問ObjectProperty球? –

+0

我認爲這是一個運行PongGame()的問題。update() –

回答

1

1)兩個開括號,三個閉合:

print(PongGame().ball.pos)) 

2)=應改爲==

if __name__ = "__main__": 

3)在這裏,你創建3個不同的PongGame對象(巫婆將有不同的狀態),而不是創建一個:

PongGame().update() #Doesn't work (doesn't do anything) 
print(PongGame().ball.pos)) #Not even printing right coordinates 
return PongGame() 

應該是:

root = PongGame() # Create one object and change it's state. 
root.update() 
print(root.ball.pos) # will print 1200, 1200 
return root 

4 ) kvlang將widgets屬性綁定到它依賴的變量。所以如果你想在將來改變球位置,你不應該將它綁定到root忽略球的pos。換句話說,

pos: (root.center_x - (root.width * 0.05), root.center_y * (1/12)) 

應的self.pos依賴:

pos: self.pos 

- )這就是很重要的。

我還添加了on_touch_down處理,以顯示球的位置改變(只需點擊窗口移動球):

Builder.load_string(b''' 
<PongGame>: 
    ball: pball 

    PongBall: 
     id: pball 
     pos: self.pos 
     size: 20, 20 

<PongBall>: 
    canvas: 
     Color: 
      rgb: [1, 1, 1] 
     Ellipse: 
      pos: self.pos 
      size: self.size 
''') 


class PongGame(Widget): 
    ball = ObjectProperty() 

    def update(self): 
     self.ball.pos = (200, 200) 

    def on_touch_down(self, touch): 
     self.ball.pos = touch.pos # change ball position to point of click 


class PongBall(Widget): 
    pass 


class PongApp(App): 
    def build(self): 
     root = PongGame() 
     root.update() # init ball position 
     return root 


if __name__ == '__main__': 
    PongApp().run() 
相關問題