##==================================================================## ## MATH BUNNY ## ##==================================================================## ## Based on PyGame Game Asteroides ## ## ## ## Version: 0.1 (20-08-2010) ## ## Desarrollado por: Ricardo Flores S. ## ## Class: Constants.py ## ## Programa desarrollado bajo licencia Creative Commons ## ##==================================================================## import pygame, random, sys from pygame.locals import * ##=========================## ##Declaracion de metodos ## ##=========================## #Close Game Method def closeGame(): pygame.quit() sys.exit() #Load Image Method def load_image(fileName): try: image = pygame.image.load(fileName) except pygame.error: raise SystemExit image = image.convert() return image #Wait Player to Press Key def waitPlayerPressKey(): while True: for event in pygame.event.get(): if event.type == QUIT: closeGame() if event.type == KEYDOWN : if event.key == K_ESCAPE: # Close game pressing escape key closeGame() return if event.type == MOUSEBUTTONDOWN: return if event.type == JOYBUTTONDOWN: return #Bunny Eats a Carrot def bunnyEatsCarrot(rectBunny, carrots): for b in carrots: if rectBunny.colliderect(b['rect']): return True return False #Draw text on the screen def drawText(text, font, surface, x, y, color): text = font.render(text, 1, color) rectText = text.get_rect() rectText.topleft = (x, y) surface.blit(text, rectText) def main(): ##=========================## ##Constants: ## ##=========================## #Screen Size WINDOWWIDTH = 1200 WINDOWHEIGHT = 900 #Text Color TEXTCOLOR = (0, 0, 0) TITLECOLOR = (173, 255, 47) #Background Color BACKGROUNDCOLOR = (0, 0, 0) #FPS: FPS = 35 #CARROT SIZE CARROTMINSIZE = 50 CARROTMAXSIZE = 80 #CARROT VELOCITY CARROTMINVEL= 2 CARROTMAXVEL = 8 #CARROT VELOCITY FRECUENCY CARROTVELFREC = 20 #BUNNY MOVING VELOCITY BUNNYMOVEVEL = 5 # Initialize Pygame, window and mouse pointer pygame.init() mainClock = pygame.time.Clock() surface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # Window Title pygame.display.set_caption('Math Bunny') # Mouse Visibility pygame.mouse.set_visible(False) ''' JoyStick Functions Disabled #Initialize Joystick pygame.joystick.init() try: # Instantiate Joystick j = pygame.joystick.Joystick(0) # Initialize Joystick j.init() print ('Joystick tipo: ' + j.get_name()) print (' '+ str(j.get_numbuttons())+ ' botones') print (' '+ str(j.get_numhats())+ ' hats') print (' '+ str(j.get_numaxes())+ ' axis') except pygame.error: print ('Joystick not found.') ''' # Sounds gameOverSound = pygame.mixer.Sound('./media/sounds/gameover.wav') #pygame.mixer.music.load('./media/sounds/background.mid') # Images bunnyImage = pygame.image.load('./media/images/bunny.gif') bunnyImage.get_alpha() rectBunny = bunnyImage.get_rect() carrotImage = pygame.image.load('./media/images/Carrots.png') carrotImage.get_alpha() #Fonts #font = pygame.font.SysFont(None, 35) font = pygame.font.Font("./media/fonts/space age.ttf", 25) # Mostrar la pantalla de Inicio drawText('Math Bunny', font, surface, (WINDOWWIDTH / 2.45), (WINDOWHEIGHT / 2.5), TITLECOLOR) drawText('Press any key', font, surface, (WINDOWWIDTH / 4.25), (WINDOWHEIGHT / 2.5) + 50, TITLECOLOR) pygame.display.update() waitPlayerPressKey() #Max Points maxScore = 0 ##============================## ## Game start ## ##============================## while True: screen = pygame.display.set_mode( (WINDOWWIDTH,WINDOWHEIGHT) ) background = load_image('./media/images/farm.jpg'); screen.blit(background, (0,0) ) #pygame.display.flip() # Initialize game start carrots = [] score = 0 rectBunny.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50) moveLeft = moveRight = moveUp = moveDown = False #Game Cheat carrotsBack = carrotsSlow = carrotsQuick = False newCarrotCounter = 0 pygame.mixer.music.play(-1, 0.0) while True: # Score loop score += 1 # increase score for event in pygame.event.get(): if event.type == QUIT: closeGame() # KEYDOWN EVENTS if event.type == KEYDOWN: if event.key == ord('z'): carrotsBack = True if event.key == ord('x'): carrotsSlow = True if event.key == ord('c'): carrotsQuick = True if event.key == K_LEFT or event.key == ord('a') or event.key == K_KP4 or event.key== K_KP7: moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == ord('d') or event.key == K_KP6 or event.key== K_KP1: moveLeft = False moveRight = True if event.key == K_UP or event.key == ord('w') or event.key == K_KP8 or event.key== K_KP9: moveDown = False moveUp = True if event.key == K_DOWN or event.key == ord('s') or event.key == K_KP2 or event.key== K_KP3: moveUp = False moveDown = True # KEYUP events if event.type == KEYUP: if event.key == ord('z'): carrotsBack = False score = 0 if event.key == ord('x'): carrotsSlow = False score = 0 if event.key == ord('c'): carrotsQuick = False score= 0 if event.key == K_ESCAPE: closeGame() if event.key == K_LEFT or event.key == ord('a') or event.key == K_KP4 or event.key== K_KP7: moveLeft = False if event.key == K_RIGHT or event.key == ord('d') or event.key == K_KP6 or event.key== K_KP1: moveRight = False if event.key == K_UP or event.key == ord('w') or event.key == K_KP8 or event.key== K_KP9: moveUp = False if event.key == K_DOWN or event.key == ord('s') or event.key == K_KP2 or event.key== K_KP3: moveDown = False # MOUSEMOTION events if event.type == MOUSEMOTION: # Follow mouse pointer rectBunny.move_ip(event.pos[0] - rectBunny.centerx, event.pos[1] - rectBunny.centery) #rectBunny.move_ip(event.pos[0] - rectBunny.centerx, 0) #JOYTICK EVENTS if event.type == JOYAXISMOTION: x1 , y1, x2, y2 = j.get_axis(0), j.get_axis(1), j.get_axis(2), j.get_axis(3) print ('x1 e y1 : ' + str(x1) +' , '+ str(y1)) print ('x2 e y2 : ' + str(x2) +' , ' + str(y2)) #Axis movement on JOYSTICK if(j.get_axis(0)<0): moveRight = False moveLeft = True if(j.get_axis(0)>0): moveLeft = False moveRight = True if(j.get_axis(1)>0): moveUp = False moveDown = True if(j.get_axis(1)<0): moveDown = False moveUp = True if(j.get_axis(0)<0 and j.get_axis(1)<0): moveRight = False moveLeft = True moveDown = False moveUp = True if(j.get_axis(0)<0 and j.get_axis(1)>0): moveRight = False moveLeft = True moveDown = True moveUp = False if(j.get_axis(0)>0 and j.get_axis(1)<0): moveLeft = False moveRight = True moveDown = False moveUp = True if(j.get_axis(0)>0 and j.get_axis(1)>0): moveLeft = False moveRight = True moveDown = True moveUp = False if(j.get_axis(0)==0): moveRight = False moveLeft = False if(j.get_axis(1)==0): moveDown = False moveUp = False if(x1==0 or y1==0): moveRight = False moveLeft = False moveDown = False moveUp = False #Joystick Directional Keys movement elif event.type == JOYHATMOTION: print ('hat motion') print(str(j.get_hat(0))) if(j.get_hat(0)==(-1,0)): moveRight = False moveLeft = True if(j.get_hat(0)==(0,1)): moveDown = False moveUp = True if(j.get_hat(0)==(1,0)): moveLeft = False moveRight = True if(j.get_hat(0)==(0,-1)): moveUp = False moveDown = True if(j.get_hat(0)==(-1,1)): moveUp = True moveLeft = True if(j.get_hat(0)==(1,1)): moveRight = True moveUp = True if(j.get_hat(0)==(1,-1)): moveRight = True moveDown = True if(j.get_hat(0)==(-1,-1)): moveLeft = True moveDown = True if(j.get_hat(0)==(0,0)): moveUp = False moveDown = False moveRight = False moveLeft = False #Joystick ball movement elif event.type == pygame.locals.JOYBALLMOTION: print ('Joystick ball movement') #JOYSTICKBUTTONDOWN event elif event.type == pygame.locals.JOYBUTTONDOWN: print ('JOYSTICKBUTTONDOWN event') print(' boton 0 state: '+str(j.get_button(0))) #Evento de Joystick de boton suelto elif event.type == pygame.locals.JOYBUTTONUP: print ('JOYBUTTONUP event') # New carrots on the screen if not carrotsBack and not carrotsSlow and not carrotsQuick: newCarrotCounter += 1 if newCarrotCounter == CARROTVELFREC: newCarrotCounter = 0 carrotSize = random.randint(CARROTMINSIZE, CARROTMAXSIZE) newCarrot = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-carrotSize), 0 - carrotSize, carrotSize, carrotSize), 'velocity': random.randint(CARROTMINVEL, CARROTMAXVEL), 'surface':pygame.transform.scale(carrotImage, (carrotSize, carrotSize)), } carrots.append(newCarrot) # Realiza el movimiento del jugador. if moveLeft and rectBunny.left > 0: rectBunny.move_ip(-1 * BUNNYMOVEVEL, 0) if moveRight and rectBunny.right < WINDOWWIDTH: rectBunny.move_ip(BUNNYMOVEVEL, 0) if moveUp and rectBunny.top > 0: rectBunny.move_ip(0, -1 * BUNNYMOVEVEL) if moveDown and rectBunny.bottom < WINDOWHEIGHT: rectBunny.move_ip(0, BUNNYMOVEVEL) # Puts Bunny on the mouse pointer pygame.mouse.set_pos(rectBunny.centerx, rectBunny.centery) # Move carrots down for b in carrots: if not carrotsBack and not carrotsSlow and not carrotsQuick: b['rect'].move_ip(0, b['velocity']) elif carrotsBack: b['rect'].move_ip(0, -5) elif carrotsSlow: b['rect'].move_ip(0, 1) elif carrotsQuick: b['rect'].move_ip(0, 5) # Delete carrots when you can't see it on the screen for b in carrots[:]: if b['rect'].top > WINDOWHEIGHT: carrots.remove(b) # Draw background on game screen.blit(background, (0,0) ) #surface.fill(BACKGROUNDCOLOR) # Draw player rectangle surface.blit(bunnyImage, rectBunny) # Dibuja a cada enemigo for b in carrots: surface.blit(b['surface'], b['rect']) # Show score and maximum score drawText('Score: %s' % (score), font, surface, 10, 0, TEXTCOLOR) drawText('Max Score: %s' % (maxScore), font, surface, 10, 40, TEXTCOLOR) pygame.display.update() # Verifica si es que algun enemigo ha colisionado con el jugador. if bunnyEatsCarrot(rectBunny, carrots): if score> maxScore: maxScore = score # Puts new score break mainClock.tick(FPS) # Stops game and shows end message pygame.mixer.music.stop() gameOverSound.play() drawText('Bunny impacts a carrot', font, surface, (WINDOWWIDTH / 3.75), (WINDOWHEIGHT / 2.25), TEXTCOLOR) drawText('Press any key', font, surface, (WINDOWWIDTH / 3.40), (WINDOWHEIGHT / 2.25) + 50, TEXTCOLOR) pygame.display.update() waitPlayerPressKey() gameOverSound.stop()