import random from kivy import app, clock, properties, vector from kivy.uix import widget class PongGame(widget.Widget): # ADD note: why the None needed... the API allows for *args, **kwargs ball = properties.ObjectProperty(None) player_one = properties.ObjectProperty(None) player_two = properties.ObjectProperty(None) def serve_ball(self, vel=(4, 0)): self.ball.center = self.center self.ball.velocity = vel def update(self, dt): self.ball.move() # 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.player_two.score += 1 self.serve_ball(vel=(4, 0)) if self.ball.x > self.width: self.player_one.score += 1 self.serve_ball(vel=(-4, 0)) def on_touch_move(self, touch): if touch.x < self.width / 3: self.player_one.center_y = touch.y if touch.x > self.width - self.width / 3: self.player_two.center_y = touch.y class PongBall(widget.Widget): velocity_x = properties.NumericProperty(0) velocity_y = properties.NumericProperty(0) velocity = properties.ReferenceListProperty(velocity_x, velocity_y) def move(self): self.pos = vector.Vector(*self.velocity) + self.pos class PongPaddle(widget.Widget): score = properties.NumericProperty(0) def bounce_ball(self, ball): if self.collide_widget(ball): vx, vy = ball.velocity offset = (ball.center_y - self.center_y) / (self.height / 2) bounced = vector.Vector(-1 * vx, vy) vel = bounced * 1.1 ball.velocity = vel.x, vel.y + offset class PongApp(app.App): def build(self): game = PongGame() game.serve_ball() clock.Clock.schedule_interval(game.update, 1.0 / 60.0) return game def run_pong_game(): PongApp().run() if __name__ == '__main__': run_pong_game()