chimp.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #!/usr/bin/env python
  2. """
  3. This simple example is used for the line-by-line tutorial
  4. that comes with pygame. It is based on a 'popular' web banner.
  5. Note there are comments here, but for the full explanation,
  6. follow along in the tutorial.
  7. """
  8. # Import Modules
  9. import os, pygame
  10. from pygame.locals import *
  11. from pygame.compat import geterror
  12. if not pygame.font: print('Warning, fonts disabled')
  13. if not pygame.mixer: print('Warning, sound disabled')
  14. main_dir = os.path.split(os.path.abspath(__file__))[0]
  15. data_dir = os.path.join(main_dir, 'data')
  16. # functions to create our resources
  17. def load_image(name, colorkey=None):
  18. fullname = os.path.join(data_dir, name)
  19. try:
  20. image = pygame.image.load(fullname)
  21. except pygame.error:
  22. print('Cannot load image:', fullname)
  23. raise SystemExit(str(geterror()))
  24. image = image.convert()
  25. if colorkey is not None:
  26. if colorkey is -1:
  27. colorkey = image.get_at((0, 0))
  28. image.set_colorkey(colorkey, RLEACCEL)
  29. return image, image.get_rect()
  30. def load_sound(name):
  31. class NoneSound:
  32. def play(self): pass
  33. if not pygame.mixer or not pygame.mixer.get_init():
  34. return NoneSound()
  35. fullname = os.path.join(data_dir, name)
  36. try:
  37. sound = pygame.mixer.Sound(fullname)
  38. except pygame.error:
  39. print('Cannot load sound: %s' % fullname)
  40. raise SystemExit(str(geterror()))
  41. return sound
  42. # classes for our game objects
  43. class Fist(pygame.sprite.Sprite):
  44. """moves a clenched fist on the screen, following the mouse"""
  45. def __init__(self):
  46. pygame.sprite.Sprite.__init__(self) #call Sprite initializer
  47. self.image, self.rect = load_image('fist.bmp', -1)
  48. self.punching = 0
  49. def update(self):
  50. """move the fist based on the mouse position"""
  51. pos = pygame.mouse.get_pos()
  52. self.rect.midtop = pos
  53. if self.punching:
  54. self.rect.move_ip(5, 10)
  55. def punch(self, target):
  56. """returns true if the fist collides with the target"""
  57. if not self.punching:
  58. self.punching = 1
  59. hitbox = self.rect.inflate(-5, -5)
  60. return hitbox.colliderect(target.rect)
  61. def unpunch(self):
  62. """called to pull the fist back"""
  63. self.punching = 0
  64. class Chimp(pygame.sprite.Sprite):
  65. """moves a monkey critter across the screen. it can spin the
  66. monkey when it is punched."""
  67. def __init__(self):
  68. pygame.sprite.Sprite.__init__(self) # call Sprite intializer
  69. self.image, self.rect = load_image('chimp.bmp', -1)
  70. screen = pygame.display.get_surface()
  71. self.area = screen.get_rect()
  72. self.rect.topleft = 10, 10
  73. self.move = 9
  74. self.dizzy = 0
  75. def update(self):
  76. """walk or spin, depending on the monkeys state"""
  77. if self.dizzy:
  78. self._spin()
  79. else:
  80. self._walk()
  81. def _walk(self):
  82. """move the monkey across the screen, and turn at the ends"""
  83. newpos = self.rect.move((self.move, 0))
  84. if not self.area.contains(newpos):
  85. if self.rect.left < self.area.left or \
  86. self.rect.right > self.area.right:
  87. self.move = -self.move
  88. newpos = self.rect.move((self.move, 0))
  89. self.image = pygame.transform.flip(self.image, 1, 0)
  90. self.rect = newpos
  91. def _spin(self):
  92. """spin the monkey image"""
  93. center = self.rect.center
  94. self.dizzy = self.dizzy + 12
  95. if self.dizzy >= 360:
  96. self.dizzy = 0
  97. self.image = self.original
  98. else:
  99. rotate = pygame.transform.rotate
  100. self.image = rotate(self.original, self.dizzy)
  101. self.rect = self.image.get_rect(center=center)
  102. def punched(self):
  103. """this will cause the monkey to start spinning"""
  104. if not self.dizzy:
  105. self.dizzy = 1
  106. self.original = self.image
  107. def main():
  108. """this function is called when the program starts.
  109. it initializes everything it needs, then runs in
  110. a loop until the function returns."""
  111. # Initialize Everything
  112. pygame.init()
  113. screen = pygame.display.set_mode((468, 60))
  114. pygame.display.set_caption('Monkey Fever')
  115. pygame.mouse.set_visible(0)
  116. # Create The Backgound
  117. background = pygame.Surface(screen.get_size())
  118. background = background.convert()
  119. background.fill((250, 250, 250))
  120. # Put Text On The Background, Centered
  121. if pygame.font:
  122. font = pygame.font.Font(None, 36)
  123. text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10))
  124. textpos = text.get_rect(centerx=background.get_width()/2)
  125. background.blit(text, textpos)
  126. # Display The Background
  127. screen.blit(background, (0, 0))
  128. pygame.display.flip()
  129. # Prepare Game Objects
  130. clock = pygame.time.Clock()
  131. whiff_sound = load_sound('whiff.wav')
  132. punch_sound = load_sound('punch.wav')
  133. chimp = Chimp()
  134. fist = Fist()
  135. allsprites = pygame.sprite.RenderPlain((fist, chimp))
  136. # Main Loop
  137. going = True
  138. while going:
  139. clock.tick(60)
  140. # Handle Input Events
  141. for event in pygame.event.get():
  142. if event.type == QUIT:
  143. going = False
  144. elif event.type == KEYDOWN and event.key == K_ESCAPE:
  145. going = False
  146. elif event.type == MOUSEBUTTONDOWN:
  147. if fist.punch(chimp):
  148. punch_sound.play() # punch
  149. chimp.punched()
  150. else:
  151. whiff_sound.play() # miss
  152. elif event.type == MOUSEBUTTONUP:
  153. fist.unpunch()
  154. allsprites.update()
  155. # Draw Everything
  156. screen.blit(background, (0, 0))
  157. allsprites.draw(screen)
  158. pygame.display.flip()
  159. pygame.quit()
  160. # Game Over
  161. # this calls the 'main' function when this script is executed
  162. if __name__ == '__main__':
  163. main()