我不熟悉Kivy和python。我正在用教程中给出的乒乓球游戏代码练习Kivy。一旦球与球拍相撞,我就要停下来。我可以通过将速度设置为零来停止更新函数中的球。但我想停止使用我自己的功能(停止发球)。我可以在类PongPaddle()的collide_小部件(Proof:Logger info)中调用stop_serve函数,但是球没有停止。请帮我实现上述目标。在
我已经分享了下面的完整代码。提前谢谢。在
乒乓球_修改的.py公司名称:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.logger import Logger
class PongPaddle(Widget):
score = NumericProperty(0)
def bounce_ball(self, ball):
if self.collide_widget(ball):
PongGame().stop_serve(vel = (0,0))
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
def move(self):
self.pos = Vector(*self.velocity) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
def serve_ball(self, vel=(4, 0)):
self.ball.center = self.center
self.ball.velocity = vel
def stop_serve(self,vel=(0,0)):
Logger.info('Inside stop_serve: %s' %self.pos)
self.ball.center = self.center
self.ball.velocity = vel
def update(self, dt):
self.ball.move()
#bounce of paddles
self.player1.bounce_ball(self.ball)
self.player2.bounce_ball(self.ball)
#bounce ball off bottom or top
if (self.ball.y < self.y) or (self.ball.top > self.top):
self.ball.velocity_y *= -1
#went of to a side to score point?
if self.ball.x < self.x:
self.player2.score += 1
self.serve_ball(vel=(4, 0))
if self.ball.x > self.width:
self.player1.score += 1
self.serve_ball(vel=(-4, 0))
def on_touch_move(self, touch):
if touch.x < self.width / 3:
self.player1.center_y = touch.y
if touch.x > self.width - self.width / 3:
self.player2.center_y = touch.y
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
PongApp().run()
在庞千伏公司名称:
^{pr2}$
这是python语法,它使用一个不同的球来创建一个新的pongame实例,因此stop\u-serve运行良好,但不会影响实际显示的任何窗口小部件。在
相反,您需要使用对现有PongGame的引用。在这种情况下,您可以使用
self.parent.stop_serve()
。在相关问题 更多 >
编程相关推荐