Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/run.py
blob: 7b2b804bcc419b4f766a22eed4fc103e2127b6a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
##==================================================================##
##                            MATH BUNNY	                        ##
##==================================================================##
## Based on PyGame Game Asteroides                                  ##
##                                                                  ##
## Version: 0.1 (20-08-2010)                                        ##
## 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 *

##=========================##
##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 = 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()

#Loading 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 Method
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 if user press scape key
                    closeGame()
                return
            if event.type == MOUSEBUTTONDOWN:
                return
            if event.type == JOYBUTTONDOWN:            
                return
            
#Bunny Eats a Carrot Method
def bunnyEatsCarrot(bunnyImage, carrots):
    for b in carrots:
        #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 screenine
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():
    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'))
    # Mouse Visibility
    pygame.mouse.set_visible(False)


    # Sounds
    gameOverSound = pygame.mixer.Sound('./media/sounds/gameover.wav')
    #pygame.mixer.music.load('./media/sounds/background.mid')





    ##=========================##
    ##Methods                  ##
    ##=========================##


    #Fonts
    font = pygame.font.SysFont(None, 80)
    #font = pygame.font.Font("./mediadef drawText(text, font, surface, x, y, color):/fonts/space age.ttf", 50)


    # 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()


    ##============================##
    ## 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 - 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

            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
                    #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
                        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 = 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)


            # 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=Carrots(carrotImage)
                carrots.append(newCarrot)
                
            # Moves player
            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)


            # Draw enemies
            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
            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()
        
            # 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()
        
         
        pygame.display.update()
        waitPlayerPressKey()
        
        gameOverSound.stop()


if __name__ == "__main__":
    main()