moveit.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. """
  3. This is the full and final example from the Pygame Tutorial,
  4. "How Do I Make It Move". It creates 10 objects and animates
  5. them on the screen.
  6. Note it's a bit scant on error checking, but it's easy to read. :]
  7. Fortunately, this is python, and we needn't wrestle with a pile of
  8. error codes.
  9. """
  10. #import everything
  11. import os, pygame
  12. from pygame.locals import *
  13. main_dir = os.path.split(os.path.abspath(__file__))[0]
  14. #our game object class
  15. class GameObject:
  16. def __init__(self, image, height, speed):
  17. self.speed = speed
  18. self.image = image
  19. self.pos = image.get_rect().move(0, height)
  20. def move(self):
  21. self.pos = self.pos.move(self.speed, 0)
  22. if self.pos.right > 600:
  23. self.pos.left = 0
  24. #quick function to load an image
  25. def load_image(name):
  26. path = os.path.join(main_dir, 'data', name)
  27. return pygame.image.load(path).convert()
  28. #here's the full code
  29. def main():
  30. pygame.init()
  31. screen = pygame.display.set_mode((640, 480))
  32. player = load_image('player1.gif')
  33. background = load_image('liquid.bmp')
  34. # scale the background image so that it fills the window and
  35. # successfully overwrites the old sprite position.
  36. background = pygame.transform.scale2x(background)
  37. background = pygame.transform.scale2x(background)
  38. screen.blit(background, (0, 0))
  39. objects = []
  40. for x in range(10):
  41. o = GameObject(player, x*40, x)
  42. objects.append(o)
  43. while 1:
  44. for event in pygame.event.get():
  45. if event.type in (QUIT, KEYDOWN):
  46. return
  47. for o in objects:
  48. screen.blit(background, o.pos, o.pos)
  49. for o in objects:
  50. o.move()
  51. screen.blit(o.image, o.pos)
  52. pygame.display.update()
  53. if __name__ == '__main__': main()