Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/runMathBunnyFunc.py
blob: a09ab77d787d2cbd076ae09e7d946141d862e979 (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
##==================================================================##
##                            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 *


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


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


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