Advertisement
Guest User

Untitled

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