/Demo/tkinter/matt/pong-demo-1.py

http://unladen-swallow.googlecode.com/ · Python · 54 lines · 36 code · 15 blank · 3 comment · 4 complexity · fc94f23ab75685cc45329628619bfdd3 MD5 · raw file

  1. from Tkinter import *
  2. import string
  3. class Pong(Frame):
  4. def createWidgets(self):
  5. self.QUIT = Button(self, text='QUIT', foreground='red',
  6. command=self.quit)
  7. self.QUIT.pack(side=LEFT, fill=BOTH)
  8. ## The playing field
  9. self.draw = Canvas(self, width="5i", height="5i")
  10. ## The speed control for the ball
  11. self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
  12. from_=-100, to=100)
  13. self.speed.pack(side=BOTTOM, fill=X)
  14. # The ball
  15. self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
  16. fill="red")
  17. self.x = 0.05
  18. self.y = 0.05
  19. self.velocity_x = 0.3
  20. self.velocity_y = 0.5
  21. self.draw.pack(side=LEFT)
  22. def moveBall(self, *args):
  23. if (self.x > 5.0) or (self.x < 0.0):
  24. self.velocity_x = -1.0 * self.velocity_x
  25. if (self.y > 5.0) or (self.y < 0.0):
  26. self.velocity_y = -1.0 * self.velocity_y
  27. deltax = (self.velocity_x * self.speed.get() / 100.0)
  28. deltay = (self.velocity_y * self.speed.get() / 100.0)
  29. self.x = self.x + deltax
  30. self.y = self.y + deltay
  31. self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
  32. self.after(10, self.moveBall)
  33. def __init__(self, master=None):
  34. Frame.__init__(self, master)
  35. Pack.config(self)
  36. self.createWidgets()
  37. self.after(10, self.moveBall)
  38. game = Pong()
  39. game.mainloop()