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() 
相关问题