2016-06-03 15:14:05 -04:00
|
|
|
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)
|
2016-06-03 16:01:08 -04:00
|
|
|
player_one = properties.ObjectProperty(None)
|
|
|
|
player_two = properties.ObjectProperty(None)
|
2016-06-03 15:14:05 -04:00
|
|
|
|
2016-06-03 16:01:08 -04:00
|
|
|
def serve_ball(self, vel=(4, 0)):
|
2016-06-03 15:14:05 -04:00
|
|
|
self.ball.center = self.center
|
2016-06-03 16:01:08 -04:00
|
|
|
self.ball.velocity = vel
|
2016-06-03 15:14:05 -04:00
|
|
|
|
|
|
|
def update(self, dt):
|
|
|
|
self.ball.move()
|
|
|
|
|
2016-06-03 16:01:08 -04:00
|
|
|
# bounce ball off bottom or top
|
|
|
|
if (self.ball.y < self.y) or (self.ball.top > self.top):
|
2016-06-03 15:14:05 -04:00
|
|
|
self.ball.velocity_y *= -1
|
|
|
|
|
2016-06-03 16:01:08 -04:00
|
|
|
# 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
|
2016-06-03 15:14:05 -04:00
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
2016-06-03 16:01:08 -04:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2016-06-03 15:14:05 -04:00
|
|
|
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()
|