listing29-1.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import sys, pygame
  2. from pygame.locals import *
  3. from random import randrange
  4. class Weight(pygame.sprite.Sprite):
  5. def __init__(self, speed):
  6. pygame.sprite.Sprite.__init__(self)
  7. self.speed = speed
  8. # image and rect used when drawing sprite:
  9. self.image = weight_image
  10. self.rect = self.image.get_rect()
  11. self.reset()
  12. def reset(self):
  13. """
  14. Move the weight to a random position at the top of the screen.
  15. """
  16. self.rect.top = -self.rect.height
  17. self.rect.centerx = randrange(screen_size[0])
  18. def update(self):
  19. """
  20. Update the weight for display in the next frame.
  21. """
  22. self.rect.top += self.speed
  23. if self.rect.top > screen_size[1]:
  24. self.reset()
  25. # Initialize things
  26. pygame.init()
  27. screen_size = 800, 600
  28. pygame.display.set_mode(screen_size, FULLSCREEN)
  29. pygame.mouse.set_visible(0)
  30. # Load the weight image
  31. weight_image = pygame.image.load('weight.png')
  32. weight_image = weight_image.convert() # ... to match the display
  33. # You might want a different speed, of courase
  34. speed = 5
  35. # Create a sprite group and add a Weight
  36. sprites = pygame.sprite.RenderUpdates()
  37. sprites.add(Weight(speed))
  38. # Get the screen surface and fill it
  39. screen = pygame.display.get_surface()
  40. bg = (255, 255, 255) # White
  41. screen.fill(bg)
  42. pygame.display.flip()
  43. # Used to erase the sprites:
  44. def clear_callback(surf, rect):
  45. surf.fill(bg, rect)
  46. while True:
  47. # Check for quit events:
  48. for event in pygame.event.get():
  49. if event.type == QUIT:
  50. sys.exit()
  51. if event.type == KEYDOWN and event.key == K_ESCAPE:
  52. sys.exit()
  53. # Erase previous positions:
  54. sprites.clear(screen, clear_callback)
  55. # Update all sprites:
  56. sprites.update()
  57. # Draw all sprites:
  58. updates = sprites.draw(screen)
  59. # Update the necessary parts of the display:
  60. pygame.display.update(updates)