I\'m practicing Kivy with the PongGame code given in the tutorial. I want to know how to call a function - serve_ball2() in the class PongGame from a newly created class - PongS
I emphasize that this seems unnecessary, and that PongSample
itself seems like it needn't exist at all. However, to do what you asked, I believe the following should work. One thing I really don't like about this however, is that a PongSample instance is created in the kv file, without any other purpose than to serve ball2. However...
Why not define the serve_ball2
function in the PongSample
class instead, and pass ball2
to it?
Example:
class PongSample(Widget):
def serve_ball2(self, ball2, vel=(3,0)):
print 'Serve ball 2'
ball2.center = self.center
ball2.velocity = vel
And in the PongGame class:
class PongGame(Widget):
ball = ObjectProperty(None)
ball2 = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
# add this
sample = ObjectProperty(None)
Then in the kv file:
# add at the top
<PongSample>:
size: self.size
pos: self.pos
# add the below in appropriate places within the PongGame definition
PongGame:
sample: pong_sample
PongSample:
id: pong_sample # now it's linked to 'sample' in PongGame
So now in PongGame
you can call self.sample.serve_ball2(ball2)
from any method.
To use your class add game.serve_ball2()
to PongApp
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
game.serve_ball2()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
And add self.ball2
to bounce off the paddles:
#bounce of paddles
self.player1.bounce_ball(self.ball)
self.player2.bounce_ball(self.ball)
self.player1.bounce_ball(self.ball2)
self.player2.bounce_ball(self.ball2)