import pygame def run_game(): name = raw_input("Please type in your name: ") ## Initialize the pygame submodules and set up the display window. pygame.init() width = 640 height = 480 screen = pygame.display.set_mode((width,height)) ## Load resources balloon = pygame.image.load("red_balloon.gif") balloon = balloon.convert() balloon2 = pygame.image.load("green_balloon.gif") balloon2 = balloon2.convert() pop_sound = pygame.mixer.Sound("pop.wav") # NEW: We are loading a font myFont = pygame.font.Font(None,30) ## Initialize game objects. # initialize the balloons' positions and speeds b_red = [100, 100, 0.2, 0.2, balloon] b_green = [300, 300, 0.1, 0.2, balloon2] balloons = [b_red, b_green] w = balloon.get_width() h = balloon.get_height() # initialize the score score = 0 scorefile = "hiscores.txt" clock = pygame.time.Clock() dead = False ## GAME LOOP starts keepGoing = True while (keepGoing): ## Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False # If the player clicks into the red balloon, he gets a # point. The game also plays a popping sound and the # balloon starts moving a bit faster. # If the player clicks outside the red balloon, he dies. elif not dead and event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() if mouse_x >= b_red[0] and mouse_x <= b_red[0]+w and mouse_y >= b_red[1] and mouse_y <= b_red[1]+h: pop_sound.play() score = score + 1 b_red[2] = 1.1 * b_red[2] b_red[3] = 1.1 * b_red[3] else: dead = True ## Update game objects. dt = clock.tick() # Update the positions and speeds of the balloons. if not dead: for b in balloons: b[0] = b[0] + dt * b[2] if (b[0] < 0): b[0] = 0 b[2] = - b[2] elif (b[0] > width - w): b[0] = width - w b[2] = - b[2] b[1] = b[1] + dt * b[3] if (b[1] < 0): b[1] = 0 b[3] = - b[3] elif (b[1] > height - h): b[1] = height - h b[3] = - b[3] ## Draw picture and update display. screen.fill(pygame.color.Color("darkblue")) # score x = 10 y = 10 label = myFont.render("Your score: "+str(score), True, pygame.color.Color("magenta")) screen.blit(label, (x,y)) # balloon images screen.blit(b_red[4],(b_red[0],b_red[1])) screen.blit(b_green[4],(b_green[0],b_green[1])) # game over message if dead: label = myFont.render("Sorry, "+name+"! Game over!", True, pygame.color.Color("magenta")) screen.blit(label, ((width-label.get_width())/2,height/2-50)) label = myFont.render("You didn't click on the red balloon.", True, pygame.color.Color("magenta")) screen.blit(label, ((width-label.get_width())/2,height/2-25)) pygame.display.update() ## GAME LOOP ends myFont = None pygame.quit() run_game()