54 lines
1.3 KiB
Python
54 lines
1.3 KiB
Python
|
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)
|
||
|
|
||
|
def serve_ball(self):
|
||
|
self.ball.center = self.center
|
||
|
# NOTE: Breaking this out
|
||
|
random_ball_direction = random.randint(0, 360)
|
||
|
self.ball.velocity = vector.Vector(4, 0).rotate(random_ball_direction)
|
||
|
|
||
|
def update(self, dt):
|
||
|
self.ball.move()
|
||
|
|
||
|
# bounce off top and bottom
|
||
|
if (self.ball.y < 0) or (self.ball.top > self.height):
|
||
|
self.ball.velocity_y *= -1
|
||
|
|
||
|
# bounce off left and right
|
||
|
if (self.ball.x < 0) or (self.ball.right > self.width):
|
||
|
self.ball.velocity_x *= -1
|
||
|
|
||
|
|
||
|
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 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()
|