Advertisement
ingwey

main.py

Mar 23rd, 2014
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. #import kivy
  2. #kivy.require('1.1.1')
  3.  
  4. from kivy.app import App
  5. from kivy.uix.widget import Widget
  6. from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
  7. from kivy.vector import Vector
  8. from kivy.clock import Clock
  9.  
  10. __version__ = '0.1'
  11.  
  12. class PongPaddle(Widget):
  13. score = NumericProperty(0)
  14.  
  15. def bounce_ball(self, ball):
  16. if self.collide_widget(ball):
  17. vx, vy = ball.velocity
  18. offset = (ball.center_y - self.center_y) / (self.height / 2)
  19. bounced = Vector(-1 * vx, vy)
  20. vel = bounced * 1.1
  21. ball.velocity = vel.x, vel.y + offset
  22.  
  23. class PongBall(Widget):
  24.  
  25. # velocity of the ball on x and y axis
  26. velocity_x = NumericProperty(0)
  27. velocity_y = NumericProperty(0)
  28.  
  29. # referencelist property so we can use ball.velocity as
  30. # a shorthand, just like e.g. w.pos for w.x and w.y
  31. velocity = ReferenceListProperty(velocity_x, velocity_y)
  32.  
  33. # ''move'' function will move the ball one step. This
  34. # will be called in equal intervals to animate the ball
  35. def move(self):
  36. self.pos = Vector(*self.velocity) + self.pos
  37.  
  38. class PongGame(Widget):
  39. ball = ObjectProperty(None)
  40. player1 = ObjectProperty(None)
  41. player2 = ObjectProperty(None)
  42.  
  43. def serve_ball(self, vel=(4,0)):
  44. self.ball.center = self.center
  45. self.ball.velocity = vel
  46.  
  47. def update(self, dt):
  48. # call ball.move and other stuff
  49. self.ball.move()
  50.  
  51. # bounce of paddles
  52. self.player1.bounce_ball(self.ball)
  53. self.player2.bounce_ball(self.ball)
  54.  
  55. # bounce off top and bottom
  56. if(self.ball.y < self.y) or (self.ball.top > self.top):
  57. self.ball.velocity_y *= -1
  58.  
  59. # went of to a side to score point
  60. if self.ball.x < self.x:
  61. self.player2.score += 1
  62. self.serve_ball(vel=(4, 0))
  63. if self.ball.x > self.width:
  64. self.player1.score += 1
  65. self.serve_ball(vel=(-4, 0))
  66.  
  67. # bounce off left and right
  68. #if(self.ball.x<0) or (self.ball.right>self.width):
  69. # self.ball.velocity_x *= -1
  70.  
  71. def on_touch_move(self, touch):
  72. if touch.x < self.width / 3:
  73. self.player1.center_y = touch.y
  74. if touch.x > self.width - self_width / 3:
  75. self.player2.center_y = touch.y
  76.  
  77. class PongApp(App):
  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. if __name__ == '__main__':
  85. PongApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement