我正在尝试使用Python和Kivy制作Pong游戏,但我无法改变球的位置。每当我尝试时,球都不会发生变化,除非我在课堂上称之为我不想做的方法。
的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 :(得分: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()