How to call a function from a class from another class in kivy Pong ball game

前端 未结 2 1415
情歌与酒
情歌与酒 2021-01-23 16:31

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

2条回答
  •  無奈伤痛
    2021-01-23 16:52

    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
    
    :
        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.

提交回复
热议问题