Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- import random
- from kivy.app import App
- from kivy.clock import Clock
- from kivy.properties import (
- NumericProperty,
- ObjectProperty,
- ReferenceListProperty,
- )
- from kivy.uix.widget import Widget
- from kivy.vector import Vector
- class PongBall(Widget):
- velocity_x = NumericProperty(0)
- velocity_y = NumericProperty(0)
- velocity = ReferenceListProperty(velocity_x, velocity_y)
- def move(self):
- self.pos = Vector(*self.velocity) + self.pos
- class PongPaddle(Widget):
- score = 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(-vx, vy)
- vel = bounced * 1.1
- ball.velocity = vel.x, vel.y + offset
- class PongGame(Widget):
- ball = ObjectProperty(None)
- player1 = ObjectProperty(None)
- player2 = ObjectProperty(None)
- def serve_ball(self, reverse=False):
- self.ball.center = self.center
- vel = Vector(4 * (-1 if reverse else 1), 0)
- self.ball.velocity = vel
- def update(self, dt):
- self.ball.move()
- self.player1.bounce_ball(self.ball)
- self.player2.bounce_ball(self.ball)
- if self.ball.y < 0 or self.ball.top > self.height:
- self.ball.velocity_y *= -1
- if self.ball.x < self.x:
- self.player2.score += 1
- self.serve_ball()
- if self.ball.x > self.width:
- self.player1.score += 1
- self.serve_ball(reverse=True)
- def on_touch_move(self, touch):
- left = self.width / 3
- right = self.width - left
- if touch.x < left:
- self.player1.center_y = touch.y
- if touch.x > right:
- self.player2.center_y = touch.y
- class PongApp(App):
- def build(self):
- game = PongGame()
- game.serve_ball()
- Clock.schedule_interval(game.update, 1.0 / 60.0)
- return game
- if __name__ == "__main__":
- PongApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement