From fd913c2048db2a3585b2d2c4acb3030a45dcd5d0 Mon Sep 17 00:00:00 2001 From: Ricardo Flores Date: Thu, 23 Sep 2010 16:07:12 +0000 Subject: This version works on xo 1 and 1.5 --- diff --git a/run.py b/run.py index 256a673..7b2b804 100644 --- a/run.py +++ b/run.py @@ -1,36 +1,104 @@ -#! /usr/bin/env python -"""Skeleton project file mainloop for new OLPCGames users""" -import olpcgames, pygame, logging, random, sys -from olpcgames import pausescreen -from pygame.locals import * - -log = logging.getLogger( 'MathBunny run' ) -log.setLevel( logging.DEBUG ) - ##==================================================================## -## MATH BUNNY ## +## 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 ## +## Developed by: Ricardo Flores S. ## +## Class: Constants.py ## +## Program developed under Creative Commons License ## ##==================================================================## - +import pygame +import sys +import random +from gettext import gettext as _ +from pygame.locals import * ##=========================## -##Declaracion de metodos ## +##Constants: ## ##=========================## -#Close Game Method + +#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 = 130 +CARROTMAXSIZE = 140 + +#CARROT VELOCITY +CARROTMINVEL= 4 +CARROTMAXVEL = 8 + +#CARROT VELOCITY FRECUENCY +CARROTVELFREC = 30 + +#BUNNY MOVING VELOCITY +BUNNYMOVEVEL = 15 + +#SCORES +maxScore = 0 +score =0 +#OPERATION RESUlT +result=0 +#IMAGES SIZE +bunnySize=175 + +# IMAGES +bunnyImage = pygame.image.load('./media/images/bunny.gif') +bunnyImage=pygame.transform.scale(bunnyImage, (bunnySize, bunnySize)) +carrotImage = pygame.image.load('./media/images/Carrots.png') + +#NUMBERS +number1=0 +number2=0 +result=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)) + +bunnyImageF=MBSprite(bunnyImage) +carrotImageF=MBSprite(carrotImage) +rectBunny = bunnyImageF.rect +#rectBunny = bunnyImage.get_rect()thBunnyFunc.py" +#rectCarrot = carrotImage.get_rect() + +#Closing Game Method def closeGame(): pygame.quit() sys.exit() -#Load Image Method +#Loading Image Method def load_image(fileName): try: image = pygame.image.load(fileName) except pygame.error: @@ -39,15 +107,15 @@ def load_image(fileName): return image -#Wait Player to Press Key +#Wait Player to Press Key Method def waitPlayerPressKey(): while True: for event in pygame.event.get(): if event.type == QUIT: closeGame() - if event.type == KEYDOWN : + if event.type == KEYDOWN: if event.key == K_ESCAPE: - # Close game pressing escape key + # Close game if user press scape key closeGame() return if event.type == MOUSEBUTTONDOWN: @@ -55,16 +123,25 @@ def waitPlayerPressKey(): if event.type == JOYBUTTONDOWN: return - -#Bunny Eats a Carrot -def bunnyEatsCarrot(rectBunny, carrots): +#Bunny Eats a Carrot Method +def bunnyEatsCarrot(bunnyImage, carrots): for b in carrots: - if rectBunny.colliderect(b['rect']): + #if bunnyImageF.rect.colliderect(b.rect):py" -> Check collisions if use 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 +#Draw text on the screenine def drawText(text, font, surface, x, y, color): text = font.render(text, 1, color) rectText = text.get_rect() @@ -74,150 +151,74 @@ def drawText(text, font, surface, x, y, color): - def main(): - """The mainloop which is specified in the activity.py file - - "main" is the assumed function name - """ - size = (800,600) - if olpcgames.ACTIVITY: - size = olpcgames.ACTIVITY.game_size - screen = pygame.display.set_mode(size) - - clock = pygame.time.Clock() - - running = True - - - - ##=========================## - ##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 - - + global score # 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') + 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') - ''' - 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') + ##=========================## + ##Methods ## + ##=========================## - # 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) + font = pygame.font.SysFont(None, 80) + #font = pygame.font.Font("./mediadef drawText(text, font, surface, x, y, color):/fonts/space age.ttf", 50) - # 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) + # Show start window + 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() - #Max Points - maxScore = 0 - while running: - screen.fill( (0,0,128)) - milliseconds = clock.tick(25) # maximum number of frames per second - - # Event-management loop with support for pausing after X seconds (20 here) - events = pausescreen.get_events() - # Now the main event-processing loop - if events: - for event in events: - log.debug( "Event: %s", event ) - if event.type == pygame.QUIT: - running = False - elif event.type == pygame.KEYDOWN: - if event.key == pygame.K_ESCAPE: - running = False - pygame.display.flip() - - screen = pygame.display.set_mode( (WINDOWWIDTH,WINDOWHEIGHT) ) + ##============================## + ## 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) + + rectBunny.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 175) moveLeft = moveRight = moveUp = moveDown = False #Game Cheat carrotsBack = carrotsSlow = carrotsQuick = False newCarrotCounter = 0 #pygame.mixer.music.play(-1, 0.0) + global number1 + global number2 + number1 = random.randint(0,49) + 1 + number2 = random.randint(0,49) + global result + result=number1+number2 + print 'number1: '+str(number1)+' number2: '+str(number2)+' result: '+str(result) + while True: # Scobre loop + #score += 1 # increase score - while True: # Score loop - score += 1 # increase score - for event in pygame.event.get(): if event.type == QUIT: closeGame() @@ -235,14 +236,15 @@ def main(): 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 + #Up and Down moves disabled + #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 @@ -254,142 +256,38 @@ def main(): carrotsQuick = False score= 0 if event.key == K_ESCAPE: - closeGame() + 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 + moveRight = Falseresult=0 + #Up and Down moves disabled + #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 + # 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 - + #rectBunny.move_ip(event.pos[0] - rectBunny.centerx, event.pos[1] - rectBunny.centery) + + rectBunny.move_ip(event.pos[0] - rectBunny.centerx, 0) - #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 + # Add 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)), - } - + #carrotSize = random.randint(CARROTMINSIZE, CARROTMAXSIZE) + + newCarrot=Carrots(carrotImage) carrots.append(newCarrot) - - # Realiza el movimiento del jugador. + + # Moves player if moveLeft and rectBunny.left > 0: rectBunny.move_ip(-1 * BUNNYMOVEVEL, 0) if moveRight and rectBunny.right < WINDOWWIDTH: @@ -405,17 +303,17 @@ def main(): # Move carrots down for b in carrots: if not carrotsBack and not carrotsSlow and not carrotsQuick: - b['rect'].move_ip(0, b['velocity']) + b.rect.move_ip(0, b.velocity) elif carrotsBack: - b['rect'].move_ip(0, -5) + b.rect.move_ip(0, -5) elif carrotsSlow: - b['rect'].move_ip(0, 1) + b.rect.move_ip(0, 1) elif carrotsQuick: - b['rect'].move_ip(0, 5) + b.rect.move_ip(0, 5) - # Delete carrots when you can't see it on the screen + # Delete carrots when you can't see it on the screen for b in carrots[:]: - if b['rect'].top > WINDOWHEIGHT: + if b.rect.top > WINDOWHEIGHT: carrots.remove(b) # Draw background on game @@ -423,41 +321,56 @@ def main(): #surface.fill(BACKGROUNDCOLOR) # Draw player rectangle + surface.blit(bunnyImage, rectBunny) - # Dibuja a cada enemigo + # Draw enemies for b in carrots: - surface.blit(b['surface'], b['rect']) + + 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, 10, 0, TEXTCOLOR) - drawText('Max Score: %s' % (maxScore), font, surface, 10, 40, TEXTCOLOR) - + global maxScore + global 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): - if score> maxScore: - maxScore = score # Puts new score + # Verify if Bunny eat carrot + #if bunnyEatsCarrot(rectBunny, carrots): + bunnyImageF.rect=rectBunny + + + if bunnyEatsCarrot(bunnyImage, carrots): + #print 'if bunnyEatsCarrot(bunnyImage, carrots): score: '+str(score) + 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() - 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() + gameOverSound.stop() + if __name__ == "__main__": - logging.basicConfig() main() -- cgit v0.9.1