##==================================================================## ## 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 import sys import random from gettext import gettext as _ from pygame.locals import * ##=========================## ##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 = 120 CARROTMAXSIZE = 150 #CARROT VELOCITY CARROTMINVEL= 4 CARROTMAXVEL = 6 #CARROT VELOCITY FRECUENCY CARROTVELFREC = 25 #BUNNY MOVING VELOCITY BUNNYMOVEVEL = 15 score=0 class MBSprite(pygame.sprite.Sprite): def __init__(self, image): self.image = image #Images.__init__(self) self.mask = pygame.mask.from_surface(self.image) # pixelmask #self.mask.invert() self.rect=image.get_rect() class Carrots(MBSprite) : def __init__(self, image): carrotSize = random.randint(CARROTMINSIZE, CARROTMAXSIZE) image=pygame.transform.scale(image, (carrotSize, carrotSize)) MBSprite.__init__(self,image) self.rect = pygame.Rect(random.randint(0, WINDOWWIDTH-carrotSize), 0 - carrotSize, carrotSize, carrotSize) self.velocity = random.randint(CARROTMINVEL, CARROTMAXVEL) self.number =random.randint(max(result-5,1), min(99,result+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) # 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') carrotImage = pygame.image.load('./media/images/Carrots.png') bunnyImageF=MBSprite(bunnyImage) carrotImageF=MBSprite(carrotImage) rectBunny = bunnyImageF.rect #rectBunny = bunnyImage.get_rect()thBunnyFunc.py", line 148, in bunnyEatsCarrot #rectCarrot = carrotImage.get_rect() ##=========================## ##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(bunnyImage, carrots): for b in carrots: #if bunnyImageF.rect.colliderect(b.rect): print 'offset '+ str(carrotImageF.rect[0]-bunnyImageF.rect[0])+', '+str(carrotImageF.rect[1]-bunnyImageF.rect[1]) print 'Carrot: ' + str(carrotImageF.rect) if pygame.sprite.collide_mask(bunnyImageF,b): return True return False def checkResult(result,carrots): global score for b in carrots: if result==b.number: score=score+20 return True if score>0: score=score-5 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) #Fonts font = pygame.font.SysFont(None, 80) #font = pygame.font.Font("./mediadef drawText(text, font, surface, x, y, color):/fonts/space age.ttf", 50) #Max Points maxScore = 0 result=0 ''' 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.') ''' # Mostrar la pantalla de Inicio drawText(_('MATH BUNNY'), font, surface, (WINDOWWIDTH / 2.75), (WINDOWHEIGHT / 2.5), TITLECOLOR) drawText(_('PRESS ANY KEY'), font, surface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2.5) + 80, TITLECOLOR) pygame.display.update() waitPlayerPressKey() ##============================## ## 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 = [] 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) number1 = random.randint(0,49) + 1 number2 = random.randint(0,49) result=number1+number2 while True: # Scobre 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) # 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=Carrots(carrotImage) 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.image, b.rect) drawText(str(b.number), font, b.image, 45, 55, (255,255,255)) # Show score and maximum score drawText(_('SCORE: %s') % (score), font, surface, 700, 0, TEXTCOLOR) drawText(_('MAX SCORE: %s') % (maxScore), font, surface, 700, 60, TEXTCOLOR) drawText(_('OPERATION: %d + %d') % (number1,number2), font, surface, 10, 0, TEXTCOLOR) pygame.display.update() # Verifica si es que algun enemigo ha colisionado con el jugador. # if bunnyEatsCarrot(rectBunny, carrots): bunnyImageF.rect=rectBunny if bunnyEatsCarrot(bunnyImage, carrots): if checkResult(result,carrots): drawText(_('CORRECT ANSWER!'), font, surface, (WINDOWWIDTH / 3.5), (WINDOWHEIGHT / 2.25), TEXTCOLOR) drawText(_('PRESS ANY KEY'), font, surface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2.25) + 50, TEXTCOLOR) if score> maxScore: maxScore = score # Puts new score else: drawText(_('BAD ANSWER!'), font, surface, (WINDOWWIDTH / 2.85), (WINDOWHEIGHT / 2.25), TEXTCOLOR) drawText(_('PRESS ANY KEY'), font, surface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2.25) + 50, TEXTCOLOR) gameOverSound.play() break mainClock.tick(FPS) # Stops game and shows end message #pygame.mixer.music.stop() pygame.display.update() waitPlayerPressKey() gameOverSound.stop()