from pygame import * from pygame.sprite import * from random import * class Mole(Sprite): def __init__(self): Sprite.__init__(self) self.image = image.load("mole02.gif").convert() self.rect = self.image.get_rect() # Called when the mole is hit # Moves to a random location def flee(self): randx = randint(0, 600) randy = randint(0, 400) self.rect.center = (randx, randy) class Shovel(Sprite): def __init__(self): Sprite.__init__(self) self.image = image.load("shovel.gif").convert() self.rect = self.image.get_rect() # Determines whether the shovel hit the mole def hit(self, target): return self.rect.colliderect(target) # Follows the mouse cursor def update(self): self.rect.center = mouse.get_pos() # main init() screen = display.set_mode((640, 480)) display.set_caption('Whack-a-mole') # Hide the mouse cursor mouse.set_visible(False) # Read more about fonts in the Font part of the API f = font.Font(None, 25) hits = 0 mole = Mole() shovel = Shovel() # Creates a group of sprites so all can be updated at once sprites = RenderPlain(shovel, mole) while True: ev = event.poll() if ev.type == QUIT: quit() break # Read more about events under the Event part of the API elif ev.type == MOUSEBUTTONDOWN: if shovel.hit(mole): mixer.Sound("hit.wav").play() hits += 1 mole.flee() # Cover everything in white so that we can paint sprites in new locations screen.fill(Color("white")) t = f.render("Hits: " + str(hits), True, (0, 0, 0)) # Draw the text to the screen screen.blit(t, (320, 0)) # Update and redraw all sprites sprites.update() sprites.draw(screen) display.update()