Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/game2/game2.py
blob: d1089dc681d90ca9b92b7deebefc412ffaaa40f5 (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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/usr/bin/python
# -*- coding: utf-8 -*-

import pygame
from pygame.locals import *
import usmpgames
from gettext import gettext as _
import sys
import random
import time
from usmpgames import *
#from constants import *
#from classes import *
#from methods import *

######################################## constants

GAMEMODE=4

#GAME TIME:

#CARROT SIZE
CARROTMINSIZE = 80
CARROTMAXSIZE = 90

#IMAGES SIZE
bunnySize=175

#Screen Size
WINDOWWIDTH = 1200
WINDOWHEIGHT = 900

#Text Color
TEXTCOLOR = (0, 0, 0)
TITLECOLOR = (173, 255, 47)
      
#Background Color
BACKGROUNDCOLOR = (0, 0, 0)

#FPS (Fames per Second):
FPS = 15


#CARROT VELOCITY
CARROTMINVEL= 4
CARROTMAXVEL = 8

#CARROT VELOCITY FRECUENCY
CARROTVELFREC = 20

#BUNNY MOVING VELOCITY
BUNNYMOVEVEL = 35

#SCORES
maxScore = 0
score =0
#OPERATION RESUlT
result=0


# IMAGES


fruit1Image = pygame.image.load('./media/images/fruit1.png')
fruit2Image = pygame.image.load('./media/images/fruit2.png')

happy=pygame.image.load('./media/images/happycuy.png')
happy=pygame.transform.scale(happy, (bunnySize+25, bunnySize))

sad=pygame.image.load('./media/images/sadcuy.png')
sad=pygame.transform.scale(sad, (bunnySize-25, bunnySize))

invisible=pygame.image.load('./media/images/invisible.png')
invisible=pygame.transform.scale(sad, (bunnySize-25, bunnySize))

looking=pygame.image.load('./media/images/looking.png')
looking=pygame.transform.scale(looking, (bunnySize-45, bunnySize))

#NUMBERS
number1=0
number2=0
result=0

resultChosen=0

gameOverSound = pygame.mixer.Sound('./media/sounds/gameover.wav')
correctAnswerSound = pygame.mixer.Sound('./media/sounds/aplause.ogg')
musicSound = pygame.mixer.Sound('./media/sounds/menumusic.ogg')

font = pygame.font.SysFont(None, 80)
        
gameOverSound = None
correctAnswerSound = None
musicSound = None

imageList = []
imageList2 = []
        
background = None
bunnyImage = None
bunnyImage = None

bunnyImageF = None
rectBunny = None

n = 0

class Game2(usmpgames.ApplicationState):

    def __init__(self,  game_mode,  next_state = None,  background_image = None):
        usmpgames.ApplicationState.__init__(self,  next_state,  background_image)
        self.game_mode = game_mode
        
        global gameOverSound, correctAnswerSound, musicSound
        gameOverSound = pygame.mixer.Sound('./media/sounds/gameover.wav')
        correctAnswerSound = pygame.mixer.Sound('./media/sounds/aplause.ogg')
        musicSound=pygame.mixer.Sound('./media/sounds/menumusic.ogg')
        
        image1= load_image('./media/images/reduced/cuya.gif');
        image2 = load_image('./media/images/reduced/enemy.gif');
        image3 = load_image('./media/images/reduced/enemy1.gif');   
        
        global imageList, imageList2
        imageList = [image1,image2,image3]
        imageList2 = []
        
        global bunnyImage, bunnyImage
        bunnyImage = pygame.image.load('./media/images/cuy.png')
        bunnyImage = pygame.transform.scale(bunnyImage, (bunnySize-45, bunnySize))

        global bunnyImageF, rectBunny
        bunnyImageF=MBSprite(bunnyImage)
        rectBunny = bunnyImageF.rect


    def entering_state(self, fromStack):
        usmpgames.ApplicationState.entering_state(self, fromStack)
        global n
        global GAMEMODE
        n = 0
        GAMEMODE = self.game_mode
        #Get initial time
        global TIMESTART
        TIMESTART= round(time.time(),0)
	global score, a
	score = 0
	a = 0

    def exiting_state(self, fromStack):
        global score
        self.next_state().clear_all()
        self.next_state().add_text2(
            _(""" Felicidades\n\nHas conseguido %d puntos""") % score,
            color = (0, 0, 0, 0),
            pos = (660, 260),
            rectsize = (380, 390) );
        global musicSound
        musicSound.stop()
        usmpgames.ApplicationState.exiting_state(self, fromStack)

    def loop(self,  ms):        
        global gameOverSound, correctAnswerSound, musicSound
        global imageList, imageList2        
        global background, bunnyImage, bunnyImage
        global bunnyImageF, rectBunny
        global result
        global n
        
        mainClock = pygame.time.Clock()
        a= round(time.time(),0)
        #print ('loopTime: '+str(a))
        compareTime(a, self)
        background = Application.get_resource_background ('./media/images/yard.jpg')
        self.screen().blit(background, (0,0) )
        surface = self.screen()

        #pygame.display.flip()

        # Initialize game start
        carrots = []

        rectBunny.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 250)
        moveLeft = moveRight = moveUp = moveDown = False
        #Game Cheat
        carrotsBack = carrotsSlow = carrotsQuick = False
        newCarrotCounter = 0
        #pygame.mixer.music.play(-1, 0.0)
        musicSound.play(-1)

        global number1
        global number2
        global GAMEMODE
        if(GAMEMODE==1):
            #print('n: '+str(n))
            #random.randint(max(result-4,1), min(99,result+4))
            number1 = random.randint(max(n-5,0),n) + 1
            number2 = random.randint(max(n-5,0),n)
            #result=number1+number2
            result=100
            while (result>=100):
                number1 = random.randint(max(n-5,0),n) + 1
                number2 = random.randint(max(n-5,0),n)
                result=number1+number2
                
        elif(GAMEMODE==2):
            #print('n: '+str(n))
            #random.randint(max(result-4,1), min(99,result+4))
            number1 = random.randint(max(n-15,0),n) + 1
            number2 = random.randint(max(n-15,0),n)
            z=min(number1,number2)
            number1=max(number1,number2)
            number2=z   
            while (number1==number2):
                number1 = random.randint(max(n-15,0),n) + 1
                number2 = random.randint(max(n-15,0),n)
                z=min(number1,number2)
                number1=max(number1,number2)
                number2=z
                result=number1-number2
            result=number1-number2
        elif(GAMEMODE==3):
            #print('n: '+str(n))
            #random.randint(max(result-4,1), min(99,result+4))
            number1 = random.randint(max(n-5,0),n+1)+1
            number2 = random.randint(max(n-5,0),n+1)+1
            while (number1>10 or number2 >10):
                number1 = random.randint(max(n-5,0),n+1)+1
                number2 = random.randint(max(n-5,0),n+1)+1
                result=number1*number2    
            result=number1*number2
        elif(GAMEMODE==4):
            #print('n: '+str(n))
            #random.randint(max(result-4,1), min(99,result+4))
            number1 = random.randint(1,9)
            #number1=9
            #number2 = random.randint(max(0,n-1),n)+1
            #result=number1+result2
            result=number1
            putImagesToList()


        #print ('number1: '+str(number1)+' number2: '+str(number2)+' result: '+str(result))
        while self.running(): # Score loop
            #score += 1 # increase score

            for event in pygame.event.get():
                if event.type == QUIT:
                    self.set_running( False ) 
                # 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    while(i<number1):

                    #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:
                        self.set_running( False ) 

                    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 = FalscorrectAnswerSounderesult=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)  
                a=random.randint(0, 1)  
                if(a==0):
                    newCarrot=Carrots(fruit1Image,result)
                else:
                    newCarrot=Carrots(fruit2Image,result)
                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-150:
                    carrots.remove(b)

            # Draw background on game
            background = Application.get_resource_background ('./media/images/yard.jpg')
            self.screen().blit(background, (0,0) )
            #surface.fill(BACKGROUNDCOLOR)

            # Draw enemies
            for b in carrots:                
                surface.blit(b.image, b.rect)
                drawText(str(b.number), font, b.image, 15, 25, (255,255,255))

           # Show score and maximum score
            global maxScore
            global score
            drawText(_('PUNTAJE: %s') % (score), font, surface, 700, 0, TEXTCOLOR)
            drawText(_('MAXIMO: %s') % (maxScore), font, surface, 700, 60, TEXTCOLOR)

            if(GAMEMODE==1):
                #This draw the operation
                drawText(_('SUMAR: %d + %d') % (number1,number2), font, surface, 10, 0, TEXTCOLOR)

            elif(GAMEMODE==2):
                #This draw the operation
                drawText(_('RESTAR: %d - %d') % (number1,number2), font, surface, 10, 0, TEXTCOLOR)

            elif(GAMEMODE==3):
                #This draw the operation
		drawText(_('MULTIPLICAR: %d x %d') % (number1,number2), font, surface, 10, 0, TEXTCOLOR)

            elif(GAMEMODE==4):
                #This draw the operation
                drawText(_('CONTAR '), font, surface, 10, 0, TEXTCOLOR)
                medC=0
                i=0
                while(i<number1):            
                    #print('Iteracion: '+str(i))
                    surface.blit(imageList2[i], (10+medC,60) )
                    medC=medC+65
                    i=i+1

            # Verify if Bunny eat carrot
            #if bunnyEatsC                    pygame.time.delay(2000)arrot(rectBunny, carrots):
            bunnyImageF.rect=rectBunny

            if bunnyEatsCarrot(bunnyImage, carrots):  
                #print ('bunnyEatsCarrot(before): MaxScore'+str(maxScore)+' score: '+str(maxScore))
                #print 'if bunnyEatsCarrot(bunnyImage, carrots): score: '+str(score)
                
                if checkResult(result):
                    rectBunny.move_ip(-35, 0)
                    #surface.blit(happy, rectBunny)
                    surface.blit(happy, rectBunny)
                    drawText(_('RESPUESTA CORRECTA!'), font, surface, (WINDOWWIDTH / 3.5), (WINDOWHEIGHT / 2.25), TEXTCOLOR)
                    if(GAMEMODE==3):
                        n=n+1
                    else:
                        n=n+5    
                    #print ('n cambio a :'+str(n))

                    drawText(_('PULSA UNA TECLA'), font, surface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2.25) + 50,TEXTCOLOR)
                    musicSound.stop()
                    correctAnswerSound.play()
                    score=returnScore()           
                    if score> maxScore:
                        maxScore = score # Puts new score
                    #print ('bunnyEatsCarrot(after): MaxScore'+str(maxScore)+' score: '+str(maxScore))
                else:
                    surface.blit(sad, rectBunny)
                    #surface.blit(sad, rectBunny)
                    score=returnScore() 
                    drawText(_('RESPUESTA INCORRECTA!'), font, surface, (WINDOWWIDTH / 4), (WINDOWHEIGHT / 2.25), TEXTCOLOR)
                    drawText(_('RESPUESTA CORRECTA: '+str(result)), font, surface, (WINDOWWIDTH / 3.8), (WINDOWHEIGHT / 2.25)+50, TEXTCOLOR)

                    drawText(_('PULSA UNA TECLA'), font, surface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2.25) + 100, TEXTCOLOR)
                    musicSound.stop()
                    gameOverSound.play()   
                    #print ('bunnyEatsCarrot(after): MaxScore'+str(maxScore)+' score: '+str(maxScore))
                break
            else:
                # Draw playerpygame.time.wait(2000) rectangle

                surface.blit(bunnyImage, rectBunny)

            pygame.display.update()

            mainClock.tick(FPS)

	pygame.mixer.music.stop()

        pygame.display.update()
        waitPlayerPressKey(self)
        #correctAnswerSound.stop()
        gameOverSound.stop()

        
######################################## methods                

#Time Limit
TIMELIMIT=240.0
#TIMELIMIT=30.0
#print ('time: '+str(TIMESTART))

def compareTime(playTime, gamestate):
    global TIMELIMIT, TIMESTART
    c=playTime-TIMESTART
    #print('c time: '+str(c))
    if(c>TIMELIMIT):
        #print ('Time Limit!')
        #gamestate.set_running( False ) 
	gamestate.go_to_next_state()

#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(gamestate):
    while True:
        for event in pygame.event.get():
            pygame.time.wait(300)
            pygame.event.clear()
            if event.type == QUIT:
                gamestate.set_running( False ) 
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    # Close game if user press scape key
                    gamestate.set_running( False ) 
                return
            if event.type == MOUSEBUTTONDOWN:
                return
            if event.type == JOYBUTTONDOWN:            
                return
                
def waitPlayerPressKeyNoWait(gamestate):
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                self.set_running( False ) 
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    # Close game if user press scape key
                    gamestate.set_running( False ) 
                return
            if event.type == MOUSEBUTTONDOWN:
                return
            if event.type == JOYBUTTONDOWN:            
                return
            
#Bunny Eats a Carrot Method
def bunnyEatsCarrot(bunnyImage, carrots):
    global resultChosen, bunnyImageF
    for b in carrots:
        #if bunnyImageF.rect.colliderect(b.rect):py" -> Check collisions if use rect
        if pygame.sprite.collide_mask(bunnyImageF,b):
            #print ('b.number: '+str(b.number))
            resultChosen=b.number
            #print ('resultChosen: '+str(resultChosen))
            return True
    return False

a=0

def checkResult(result): 
    global resultChosen
    global score
    global a
    #print ('resultChosen: '+str(resultChosen)+ ' and result: '+str(result))
    if result==resultChosen:
        score=score+20
        #print('score: '+str(score))
        a=score
        #print ('a::::check result::: '+str(a))
        return True
    if score>0:
        score=score-5
        a=score    
        #print('score: '+str(score))
    return False


def returnScore():
    global a
    #print ('a::::::: '+str(a))
    return a
    

#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 putImagesToList():
    global imageList
    global imageList2
    i=0
    imageList2=[]
    while(i<number1):
        randomImage=imageList[random.randint(0,len(imageList)-1)]
        imageList2.append(randomImage)
        #print(imageList2[i])
        i=i+1

########################################## classes


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,result):
        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-3,1), min(99,result+3))
        #print ('fruit result: '+str(self.number))

class Cuy(MBSprite) :
    def __init__(self, image):
        self.image = image
        self.state=image