kivy/examples/tutorials/pong/main.py

78 lines
2.0 KiB
Python
Raw Normal View History

2012-01-11 03:53:01 +00:00
import kivy
kivy.require('1.1.1')
2012-01-11 03:53:01 +00:00
from kivy.app import App
from kivy.uix.widget import Widget
2012-12-08 17:14:16 +00:00
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
2012-01-11 03:53:01 +00:00
from kivy.vector import Vector
from kivy.clock import Clock
class PongPaddle(Widget):
score = NumericProperty(0)
2012-01-11 03:53:01 +00:00
def bounce_ball(self, ball):
if self.collide_widget(ball):
vx, vy = ball.velocity
2012-12-08 17:14:16 +00:00
offset = (ball.center_y - self.center_y) / (self.height / 2)
bounced = Vector(-1 * vx, vy)
2012-01-11 03:53:01 +00:00
vel = bounced * 1.1
ball.velocity = vel.x, vel.y + offset
2012-01-11 03:53:01 +00:00
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
2012-01-11 03:53:01 +00:00
def move(self):
self.pos = Vector(*self.velocity) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
2012-12-08 17:14:16 +00:00
def serve_ball(self, vel=(4, 0)):
2012-01-11 03:53:01 +00:00
self.ball.center = self.center
self.ball.velocity = vel
2012-12-08 17:14:16 +00:00
def update(self, dt):
2012-01-11 03:53:01 +00:00
self.ball.move()
2012-01-11 03:53:01 +00:00
#bounce of paddles
self.player1.bounce_ball(self.ball)
self.player2.bounce_ball(self.ball)
2012-01-11 03:53:01 +00:00
#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.player2.score += 1
2012-12-08 17:14:16 +00:00
self.serve_ball(vel=(4, 0))
2012-01-11 03:53:01 +00:00
if self.ball.x > self.width:
self.player1.score += 1
2012-12-08 17:14:16 +00:00
self.serve_ball(vel=(-4, 0))
2012-01-11 03:53:01 +00:00
def on_touch_move(self, touch):
2012-12-08 17:14:16 +00:00
if touch.x < self.width / 3:
2012-01-11 03:53:01 +00:00
self.player1.center_y = touch.y
2012-12-08 17:14:16 +00:00
if touch.x > self.width - self.width / 3:
2012-01-11 03:53:01 +00:00
self.player2.center_y = touch.y
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
2012-12-08 17:14:16 +00:00
Clock.schedule_interval(game.update, 1.0 / 60.0)
2012-01-11 03:53:01 +00:00
return game
if __name__ == '__main__':
2012-01-11 03:53:01 +00:00
PongApp().run()