Advertisement
cmiN

main.py

Sep 16th, 2017
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3.  
  4. import random
  5.  
  6. from kivy.app import App
  7. from kivy.clock import Clock
  8. from kivy.properties import (
  9.     NumericProperty,
  10.     ObjectProperty,
  11.     ReferenceListProperty,
  12. )
  13. from kivy.uix.widget import Widget
  14. from kivy.vector import Vector
  15.  
  16.  
  17. class PongBall(Widget):
  18.  
  19.     velocity_x = NumericProperty(0)
  20.     velocity_y = NumericProperty(0)
  21.     velocity = ReferenceListProperty(velocity_x, velocity_y)
  22.  
  23.     def move(self):
  24.         self.pos = Vector(*self.velocity) + self.pos
  25.  
  26.  
  27. class PongPaddle(Widget):
  28.  
  29.     score = NumericProperty(0)
  30.  
  31.     def bounce_ball(self, ball):
  32.         if self.collide_widget(ball):
  33.             vx, vy = ball.velocity
  34.             offset = (ball.center_y - self.center_y) / (self.height / 2)
  35.             bounced = Vector(-vx, vy)
  36.             vel = bounced * 1.1
  37.             ball.velocity = vel.x, vel.y + offset
  38.  
  39.  
  40. class PongGame(Widget):
  41.  
  42.     ball = ObjectProperty(None)
  43.     player1 = ObjectProperty(None)
  44.     player2 = ObjectProperty(None)
  45.  
  46.     def serve_ball(self, reverse=False):
  47.         self.ball.center = self.center
  48.         vel = Vector(4 * (-1 if reverse else 1), 0)
  49.         self.ball.velocity = vel
  50.  
  51.     def update(self, dt):
  52.         self.ball.move()
  53.  
  54.         self.player1.bounce_ball(self.ball)
  55.         self.player2.bounce_ball(self.ball)
  56.  
  57.         if self.ball.y < 0 or self.ball.top > self.height:
  58.             self.ball.velocity_y *= -1
  59.  
  60.         if self.ball.x < self.x:
  61.             self.player2.score += 1
  62.             self.serve_ball()
  63.         if self.ball.x > self.width:
  64.             self.player1.score += 1
  65.             self.serve_ball(reverse=True)
  66.  
  67.     def on_touch_move(self, touch):
  68.         left = self.width / 3
  69.         right = self.width - left
  70.         if touch.x < left:
  71.             self.player1.center_y = touch.y
  72.         if touch.x > right:
  73.             self.player2.center_y = touch.y
  74.  
  75.  
  76. class PongApp(App):
  77.  
  78.     def build(self):
  79.         game = PongGame()
  80.         game.serve_ball()
  81.         Clock.schedule_interval(game.update, 1.0 / 60.0)
  82.         return game
  83.  
  84.  
  85. if __name__ == "__main__":
  86.     PongApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement