예제 #1
0
    def app(self,amount,date,month,year):
          global p,r
          android.vibrate(0.05)
          if  (self.item.state=='down'):
                r=0.03
          elif  (self.itema.state=='down'):
                r=0.04
                
          try:
               self.display1.text=time1(p,date,month,year,1)
               t=time1(p,date,month,year,2)
               self.ka.text=str(int(t))+' months'
               self.kb.text=str(int(t)+1)+' months'
               if self.ka.state=='down':
                   t=int(t)
               elif self.kb.state=='down':
                   t=int(t)+1
          except Exception:
                self.display1.text='Error'

          try:
               if  (self.item1.state=='down'):
                     self.display2.text=intrest(amount,t,r)
               else:
                     self.display2.text=intrest1(amount,t,r)
                 
              
          except Exception:
                self.display2.text='Error'
예제 #2
0
	def runEventControler(self,event,resize,move):
		self.relocateButton(move)
		mouse_pos=(event.pos[0]/resize[0],event.pos[1]/resize[1])
		button_up = event.type is MOUSEBUTTONUP and event.button is 1
		if self.rect.collidepoint(mouse_pos):
			if self.sound[1] and self.state!=2: 
				self.sound[1][0].play()
				pygame.time.wait(self.sound[1][1])
			if len(self.img)>2:self.state=2
			if event.type==MOUSEBUTTONUP and event.button==1:
				if self.vibrate[0]>0 and android:android.vibrate(self.vibrate[0])
				if self.sound[0]: 
					self.sound[0][0].play()
					pygame.time.wait(self.sound[0][1])
				self.actived=True
				self.pressed=False
				if len(self.img)>3 and self.state!=3:
					self.state=3
				else:self.state=0
			if event.type==MOUSEBUTTONDOWN and event.button==1:
				if self.vibrate[1]>0 and android:android.vibrate(self.vibrate[1])
				if self.sound[2]: 
					self.sound[2][0].play()
					pygame.time.wait(self.sound[2][1])
				if len(self.img)>1:self.state=1
				self.pressed=True
		elif button_up or self.state==2:
			if button_up: self.pressed_out=True
			self.state=0
예제 #3
0
    def end_round(self, loser):
        winner = 1 - self.players.index(loser)
        self.players[winner].score += 1

        self.active_player ^= 1
        if android:
            android.vibrate(1)

        self.init_round()
예제 #4
0
 def get_new_comment(self,*args,**kwargs):
     print 'get new comment called'
     if self.comment_text == '[color=444444]Long press to add comment.[/color]':
         popup = Popup(content=CommentInput(board=self,comment=''),title='Edit comment:',size_hint=(0.85,0.85))
     else:
         popup = Popup(content=CommentInput(board=self,comment=self.comment_text),title='Edit comment:',size_hint=(0.85,0.55),pos=(0.075*Window.width, 0.95*Window.height))
     popup.content.popup = popup
     if platform() == 'android':
         import android
         android.vibrate(0.1)
     popup.open()
예제 #5
0
def main():

    pygame.init()
    if android:
        android.init()
     
    # Set the screen size.
    screen = pygame.display.set_mode((480, 800), pygame.FULLSCREEN)

    test = pygame.image.load("test.jpg").convert()
    test.set_alpha(128)
    
    
    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Android-specific: 
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill(color)
            screen.blit(test, (100, 100))
            pygame.display.flip()

        # When the touchscreen is pressed, change the color to green. 
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.25)
            
        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
예제 #6
0
def main():
    pygame.init()
    if android:
        android.init()

        android.mixer.music.load("click.wav")
        android.mixer.music.play(-1)

    # Set the screen size.
    screen = pygame.display.set_mode((480, 800))

    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill(color)
            pygame.display.flip()
            android.mixer.periodic()

        # When the touchscreen is pressed, change the color to green.
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.25)
                print "Open URL Version 2"
                webbrowser.open("http://www.renpy.org/")

        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
예제 #7
0
파일: main.py 프로젝트: AndroidMarv/rapt
def main():
    pygame.init()
    if android:
        android.init()
        
        android.mixer.music.load("click.wav")
        android.mixer.music.play(-1)

    # Set the screen size.
    screen = pygame.display.set_mode((480, 800))

    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Android-specific: 
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill(color)
            pygame.display.flip()
            android.mixer.periodic()

        # When the touchscreen is pressed, change the color to green. 
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.25)
                print "Open URL Version 2"
                webbrowser.open("http://www.renpy.org/")
            
        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
예제 #8
0
파일: exports.py 프로젝트: MSEMJEJME/tkot
def vibrate(duration):
    """
    :doc: other

    Causes the device to vibrate for `duration` seconds. Currently, this
    is only supported on Android.
    """

    try:
        import android #@UnresolvedImport
        android.vibrate(duration)
    except:
        pass
예제 #9
0
def vibrate(duration):
    """
    :doc: other

    Causes the device to vibrate for `duration` seconds. Currently, this
    is only supported on Android.
    """

    try:
        import android  #@UnresolvedImport
        android.vibrate(duration)
    except:
        pass
예제 #10
0
def collide(p1, p2):
    """ Tests whether two particles overlap
        If they do, make them bounce, i.e. update their angle, speed and position """

    dx = p1.x - p2.x
    dy = p1.y - p2.y

    dist = math.hypot(dx, dy)
    if dist < p1.size + p2.size:
        angle = math.atan2(dy, dx) + 0.5 * math.pi
        if p1.mass == p2.mass:
            p1.mass += 1
        total_mass = p1.mass + p2.mass
        (p1angle, p1speed) = addVectors(
            (p1.angle, p1.speed * (p1.mass - p2.mass) / total_mass),
            (angle, 2 * p2.speed * p2.mass / total_mass))
        (p2angle, p2speed) = addVectors(
            (p2.angle, p2.speed * (p2.mass - p1.mass) / total_mass),
            (angle + math.pi, 2 * p1.speed * p1.mass / total_mass))
        (p2.angle, p2.speed, p1.angle, p1.speed) = (p2angle, p2speed, p1angle,
                                                    p1speed)

        elasticity = p2.elasticity * p1.elasticity
        total_speed = (p1.speed + p2.speed)

        p1.hitpoints -= elasticity * 2
        p2.hitpoints -= elasticity * 2
        p1.speed *= elasticity
        p2.speed *= elasticity

        overlap = 0.5 * (p1.size + p2.size - dist + 1)
        p1.x += math.sin(angle) * overlap
        p1.y -= math.cos(angle) * overlap
        p2.x -= math.sin(angle) * overlap
        p2.y += math.cos(angle) * overlap
        ### VIBRATION
        if VIBRATE and p1.vibrate and p2.vibrate:
            if android:
                android.vibrate(0.05)
        if SOUND and p1.sound and p2.sound:
            if p1.hitpoints <= 0 or p2.hitpoints <= 0:
                DEATH_SOUND.play()
            if not mixer.get_busy():
                vol = float((total_speed * 2) / 100)
                if vol > 100:
                    vol = 100
                BOP_SOUND.set_volume(vol)
                BOP_SOUND.play()
예제 #11
0
def main():
    pygame.init()

    if android:
        android.init()

    # Set the screen size.
    screen = pygame.display.set_mode((480, 800))

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Handle application state events.
        if ev.type == pygame.APP_WILLENTERBACKGROUND:
            print "Will enter background."
            pygame.time.set_timer(TIMEREVENT, 0)
        elif ev.type == pygame.APP_DIDENTERFOREGROUND:
            print "Did enter foreground."
            screen = pygame.display.set_mode((480, 800))
            pygame.time.set_timer(TIMEREVENT, 1000 / FPS)
        elif ev.type == pygame.APP_TERMINATING:
            break

        # Draw the screen based on the timer.
        elif ev.type == TIMEREVENT:
            screen.fill(color)
            pygame.display.flip()

        # When the touchscreen is pressed, change the color to green.
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.1)

        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # Escape or the back button quits.
        elif ev.type == pygame.KEYDOWN and (ev.key == pygame.K_ESCAPE or ev.key == pygame.K_AC_BACK):
            break
예제 #12
0
파일: main.py 프로젝트: nithramus/42
def main():
    pygame.init()

    fenetre = pygame.display.set_mode(Constante.TAILLE_FENETRE)

    if android:
        android.init()

    serverIsKnown = False

    if android:
        android.vibrate(10)

    print "Labyrinth - android is set " + str(android)

    reponse = lancerServeur(fenetre)
    serverLaunch = (reponse == 'y')

    print "server launch: " + str(serverLaunch)

    if (serverLaunch):
        print "server = " + str(socket.gethostname())
        executerServeur()
        ip = socket.gethostbyname(socket.gethostname())
        ip2 = str(socket.gethostbyname_ex(socket.gethostname())[2])
        demandeUtilisateur(fenetre,
                           "l'adresse du serveur est " + ip2 + " [y] ")
        serverIsKnown = True
    else:
        ip = demandeUtilisateur(fenetre,
                                "rentrez adresse ip (puis entree)",
                                answer="192.168.1.")
        serverIsKnown = True

    print "ip " + ip

    if (serverIsKnown == True):
        client = Client(ip, Constante.SERVER_PORT)
        nomJoueur = demandeUtilisateur(fenetre, "Nom du joueur (puis entree)")
        labyrinthC.start.start(client, nomJoueur, fenetre, ip)

    if (serverLaunch):
        demandeUtilisateur(fenetre, "Arret du serveur [entree]")
        reponse = client.arretServeur()
        print "arret du serveur reponse: " + str(reponse)

    pygame.quit()
예제 #13
0
 def get_new_comment(self, *args, **kwargs):
     print 'get new comment called'
     if self.comment_text == '[color=444444]Long press to add comment.[/color]':
         popup = Popup(content=CommentInput(board=self, comment=''),
                       title='Edit comment:',
                       size_hint=(0.85, 0.85))
     else:
         popup = Popup(content=CommentInput(board=self,
                                            comment=self.comment_text),
                       title='Edit comment:',
                       size_hint=(0.85, 0.55),
                       pos=(0.075 * Window.width, 0.95 * Window.height))
     popup.content.popup = popup
     if platform() == 'android':
         import android
         android.vibrate(0.1)
     popup.open()
예제 #14
0
def collide(p1, p2):
    """ Tests whether two particles overlap
        If they do, make them bounce, i.e. update their angle, speed and position """
    
    dx = p1.x - p2.x
    dy = p1.y - p2.y
    
    dist = math.hypot(dx, dy)
    if dist < p1.size + p2.size:
        angle = math.atan2(dy, dx) + 0.5 * math.pi
        if p1.mass == p2.mass:
            p1.mass += 1
        total_mass = p1.mass + p2.mass
        (p1angle, p1speed) = addVectors((p1.angle, p1.speed*(p1.mass-p2.mass)/total_mass), (angle, 2*p2.speed*p2.mass/total_mass))
        (p2angle, p2speed) = addVectors((p2.angle, p2.speed*(p2.mass-p1.mass)/total_mass), (angle+math.pi, 2*p1.speed*p1.mass/total_mass))
        (p2.angle, p2.speed, p1.angle, p1.speed) = (p2angle, p2speed, p1angle, p1speed)

        elasticity = p2.elasticity * p1.elasticity
        total_speed = (p1.speed + p2.speed)

        p1.hitpoints -= elasticity*2
        p2.hitpoints -= elasticity*2
        p1.speed *= elasticity
        p2.speed *= elasticity

        overlap = 0.5*(p1.size + p2.size - dist+1)
        p1.x += math.sin(angle)*overlap
        p1.y -= math.cos(angle)*overlap
        p2.x -= math.sin(angle)*overlap
        p2.y += math.cos(angle)*overlap
        ### VIBRATION
        if VIBRATE and p1.vibrate and p2.vibrate:
            if android:
                android.vibrate(0.05)
        if SOUND and p1.sound and p2.sound:
            if p1.hitpoints <= 0 or p2.hitpoints <= 0:
                DEATH_SOUND.play()
            if not mixer.get_busy():
                vol = float((total_speed*2)/100)
                if vol > 100:
                    vol = 100
                BOP_SOUND.set_volume(vol)
                BOP_SOUND.play()
예제 #15
0
파일: main.py 프로젝트: looneyka/MobileApp
    def update(self, dt):
        self.ball.move()

        #bounce of paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)

        #bounce ball off bottom or top
        if (self.ball.y < self.y) or (self.ball.top > self.top):
            self.ball.velocity_y *= -1

        #went of to a side to score point?
        if self.ball.x < self.x:
            self.player2.score += 1
            android.vibrate(1)
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            android.vibrate(1)
            self.serve_ball(vel=(-4, 0))
예제 #16
0
 def updateSnakes(self):
     if self.apple.expiration == 0:
         self.apple.type = AppleTypes.NORMAL
     else:
         self.apple.expiration -= 1
     if self.apple.type == AppleTypes.SPECIAL:
         self.apple.move()
     for snake in self.snakes:
         snake.updatePosition()
         if snake.hitSnake(snake) or snake.hitBorder():
             SOUNDS['Hit'].play()
             android.vibrate(0.2)
             snake.changeColor(RED)
             if snake.lives == 0:
                 return False
         if snake.eatApple(self.apple):
             if not self.apple.type == AppleTypes.NORMAL:
                 snake.changeColor(APPLE_COLORS[self.apple.type])
             self.apple = Apple(self.snakes)
     return True
예제 #17
0
파일: main.py 프로젝트: irvingprog/WITS
    def update(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            elif event.type == MOUSEBUTTONDOWN:
                if self.button_returnmenu.rect.collidepoint(event.pos[0],event.pos[1]):
                    levelsselector_start(self.continent,self.difficult)
                if self.button_pause.rect.collidepoint(event.pos[0],event.pos[1]):
                    self.timer.stop()
                    self.pause.status = True
                if self.button_playreboot.rect.collidepoint(event.pos[0],event.pos[1]):
                    game_start(self.level,self.continent,self.difficult)
                if (self.star.rect.collidepoint(event.pos[0],event.pos[1])
                    and not self.star.move):
                    if android:
                        android.vibrate(1)
                    self.star.change_state()
                    self.tweener.addTween(self.star,x=1024,tweenTime=1, tweenType=pytweener.Easing.Elastic.easeIn)
                    if self.timer.time()<=4:
                        #Write rating of level and total rating of continent
                        levels_rating[self.continent+self.difficult][str(self.level)] = "3"
                        Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(3)
                    elif self.timer.time()>4 and self.timer.time()<= 6:
                        if not self.current_rating_level == 3:
                            levels_rating[self.continent+self.difficult][str(self.level)] = "2"
                            Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(2)
                    elif self.timer.time()> 6:
                        if (not self.current_rating_level == 2 or
                            not self.current_rating_level == 3):
                            levels_rating[self.continent+self.difficult][str(self.level)] = "1"
                            Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(1)
                    self.timer.stop()

        #print self.timer.time()
        self.timer.time()
        self.dt = self.clock.tick(60)
        self.tweener.update(self.dt/1000.0)
예제 #18
0
	def runEventControler(self,event,resize,move):
		self.relocateButton(move)
		mouse_pos=(event.pos[0]/resize[0],event.pos[1]/resize[1])
		button_up = event.type is MOUSEBUTTONUP and event.button is 1
		if self.rect.collidepoint(mouse_pos):
			if self.sound[1] and self.state!=2: 
				self.sound[1][0].play()
				pygame.time.wait(self.sound[1][1])
			if len(self.img)>2:self.state=2
			if event.type==MOUSEBUTTONUP and event.button==1:
				if self.vibrate[0]>0 and android:android.vibrate(self.vibrate[0])
				if self.sound[0]: 
					self.sound[0][0].play()
					pygame.time.wait(self.sound[0][1])
				self.actived=True
				self.pressed=False
				if self.auto_skin:
					self.selected_skin+=1
					if self.selected_skin>=len(self.skin):
						self.selected_skin=0
					self.setSkin(self.selected_skin)
				if len(self.img)>3 and self.state!=3:
					self.state=3
				else:self.state=0
			if event.type==MOUSEBUTTONDOWN and event.button==1:
				if self.vibrate[1]>0 and android:android.vibrate(self.vibrate[1])
				if self.sound[2]: 
					self.sound[2][0].play()
					pygame.time.wait(self.sound[2][1])
				if len(self.img)>1:self.state=1
				self.pressed=True
		elif button_up or self.state==2:
			if button_up: 
				self.pressed_out=True
				#self.pressed=False#solução para movimento do ciclista quando segurava o clique e soltava fora do botão
			self.state=0
예제 #19
0
def game(screen):
    '''main function that runs the game'''
    pygame.init()
    window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('Sky High')
    screen = pygame.display.get_surface()
    clock = pygame.time.Clock()
    scroll_speed = 3
    
    sky_image = "assets/sky.gif"
    balloon0 = pygame.transform.scale (load_image('assets/balloon.png'), (132, 200))
    balloon1 = pygame.transform.scale (load_image('assets/balloon1.png'), (132, 200))
    balloon2 = pygame.transform.scale (load_image('assets/balloon2.png'), (132, 200))
    balloonflashing = pygame.transform.scale (load_image('assets/balloonflash.png'), (132, 200))
    
    font = pygame.font.Font("BRLNSDB.TTF", 30)
    try:
        mixer.music.load("assets/Scores.ogg")
        hit = mixer.Sound("assets/hit.ogg")
        star = mixer.Sound("assets/star.ogg")
        mixer.music.play(-1)
    except pygame.error:
        print "Couldn't find file."
    
    balloon_speed = 6
    moveRate = 2
    
    score = 0
    
    sky = Background(screen, scroll_speed, sky_image)

    # Map the back button to the escape key.
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
        android.accelerometer_enable(True)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000)
    pygame.time.set_timer(USEREVENT + 1, 3000)
    pygame.time.set_timer(USEREVENT + 2, 2000)
    pygame.time.set_timer(USEREVENT + 3, 4000)
    pygame.time.set_timer(USEREVENT + 4, 5000)
    pygame.time.set_timer(USEREVENT + 5, 8000)
    
    pygame.key.set_repeat(FPS, FPS) # set key repeat on 
    
    lives = 10
    
    balloon = Balloon(screen, SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT, 0, balloon_speed, "assets/balloon.png", lives)
    city = Enemy(screen,0, SCREEN_HEIGHT-800, 0, -3, "assets/cityskyline.png",(800,480),1,1)
    city.image = load_image("assets/cityskyline.png")
    city.rect = city.image.get_rect()
    airplanes = pygame.sprite.Group()
    birds = pygame.sprite.Group()
    missiles = pygame.sprite.Group()
    
    powerups = pygame.sprite.Group()
    spawn_pt = range(-200, -100) + range(SCREEN_WIDTH, SCREEN_WIDTH + 100)
    elapsed_time = 0
    timer = 0
    justcollided = 0
    imagechanged = False
    
    
    while True:
        #game loop
        time_passed = clock.tick(FPS)
        elapsed_time += 1
        
        text = font.render("Height: " + str(score), 1, (120, 40, 80)) 
        #render score
        
        lives_txt = font.render("Balloon Strength: " + str(lives)+ "/10" , 1, (85, 0, 50)) 
        
        timer -= 1
        justcollided -= 1
        
        if android:
            balloon_move = android.accelerometer_reading()
            if balloon.x >= 0 and balloon.x <= SCREEN_WIDTH - balloon.image_w:
                balloon.x = balloon.x - (balloon_move[0] * moveRate)
            elif balloon.x <= 0:   
                balloon.x += 1
            else:
                balloon.x -= 1
            if balloon.rect.bottom <= SCREEN_HEIGHT and balloon.y >= (SCREEN_HEIGHT - balloon.image_h)/3:
                balloon.y = balloon.y + ((balloon_move[1] - 5) * moveRate)
            elif balloon.rect.bottom >= SCREEN_HEIGHT:
                balloon.y -= 1
            else:
                balloon.y += 1
            
                    

            if android.check_pause():
                android.wait_for_resume()
                
        #Randomly choose a spawn point from the list
        init_x = choice(spawn_pt)
        
        if init_x < SCREEN_WIDTH/2:
            enemy_image = "assets/plane-right.gif"
        else:
            enemy_image = "assets/plane-left.gif"
        
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                elif event.key == pygame.K_RIGHT:
                    if balloon.x <= SCREEN_WIDTH - balloon.image_w:
                        balloon.x += balloon_speed
                elif event.key == pygame.K_LEFT:
                    if balloon.x >= 0:
                        balloon.x -= balloon_speed
                elif event.key == pygame.K_DOWN:
                    if balloon.y <= SCREEN_HEIGHT - balloon.image_h:
                        balloon.y += balloon_speed
                elif event.key == pygame.K_UP:
                    if balloon.y >= 0:
                        balloon.y -= balloon_speed
            elif event.type == TIMEREVENT:
                score += 1
            elif event.type == USEREVENT + 1 and score>=2 and score<=20:
                airplanes.add(Enemy(screen, init_x, randint(-50, 200), randint(1, 5), 3, enemy_image, (100, 50), 1, 1))
            
            elif event.type == USEREVENT + 2 and score>=50: 
                airplanes.add(Enemy(screen, init_x, randint(-50, 200), randint(1, 5), randint(3, 5), enemy_image, (100, 50), 1, 1))
                
            elif event.type == USEREVENT + 3 and score>=5:
                birds.add(Enemy(screen, init_x, randint(-50, SCREEN_HEIGHT + 50), randint(2,4), 0, "assets/UFO.png", (100, 80), 1, 1))
                if score >=20 and score<40:
                    missiles.add(Enemy(screen, randint(0, SCREEN_WIDTH), SCREEN_HEIGHT, 0, randint(-8, -3), "assets/missile.png", (40, 150), 1, 1))
            elif event.type == USEREVENT + 4 and score>=50:
                missiles.add(Enemy(screen, randint(0, SCREEN_WIDTH), SCREEN_HEIGHT, 0, randint(-8, -3), "assets/missile.png", (40, 150), 1, 1))
        
            elif event.type == USEREVENT + 5 and score>=30:
                powerups.add(Enemy(screen, randint(100, SCREEN_WIDTH-100), 0, 0, 3, "assets/gold-star.gif", (60, 60), 1, 1))
 
        if timer <= 20 and timer >= 0:
            sky.dy = 6
        elif timer > 45:
           sky.dy = -6
        else:
            sky.dy = 3
        
        sky.update(score)
        sky.draw()

        city.update2(score,SCREEN_HEIGHT)
        city.draw()
        
            
        balloon.update(lives, balloon0, balloon1, balloon2, justcollided)
        balloon.draw()
        if balloon.y <= SCREEN_HEIGHT / 3:
            balloon.dy = 0
            sky.scrolling = True
        if justcollided <= 0:
            balloon.update(lives, balloon0, balloon1, balloon2, justcollided)
            
            for enemy in airplanes:
                if pygame.sprite.collide_mask(enemy, balloon):
                    # ADD GAME OVER SCREEN HERE
                    if android:
                        android.vibrate(0.3)
                    if lives <= 0:
                        return score
                    enemy.dy = 20
                    timer = 80
                    if score >= 10:
                        score -= 10
                    else:
                        score = 1
                    justcollided = 20
                    lives -= 1
                    hit.play()
                
            for bird in birds:
                if bird.dy != 20:
                    bird.dy = 6*cos(0.1*elapsed_time) + 1
                if pygame.sprite.collide_mask(bird, balloon):
                    # ADD GAME OVER SCREEN HERE
                    if android:
                        android.vibrate(0.3)
                    if lives <= 0:
                        return score
                    bird.dy = 20
                    timer = 70
                    if score >= 5:
                        score -= 5
                    else:
                        score = 1
                    justcollided = 20
                    lives -= 1
                    hit.play()
                
            for missile in missiles:
                if pygame.sprite.collide_mask(missile, balloon):
                    # ADD GAME OVER SCREEN HERE
                    if android:
                        android.vibrate(0.1)
                    missile.dy = 20
                    if lives <= 0:
                        return score
                    timer = 80
                    if score >= 15:
                        score -= 15
                    else:
                        score = 1
                    justcollided = 20
                    lives -= 1
                    hit.play()
                    
            for powerup in powerups:
                if pygame.sprite.collide_mask(powerup, balloon):
                    timer = 25
                    powerup.kill()
                    score += 10
                    star.play()
        else:
           balloon.image = balloonflashing
           imagechanged = True
        airplanes.update()
        airplanes.draw(screen)
        birds.update()
        birds.draw(screen)
        missiles.update()
        missiles.draw(screen)
        powerups.update()
        powerups.draw(screen)
            
        screen.blit(text, (0,  SCREEN_HEIGHT - 30))
        screen.blit(lives_txt, (0, 0))
        pygame.display.flip()
예제 #20
0
from kivy.core.audio import SoundLoader
from kivy.clock import Clock

from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.image import Image

from kivy.animation import Animation
# from kivy.vector import Vector
from kivy.properties import NumericProperty, StringProperty, ObjectProperty

import expression_generator as generator

try:
    import android
    android.vibrate(0.05)
except ImportError:
    android = None
    Window.size = [600, 800]

EASY = 1
MEDIUM = 2
HARD = 3
LIFE = 5

COW_WIDTH = Window.width // 10
COW_HEIGHT = COW_WIDTH * 0.7
COW_SPEED = 0.001 * Window.width

UFO_WIDTH = COW_WIDTH * 1.5
UFO_HEIGHT = COW_HEIGHT
예제 #21
0
파일: main.py 프로젝트: jvelez/KinderGame
	def HandleInput(self,event):
		if self.edit == True: 
			if event.type == pygame.KEYDOWN and event.key == pygame.K_TAB:
				self.caps = not self.caps
			if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
				self.edit = False
				self.clicked = False
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_BACKSPACE:
				self.string = self.string[:-1]
				self.ast = self.ast[:-1]
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_a:
				if self.caps == True:
					self.string = self.string + "A"
				else:
					self.string = self.string + "a"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_b:
				if self.caps == True:
					self.string = self.string + "B"
				else:
					self.string = self.string + "b"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_c:
				if self.caps == True:
					self.string = self.string + "C"
				else:
					self.string = self.string + "c"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_d:
				if self.caps == True:
					self.string = self.string + "D"
				else:
					self.string = self.string + "d"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_e:
				if self.caps == True:
					self.string = self.string + "E"
				else:
					self.string = self.string + "e"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
				if self.caps == True:
					self.string = self.string + "F"
				else:
					self.string = self.string + "f"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_g:
				if self.caps == True:
					self.string = self.string + "G"
				else:
					self.string = self.string + "g"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_h:
				if self.caps == True:
					self.string = self.string + "H"
				else:
					self.string = self.string + "h"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_i:
				if self.caps == True:
					self.string = self.string + "I"
				else:
					self.string = self.string + "i"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_j:
				if self.caps == True:
					self.string = self.string + "J"
				else:
					self.string = self.string + "j"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_k:
				if self.caps == True:
					self.string = self.string + "K"
				else:
					self.string = self.string + "k"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_l:
				if self.caps == True:
					self.string = self.string + "L"
				else:
					self.string = self.string + "l"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_m:
				if self.caps == True:
					self.string = self.string + "M"
				else:
					self.string = self.string + "m"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_n:
				if self.caps == True:
					self.string = self.string + "N"
				else:
					self.string = self.string + "n"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_o:
				if self.caps == True:
					self.string = self.string + "O"
				else:
					self.string = self.string + "o"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_p:
				if self.caps == True:
					self.string = self.string + "P"
				else:
					self.string = self.string + "p"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_q:
				if self.caps == True:
					self.string = self.string + "Q"
				else:
					self.string = self.string + "q"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_r:
				if self.caps == True:
					self.string = self.string + "R"
				else:
					self.string = self.string + "r"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
				if self.caps == True:
					self.string = self.string + "S"
				else:
					self.string = self.string + "s"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_t:
				if self.caps == True:
					self.string = self.string + "T"
				else:
					self.string = self.string + "t"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_u:
				if self.caps == True:
					self.string = self.string + "U"
				else:
					self.string = self.string + "u"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_v:
				if self.caps == True:
					self.string = self.string + "V"
				else:
					self.string = self.string + "v"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_w:
				if self.caps == True:
					self.string = self.string + "W"
				else:
					self.string = self.string + "w"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_x:
				if self.caps == True:
					self.string = self.string + "X"
				else:
					self.string = self.string + "x"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_y:
				if self.caps == True:
					self.string = self.string + "Y"
				else:
					self.string = self.string + "y"
				self.ast = self.ast + "*"
			elif event.type == pygame.KEYDOWN and event.key == pygame.K_z:
				if self.caps == True:
					self.string = self.string + "Z"
				else:
					self.string = self.string + "z"
				self.ast = self.ast + "*"

		self.clicked = False
		if Mouse[MLC] == True or Mouse[MRC] == True:
			if PointRectIntersection2(Mouse[MX],Mouse[MY],self.rect) == True:
				self.clicked = self.edit = True
				if android:
					android.vibrate(0.04);
			else:
				self.edit = self.clicked = False
예제 #22
0
 def vibrate(self, t):
     # Vibrace Android telefonu
     android.vibrate(t)
예제 #23
0
from kivy.core.audio import SoundLoader
from kivy.clock import Clock

from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.image import Image

from kivy.animation import Animation
# from kivy.vector import Vector
from kivy.properties import NumericProperty, StringProperty, ObjectProperty

import expression_generator as generator

try:
    import android
    android.vibrate(0.05)
except ImportError:
    android = None
    Window.size = [600, 800]

EASY = 1
MEDIUM = 2
HARD = 3
LIFE = 5

COW_WIDTH = Window.width // 10
COW_HEIGHT = COW_WIDTH * 0.7
COW_SPEED = 0.001 * Window.width

UFO_WIDTH = COW_WIDTH * 1.5
UFO_HEIGHT = COW_HEIGHT
예제 #24
0
파일: main.py 프로젝트: omotto/Saimon
def game(screen, sonido, code):
    # Declaramos los objetos
    error = Window("YOU FAIL", "", WHITE, "DroidSans-Bold.ttf", 76, "sound0.wav", SCREEN_WIDTH / 2 - 220, SCREEN_HEIGHT / 2 - 50, 440, 100, RED, DARK_RED, WHITE, WHITE)
    fondo = Window("", "", WHITE, "DroidSans-Bold.ttf", 1, "sound0.wav", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, BLACK, WHITE, WHITE, WHITE)
    windows = [ Window("", "", GREEN, "DroidSans-Bold.ttf", 22, "sound1.wav", 10, 50, 220, 220, RED, DARK_RED, WHITE, WHITE),
                Window("", "", YELLOW, "DroidSans-Bold.ttf", 22, "sound2.wav", 250, 50, 220, 220, GREEN, DARK_GREEN, WHITE, WHITE),
                Window("", "", CYAN, "DroidSans-Bold.ttf", 22, "sound3.wav", 10, 290, 220, 220, YELLOW, DARK_YELLOW, WHITE, WHITE),
                Window("", "", MAGENTA, "DroidSans-Bold.ttf", 22, "sound4.wav", 250, 290, 220, 220, CYAN, DARK_CYAN, WHITE, WHITE),
                Window("", "", CYAN, "DroidSans-Bold.ttf", 22, "sound5.wav", 10, 530, 220, 220, MAGENTA, DARK_MAGENTA, WHITE, WHITE),
                Window("", "", MAGENTA, "DroidSans-Bold.ttf", 22, "sound6.wav", 250, 530, 220, 220, BLUE, DARK_BLUE, WHITE, WHITE) ]
    
    # Printamos
    fondo.plot(screen)
    for contador in range(6):           
        windows[contador].plot(screen)

    pygame.display.flip() # Printamos
    
    fuente = load_text_font("DroidSans-Bold.ttf", FNT_DIR, 26)
    
    # Generamos un array bidimensional de valores alaeatorios del 1 al 6
    valores = [[random.randint(0, 5) for i in range(MAX_SUB_LEVELS)] for i in range(MAX_LEVELS)]
    
    max_sublevels = [10, 12, 12, 14, 14, 16, 16, 18, 18, 20]
    
    # Inicializamos valores globales del juego
    codes = [[4,9,3,0],[3,8,5,6],[4,9,5,1],[1,4,5,6],[0,4,5,6],[6,4,6,2],[7,8,5,6],[3,1,7,4],[9,4,2,2],[3,8,5,7]]
    level = 0
    for i in range(MAX_LEVELS):    
        if (codes[i][0] == code[0]) and (codes[i][1] == code[1]) and (codes[i][2] == code[2]) and (codes[i][3] == code[3]):
            level = i
    exit_game = True
    sublevel = 0
    while exit_game: 
        pygame.gfxdraw.box(screen, (0, 0, SCREEN_WIDTH, 40), BLACK)
        pygame.gfxdraw.box(screen, (0, 755, SCREEN_WIDTH, 40), BLACK)
        mensaje_level = fuente.render("Level {0}".format(level), 1, WHITE)
        screen.blit(mensaje_level, (10, 10))
        mensaje_stage = fuente.render("Stage {0}".format(sublevel), 1, WHITE)
        screen.blit(mensaje_stage, (250, 10))
        mensaje_code = fuente.render("Level Code : {0} {1} {2} {3}".format(codes[level][0], codes[level][1], codes[level][2], codes[level][3]), 1, WHITE)
        screen.blit(mensaje_code, (120, 760))
        pygame.display.flip()
        pygame.time.wait(1000)
        # Mostramos la siguiente combinacion
        for i in range(sublevel+1):
            pygame.time.wait(600 - ((level+2) * 40) - ((sublevel+1) * 5))
            windows[valores[level][i]].invert_color()
            windows[valores[level][i]].plot(screen)
            pygame.display.flip()  
            if sonido == True: windows[valores[level][i]].play_sound()            
            pygame.time.wait(500 - ((level+2) * 20) - ((sublevel+1) * 2))
            windows[valores[level][i]].invert_color()
            windows[valores[level][i]].plot(screen)
            pygame.display.flip()    
        # Ahora nos toca jugar
        salir = True
        indice = 0
        while salir:
            for event in pygame.event.get():
                # When the touchscreen is pressed, change the color to green.
                if event.type == pygame.MOUSEBUTTONDOWN:
                    posicion = pygame.mouse.get_pos()
                    touched = 7
                    for i in range(6):
                        if windows[i].is_touched(posicion[0], posicion[1]) == True: 
                            touched = i
                    if touched != 7: # Has dado a un pulsador
                        windows[touched].invert_color()
                        windows[touched].plot(screen)
                        pygame.display.flip()  
                        if sonido == True: windows[touched].play_sound()            
                        pygame.time.wait(200)
                        windows[touched].invert_color()
                        windows[touched].plot(screen)
                        pygame.display.flip()    
                        if touched != valores[level][indice]:# Te has equivocado de boton
                            exit_game = False
                            salir = False
#                            fondo.invert_color()
#                            fondo.plot(screen)
#                            if sonido == True: fondo.play_sound()
#                            pygame.display.flip()
                            touched = 7 #indicamos en la salida que es por error
                        else: 
                            indice = indice + 1
                            if indice == (sublevel + 1):
                                salir = False
                elif event.type == pygame.QUIT:
                    sys.exit()
        # Siguiente nivel
        sublevel = sublevel + 1
        if sublevel == max_sublevels[level]: #MAX_SUB_LEVELS
            level = level + 1
            sublevel = 0
        if level == MAX_LEVELS:
            exit_game = False
    if touched == 7:
        if android: 
            android.vibrate(1)
        error.plot(screen)
        pygame.display.flip()
        salir2 = True
        while salir2:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    posicion = pygame.mouse.get_pos()
                    if error.is_touched(posicion[0], posicion[1]) == True:
                        error.invert_color()
                        error.plot(screen)
                        pygame.display.flip()                          
                        if sonido == True: fondo.play_sound()
                        pygame.time.wait(200)
                        error.invert_color()
                        error.plot(screen)
                        pygame.display.flip()                          
                        salir2 = False
                elif event.type == pygame.QUIT:
                    sys.exit()
예제 #25
0
파일: main.py 프로젝트: ozroc/lunar_taxi
def main():
	if android:
			android.init()
			android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
			android.accelerometer_enable(True)
	
	carretera=Carretera()			
	speed=0.
	coches=[]
	bichos=[]
	bichos.append(Objeto())
	bichos[-1].pos=[-150.,15]
	bichos[-1].clase=1
	bichos[-1].carga_imagen()
	bichos.append(Objeto())
	bichos[-1].pos=[-150.,35]
	bichos[-1].clase=1
	bichos[-1].carga_imagen()
	bichos.append(Objeto())
	bichos[-1].pos=[150.,50]
	bichos[-1].clase=1
	bichos[-1].carga_imagen()
	pygame.display.update()
	stage=1
	TIMEREVENT = pygame.USEREVENT
	checkpoint=3000
	FPS=25
	t=0
	l=0
	dt=0.01
	pos=0
	vel=0
	t0=time.time()
	t00=time.time()+60
	last_coche=0
	lives=3
	dcoches=4
	cracks=0
	dentro=True
	if mixer:
		mixer.init()
		mixer.music.load('sound/blues.wav')
		mixer.music.play()
	while dentro:
		if android:
			if mixer.music_channel.get_busy()==False:
				mixer.music.play()
		else:
			if mixer.music.get_busy()==False:
				mixer.music.play()
		for ev in pygame.event.get():
			if pygame.mouse.get_pressed()[0]:
				speed*=0.95
			elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
				dentro=False
		t+=dt
		l+=dt*speed
		curva=math.cos(t)*0.75*math.sin(t/2+3)*math.cos(t/10+12)
		carretera.curva=curva
		n=0
		for i in bichos:
			i.vel=speed
			i.pos[1]+=speed*i.pos[1]*dt+dt
			i.curva=curva
			if i.pos[1] > 100:
				bichos.pop(n)
			n+=1
		n=0
		for i in coches:
			i.vel=speed
			i.pos[1]+=speed*i.pos[1]*dt+dt
			i.curva=curva
			if i.pos[1] > 85 and i.pos[1] < 95:
				#print i.pos[0]-pos
				if i.clase==0:
					if abs(i.pos[0]-pos) < 30:
						if android:
							android.vibrate(2)
						pygame.time.delay(2000)
						lives-=1
						cracks+=1
						if lives < 0:
							dentro=False
						speed*=0
						coches.pop(n)
				elif i.clase==1:
					if abs(i.pos[0]-pos) < 20:
						if lives < 3:
							lives+=1
						if cracks > 0:
							cracks-=1
						if android:
							android.vibrate(1)
						speed*=0
						coches.pop(n)
			if i.pos[1] > 120:
				coches.pop(n)
			n+=1
		if random.random() < 0.05:
			#print 'arbol'
			bichos.append(Objeto())
			if random.random() < 0.5:
				bichos[-1].pos=[150.,0.1]
			else:
				bichos[-1].pos=[-150.,0.1]
			bichos[-1].radius=800
			bichos[-1].clase=1
			bichos[-1].carga_imagen()
		if random.random() < 0.1 and t-last_coche > dcoches:
			coches.append(Coche())
			coches[-1].radius=100
			coches[-1].curva=curva
			if random.random() < 0.05:
				coches[-1].clase=1
			coches[-1].pos=[random.random()*150-75,0.1]
			coches[-1].carga_imagen()
			last_coche=t*1
		speed+=dt
		if pos > 100 or pos < -100:
			speed*=0.9
			if android:
				android.vibrate(0.1)
			if pos > 120:
				pos=120
				speed=0.
			elif pos < -120:
				pos = -120
				speed=0.
		if speed > 5:
			speed=5.
		if android:
			accels=android.accelerometer_reading()
			dpx=accels[1]*100
		else:
			dp=pygame.mouse.get_pos()
			dpx=(dp[0]-400)*2
		pos+=dt*curva*300*speed
		pos+=dpx*dt
		alpha=dpx/2*dt
		carretera.draw()
		screen.blit(sky,(0,0))
		#screen.blit(sky2,(int(-150-curva*150),0))
		for i in range(len(bichos)):
			bichos[-1-i].draw()
		for i in range(len(coches)):
			coches[-1-i].draw()
		motor=pygame.transform.rotate(moto,-int(alpha)*10)
		#(w,h)=motor.get_size()
		xn,yn,f=coordenadas((pos,90),curva)
		screen.blit(motor,(int(xn-w/2),int(yn-h)))
		while 1/(time.time()-t0) > 30:
			time.sleep(0.01)
		#display_text(screen,': '+str(int(speed*20)))
		if (t00-time.time()) < 0:
			lives-=1
			if android:
				android.vibrate(1)
			t00+=60
			if lives < 0:
				dentro=False
		elif l*100 < checkpoint*stage-500 and l*100 > checkpoint*stage-520:
			bichos.append(Objeto())
			bichos[-1].pos=[0.,0.1]
			bichos[-1].radius=800
			bichos[-1].clase=0
			bichos[-1].carga_imagen()
		elif l*100 > checkpoint*stage:
			stage+=1
			if checkpoint < 6000:
				checkpoint+=500
			t00+=60
			dcoches*=0.75
		panel(screen,panel_image,crack1_image,crack2_image,crack3_image,font,int(checkpoint*stage-l*100),int(t00-time.time()),speed*20,lives,cracks)
		pygame.display.update()
		t0=time.time()
		screen.fill((150,255,150))
	ending=pygame.image.load('images/ending.png').convert_alpha()
	screen.blit(ending,(0,0))
	pygame.display.flip()
	pygame.time.delay(5000)	
예제 #26
0
파일: main.py 프로젝트: ozroc/lunar_taxi
def main():
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
        android.accelerometer_enable(True)

    carretera = Carretera()
    speed = 0.
    coches = []
    bichos = []
    bichos.append(Objeto())
    bichos[-1].pos = [-150., 15]
    bichos[-1].clase = 1
    bichos[-1].carga_imagen()
    bichos.append(Objeto())
    bichos[-1].pos = [-150., 35]
    bichos[-1].clase = 1
    bichos[-1].carga_imagen()
    bichos.append(Objeto())
    bichos[-1].pos = [150., 50]
    bichos[-1].clase = 1
    bichos[-1].carga_imagen()
    pygame.display.update()
    stage = 1
    TIMEREVENT = pygame.USEREVENT
    checkpoint = 3000
    FPS = 25
    t = 0
    l = 0
    dt = 0.01
    pos = 0
    vel = 0
    t0 = time.time()
    t00 = time.time() + 60
    last_coche = 0
    lives = 3
    dcoches = 4
    cracks = 0
    dentro = True
    if mixer:
        mixer.init()
        mixer.music.load('sound/blues.wav')
        mixer.music.play()
    while dentro:
        if android:
            if mixer.music_channel.get_busy() == False:
                mixer.music.play()
        else:
            if mixer.music.get_busy() == False:
                mixer.music.play()
        for ev in pygame.event.get():
            if pygame.mouse.get_pressed()[0]:
                speed *= 0.95
            elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                dentro = False
        t += dt
        l += dt * speed
        curva = math.cos(t) * 0.75 * math.sin(t / 2 + 3) * math.cos(t / 10 +
                                                                    12)
        carretera.curva = curva
        n = 0
        for i in bichos:
            i.vel = speed
            i.pos[1] += speed * i.pos[1] * dt + dt
            i.curva = curva
            if i.pos[1] > 100:
                bichos.pop(n)
            n += 1
        n = 0
        for i in coches:
            i.vel = speed
            i.pos[1] += speed * i.pos[1] * dt + dt
            i.curva = curva
            if i.pos[1] > 85 and i.pos[1] < 95:
                #print i.pos[0]-pos
                if i.clase == 0:
                    if abs(i.pos[0] - pos) < 30:
                        if android:
                            android.vibrate(2)
                        pygame.time.delay(2000)
                        lives -= 1
                        cracks += 1
                        if lives < 0:
                            dentro = False
                        speed *= 0
                        coches.pop(n)
                elif i.clase == 1:
                    if abs(i.pos[0] - pos) < 20:
                        if lives < 3:
                            lives += 1
                        if cracks > 0:
                            cracks -= 1
                        if android:
                            android.vibrate(1)
                        speed *= 0
                        coches.pop(n)
            if i.pos[1] > 120:
                coches.pop(n)
            n += 1
        if random.random() < 0.05:
            #print 'arbol'
            bichos.append(Objeto())
            if random.random() < 0.5:
                bichos[-1].pos = [150., 0.1]
            else:
                bichos[-1].pos = [-150., 0.1]
            bichos[-1].radius = 800
            bichos[-1].clase = 1
            bichos[-1].carga_imagen()
        if random.random() < 0.1 and t - last_coche > dcoches:
            coches.append(Coche())
            coches[-1].radius = 100
            coches[-1].curva = curva
            if random.random() < 0.05:
                coches[-1].clase = 1
            coches[-1].pos = [random.random() * 150 - 75, 0.1]
            coches[-1].carga_imagen()
            last_coche = t * 1
        speed += dt
        if pos > 100 or pos < -100:
            speed *= 0.9
            if android:
                android.vibrate(0.1)
            if pos > 120:
                pos = 120
                speed = 0.
            elif pos < -120:
                pos = -120
                speed = 0.
        if speed > 5:
            speed = 5.
        if android:
            accels = android.accelerometer_reading()
            dpx = accels[1] * 100
        else:
            dp = pygame.mouse.get_pos()
            dpx = (dp[0] - 400) * 2
        pos += dt * curva * 300 * speed
        pos += dpx * dt
        alpha = dpx / 2 * dt
        carretera.draw()
        screen.blit(sky, (0, 0))
        #screen.blit(sky2,(int(-150-curva*150),0))
        for i in range(len(bichos)):
            bichos[-1 - i].draw()
        for i in range(len(coches)):
            coches[-1 - i].draw()
        motor = pygame.transform.rotate(moto, -int(alpha) * 10)
        #(w,h)=motor.get_size()
        xn, yn, f = coordenadas((pos, 90), curva)
        screen.blit(motor, (int(xn - w / 2), int(yn - h)))
        while 1 / (time.time() - t0) > 30:
            time.sleep(0.01)
        #display_text(screen,': '+str(int(speed*20)))
        if (t00 - time.time()) < 0:
            lives -= 1
            if android:
                android.vibrate(1)
            t00 += 60
            if lives < 0:
                dentro = False
        elif l * 100 < checkpoint * stage - 500 and l * 100 > checkpoint * stage - 520:
            bichos.append(Objeto())
            bichos[-1].pos = [0., 0.1]
            bichos[-1].radius = 800
            bichos[-1].clase = 0
            bichos[-1].carga_imagen()
        elif l * 100 > checkpoint * stage:
            stage += 1
            if checkpoint < 6000:
                checkpoint += 500
            t00 += 60
            dcoches *= 0.75
        panel(screen, panel_image, crack1_image, crack2_image,
              crack3_image, font, int(checkpoint * stage - l * 100),
              int(t00 - time.time()), speed * 20, lives, cracks)
        pygame.display.update()
        t0 = time.time()
        screen.fill((150, 255, 150))
    ending = pygame.image.load('images/ending.png').convert_alpha()
    screen.blit(ending, (0, 0))
    pygame.display.flip()
    pygame.time.delay(5000)
예제 #27
0
파일: main.py 프로젝트: patmorin/alphapop
    def clicked(self, pos):
        """The user clicked at location pos, see if they hit the target"""

        b = self.bubbles[self.target]

        # The user clicked the target bubble
        if distance(pos, b.center()) < b.radius:

            self.pop_sound.play()
            letter = b.letter
            bravo = self.load_sound("bravo-" + letter + ".wav")
            bravo.play()
            self.bubbles[self.target] = self.make_bubble()

            # After every 7 correct answers we change the background
            self.correct += 1
            if self.correct % 7 == 0:
                i = (self.correct//7) % len(self.backgrounds)
                self.bg_img = self.load_background(self.backgrounds[i])
            self.target = random.randrange(len(self.bubbles))
            self.state = Game.BRAVO_STATE
            if android:
                ms = 2000  # get_length() not supported by android.mixer
            else:
                ms = int(bravo.get_length()*1000)
            pygame.time.set_timer(Game.BRAVO_EVENT, ms)

        # User clicked the mode indicator---adjust the font choice
        elif self.get_mode_rect().collidepoint(pos):
            self.mode = (self.mode + 1) % len(self.mode_imgs)

        # User clicked the bubble count indicator---adjust the number of bubbles
        elif self.get_bubbles_rect().collidepoint(pos):
            rect = self.get_bubbles_rect()
            maxn = len(self.bubble_imgs)
            n = 1+ int( ((pos[0] - rect.left)/rect.width) * maxn)
            n = int(max(1, min(n, maxn)))
            n = max(n, 1)
            n = int(n)
            self.bubbles[self.target], self.bubbles[0] \
                    = self.bubbles[0], self.bubbles[self.target]
            self.target = 0
            while len(self.bubbles) < n:
                self.bubbles.append(self.make_bubble())
            while len(self.bubbles) > n:
                i = random.randrange(1, len(self.bubbles))
                self.bubbles[i], self.bubbles[len(self.bubbles)-1] \
                    = self.bubbles[len(self.bubbles)-1], self.bubbles[i]
                del self.bubbles[len(self.bubbles)-1]
            
        # User clicked somewhere else
        else: 
            self.wrong_sound.play()
            if android:
                android.vibrate(1)
            for i in range(len(self.bubbles)):
                b = self.bubbles[i]
                if distance(pos, b.center()) < b.radius:
                    # user clicked wrong bubble, pop it anyway
                    self.pop_sound.play()
                    self.bubbles[i] = self.make_bubble()
예제 #28
0
def game_main():
    global first_time,number_list,over_ride
    new()
    #mixer.music.play(-1)
    while True:
        for event in pygame.event.get():
            if event.type==QUIT or (event.type==KEYUP and event.key==K_ESCAPE):
                new()
                
            elif event.type==MOUSEBUTTONDOWN:
                if new_rect.collidepoint(event.pos):
                    button_animation(DISPLAYSURF,new_image_down,new_image_up,new_rect)
                    fade_in(DISPLAYSURF)
                    new()
                elif undo_rect.collidepoint(event.pos):
                    button_animation(DISPLAYSURF,undo_image_down,undo_image_up,undo_rect)
                    if not first_time and undo==True:
                        number_list=[]
                        number_list.extend(previous_number_list)
                        previous_triangle.player=previous_player
                        if previous_first_time:
                            first_time=previous_first_time
                        if not over_ride:
                            FIRST_PLAYER,SECOND_PLAYER=SECOND_PLAYER,FIRST_PLAYER
                        over_ride=previous_over_ride
                        draw_board(FIRST_PLAYER)
                        fade_in_out(DISPLAYSURF)
                        undo=False
                        break
                    
                for i in range(0,r_c): 
                    for j in range(0,r_c):
                        block=list_of_objects[i][j]
                        if block.rect.collidepoint(event.pos):
                            if first_time:
                                if number_list[r_c*i+j]%2==0:
                                    FIRST_PLAYER=PLAYER1
                                    SECOND_PLAYER=PLAYER2
                                else:
                                    FIRST_PLAYER=PLAYER2
                                    SECOND_PLAYER=PLAYER1
                                previous_first_time=first_time
                                first_time=False
                            else:
                                previous_first_time=first_time
                            if (number_list[r_c*i+j]%2==0 and FIRST_PLAYER==PLAYER1) or (number_list[r_c*i+j]%2!=0 and FIRST_PLAYER==PLAYER2):
                                if block.triangles[0].collide(event.pos):
                                    k=0
                                    if FIRST_PLAYER==PLAYER2:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER2 and over_ride):
                                            player2_0_rect.center=(block.triangles[0].pts[0][0]+BLOCK_SIZE/2-BLOCK_WIDTH/2,block.triangles[0].pts[0][1]+BLOCK_SIZE/4+BLOCK_WIDTH/4)
                                            put_in(DISPLAYSURF,player2_0,player2_0_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                    else:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER1 and over_ride):
                                            player1_0_rect.center=(block.triangles[0].pts[0][0]+BLOCK_SIZE/2-BLOCK_WIDTH/2,block.triangles[0].pts[0][1]+BLOCK_SIZE/4+BLOCK_WIDTH/4)
                                            put_in(DISPLAYSURF,player1_0,player1_0_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                elif block.triangles[1].collide(event.pos):
                                    k=1
                                    if FIRST_PLAYER==PLAYER2:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER2 and over_ride):
                                            player2_1_rect.center=(block.triangles[1].pts[0][0]+BLOCK_SIZE/4+BLOCK_WIDTH/4,block.triangles[1].pts[0][1]+BLOCK_SIZE/2-BLOCK_WIDTH/2)
                                            put_in(DISPLAYSURF,player2_1,player2_1_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                    else:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER1 and over_ride):
                                            player1_1_rect.center=(block.triangles[1].pts[0][0]+BLOCK_SIZE/4+BLOCK_WIDTH/4,block.triangles[1].pts[0][1]+BLOCK_SIZE/2-BLOCK_WIDTH/2)
                                            put_in(DISPLAYSURF,player1_1,player1_1_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                elif block.triangles[2].collide(event.pos):
                                    k=2
                                    if FIRST_PLAYER==PLAYER2:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER2 and over_ride):
                                            player2_2_rect.center=(block.triangles[2].pts[0][0]+BLOCK_SIZE/2-BLOCK_WIDTH/2,block.triangles[2].pts[0][1]-BLOCK_SIZE/4-BLOCK_WIDTH/4)
                                            put_in(DISPLAYSURF,player2_2,player2_2_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                    else:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER1 and over_ride):
                                            player1_2_rect.center=(block.triangles[2].pts[0][0]+BLOCK_SIZE/2-BLOCK_WIDTH/2,block.triangles[2].pts[0][1]-BLOCK_SIZE/4-BLOCK_WIDTH/4)
                                            put_in(DISPLAYSURF,player1_2,player1_2_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                else:
                                    k=3
                                    if FIRST_PLAYER==PLAYER2:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER2 and over_ride):
                                            player2_3_rect.center=(block.triangles[3].pts[0][0]-BLOCK_SIZE/4-BLOCK_WIDTH/4,block.triangles[3].pts[0][1]-BLOCK_SIZE/2+BLOCK_WIDTH/2)
                                            put_in(DISPLAYSURF,player2_3,player2_3_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                    else:
                                        if block.triangles[k].player==None or (block.triangles[k].player!=PLAYER1 and over_ride):
                                            player1_3_rect.center=(block.triangles[3].pts[0][0]-BLOCK_SIZE/4-BLOCK_WIDTH/4,block.triangles[3].pts[0][1]-BLOCK_SIZE/2+BLOCK_WIDTH/2)
                                            put_in(DISPLAYSURF,player1_3,player1_3_rect)
                                            undo=True
                                            previous_triangle=block.triangles[k]
                                previous_player=block.triangles[k].player
                                block.triangles[k].player=FIRST_PLAYER
                                if blocked(FIRST_PLAYER,i,j,k)==False:
                                    if previous_player==None:
                                        FIRST_PLAYER,SECOND_PLAYER=SECOND_PLAYER,FIRST_PLAYER
                                        previous_over_ride=over_ride
                                        over_ride=False
                                        previous_number_list=[]
                                        previous_number_list.extend(number_list)
                                        random.shuffle(number_list)
                                        
                                    elif previous_player==SECOND_PLAYER and over_ride==True:
                                        FIRST_PLAYER,SECOND_PLAYER=SECOND_PLAYER,FIRST_PLAYER
                                        previous_over_ride=over_ride
                                        over_ride=False
                                        previous_number_list=[]
                                        previous_number_list.extend(number_list)
                                        random.shuffle(number_list)
                                        
                                    elif previous_player==SECOND_PLAYER and over_ride==False:
                                        block.triangles[k].player=previous_player  
                                elif blocked(FIRST_PLAYER,i,j,k)==True:
                                    if previous_player==SECOND_PLAYER and over_ride==False:
                                        block.triangles[k].player=previous_player
                                    elif previous_player==FIRST_PLAYER:
                                        pass
                                    else:
                                        previous_over_ride=over_ride
                                        over_ride=True
                                        play_block_sound()
                                        pygame.time.wait(20)
                                        if android:
                                            android.vibrate(0.2)
                                        shake(DISPLAYSURF)
                                        previous_number_list=[]
                                        previous_number_list.extend(number_list)
                                        random.shuffle(number_list)
                            if not over_ride:
                                play_put_sound()
                            draw_board(FIRST_PLAYER)
        pygame.display.update()
        if not first_time:
            if check_end(FIRST_PLAYER,over_ride):
                play_end_sound()
                pygame.time.wait(500)
                display_win_message()
                end_event_handeling_function()
                new()
예제 #29
0
def vibrate():
	if android:
		android.vibrate(0.3)
예제 #30
0
def vibrate(seconds):
    if android:
        android.vibrate(seconds)
        print("Vibration finished")
    else:
        print("Vibration is only available on Android")
예제 #31
0
 def vibrate(self, t):
     # Vibrace Android telefonu
     android.vibrate(t)
예제 #32
0
파일: main.py 프로젝트: looneyka/MobileApp
 def build(self):
     register(APPLICATION_ID, REST_API_KEY)
     android.vibrate(2)
예제 #33
0
	def lifechange(self):
		self.lives -= 1
		self.img_life = self.font.render(str(self.lives), True, (255, 0, 0))
		self.just_died = True
		if android:
			android.vibrate(0.3)
                                    previous_number_list.extend(number_list)
                                    random.shuffle(number_list)
                                    
                                elif previous_player==SECOND_PLAYER and over_ride==False:
                                    block.triangles[k].player=previous_player  
                            elif blocked(FIRST_PLAYER,i,j,k)==True:
                                if previous_player==SECOND_PLAYER and over_ride==False:
                                    block.triangles[k].player=previous_player
                                elif previous_player==FIRST_PLAYER:
                                    pass
                                else:
                                    previous_over_ride=over_ride
                                    over_ride=True
                                    play_block_sound()
                                    if android:
                                        android.vibrate(0.2)
                                    shake(DISPLAYSURF)
                                    previous_number_list=[]
                                    previous_number_list.extend(number_list)
                                    random.shuffle(number_list)
                        draw_board(FIRST_PLAYER)
    pygame.display.update()
    if not first_time:
        if check_end(FIRST_PLAYER,over_ride):
            play_end_sound()
            pygame.time.wait(500)
            display_win_message()
            end_event_handeling_function()
            new()

예제 #35
0
    def fightBattle(self, game, enemy, board_, enemyImgs, heroImgs):
        self.heroImgs = heroImgs
        self.enemyImgs = enemyImgs
        self.enemyAvatar = enemyImgs[self.enemyImgIdx]
        self.heroAvatar = heroImgs[self.heroImgIdx]
        self.drawBattleScreen(game, enemy)
        game.FX.scrollFromCenter(board_, self.battleField)
        hero = game.myHero
        (cHP, mHP, cMP, mMP, sth, dex, itl, scr, kys, cEX, nEX,
         psn) = hero.getPlayerStats()
        (armor, weapon) = (hero.getArmorEquipped(), hero.getWeaponEquipped())
        if enemy.getLevel() > 0:
            game.textMessage('You are facing a level {} {}!'.format(
                enemy.getLevel(), enemy.getName()))
        else:
            game.textMessage('You are facing the {}!'.format(enemy.getName()))
        time = 0
        while enemy.getHP() > 0:
            self.drawBattleScreen(game, enemy)
            if not hero.updateStatus(game):
                return False
            # hero turn
            while not self.heroTurn(game, enemy, board_):
                pass
            game.myInterface.update(game)
            self.drawBattleScreen(game, enemy)

            game.Ticker.tick(10)
            #enemy attacks
            self.drawEnemyAttack(game, enemy)
            if enemy.getHP() > 0:
                if not misc.rollDie(hero.dex, const.maxStats):
                    dmg = random.randrange(
                        enemy.getBaseAttack() - 5,
                        enemy.getBaseAttack() + 5) - (hero.armorClass)
                    if dmg > 0:
                        game.textMessage("The " + enemy.getName() +
                                         " hits you for " + str(dmg) +
                                         " points!")
                        if enemy.poison:
                            if misc.rollDie(0, 3):
                                if hero.isDamned:
                                    hero.isDamned = False
                                hero.isPoisoned = True
                                hero.poisonedAt = game.Ticker.getTicks()
                                game.textMessage("You are poisoned!")
                        elif enemy.damned:
                            if misc.rollDie(0, 3):
                                if hero.isPoisoned:
                                    hero.isPoisoned = False
                                hero.isDamned = True
                                hero.damnedAt = game.Ticker.getTicks()
                                game.textMessage("You are damned!")
                        game.SFX.play(1)
                        self.enemyImg = self.enemyImgs[1]
                        if android:
                            android.vibrate(0.1)
                    else:
                        game.textMessage(
                            "The {} attack is ineffective.".format(
                                enemy.getName()))
                    if hero.takeDmg(dmg) < 1:
                        game.textMessage("You have died!")
                        #game.FX.scrollFromCenter(self.battleField, board_)
                        return 'died'
                else:
                    game.textMessage("The " + enemy.getName() + " missed you!")
                    game.SFX.play(2)
            game.Ticker.tick(10)
            game.myInterface.update(game)
            self.drawBattleScreen(game, enemy)
            pygame.time.wait(1000)
        game.textMessage("The " + enemy.getName() + " is dead!")
        if hero.increaseExp(enemyScr.expDict[enemy.getName()] +
                            random.randrange(enemy.getLevel() * 2,
                                             enemy.getLevel() * 4)):
            game.textMessage("Congratulations! You have gained a level.")
        game.FX.scrollFromCenter(self.background, board_)
        return 'won'
        return 'won'
예제 #36
0
 def fightBattle(self, game, enemy, board_, enemyImgs, heroImgs):
     self.heroImgs = heroImgs
     self.enemyImgs = enemyImgs
     self.enemyAvatar = enemyImgs[self.enemyImgIdx]
     self.heroAvatar = heroImgs[self.heroImgIdx]
     self.drawBattleScreen(game, enemy)
     game.FX.scrollFromCenter(board_, self.battleField)
     hero = game.myHero
     (cHP, mHP, cMP, mMP, sth, dex, itl, scr, kys, cEX, nEX, psn) = hero.getPlayerStats()
     (armor, weapon) = (hero.getArmorEquipped(), hero.getWeaponEquipped())
     if enemy.getLevel() > 0:
         game.textMessage('You are facing a level {} {}!'.format(enemy.getLevel(), enemy.getName()))
     else:
         game.textMessage('You are facing the {}!'.format(enemy.getName()))
     time = 0
     while enemy.getHP() > 0:
         self.drawBattleScreen(game, enemy)
         if not hero.updateStatus(game):
             return False
         # hero turn
         while not self.heroTurn(game, enemy, board_):
             pass
         game.myInterface.update(game)
         self.drawBattleScreen(game, enemy)
         
         game.Ticker.tick(10)
         #enemy attacks
         self.drawEnemyAttack(game, enemy)
         if enemy.getHP() > 0:
             if not misc.rollDie(hero.dex, const.maxStats):
                 dmg = random.randrange(enemy.getBaseAttack()-5,enemy.getBaseAttack()+5) - ( hero.armorClass )
                 if dmg > 0:
                     game.textMessage("The "+enemy.getName()+" hits you for "+str(dmg)+" points!")
                     if enemy.poison:
                         if misc.rollDie(0,3):
                             if hero.isDamned:
                                 hero.isDamned = False
                             hero.isPoisoned = True
                             hero.poisonedAt = game.Ticker.getTicks()
                             game.textMessage("You are poisoned!")
                     elif enemy.damned:
                         if misc.rollDie(0,3):
                             if hero.isPoisoned:
                                 hero.isPoisoned = False
                             hero.isDamned = True
                             hero.damnedAt = game.Ticker.getTicks()
                             game.textMessage("You are damned!")
                     game.SFX.play(1)
                     self.enemyImg = self.enemyImgs[1]
                     if android:
                         android.vibrate(0.1)
                 else: game.textMessage("The {} attack is ineffective.".format(enemy.getName()))
                 if hero.takeDmg(dmg) < 1:
                     game.textMessage("You have died!")
                     #game.FX.scrollFromCenter(self.battleField, board_)
                     return 'died'
             else:
                 game.textMessage("The "+enemy.getName()+" missed you!")
                 game.SFX.play(2)
         game.Ticker.tick(10)
         game.myInterface.update(game)
         self.drawBattleScreen(game, enemy)
         pygame.time.wait(1000)
     game.textMessage("The "+enemy.getName()+" is dead!")
     if hero.increaseExp( enemyScr.expDict[enemy.getName()] + random.randrange(enemy.getLevel()*2, enemy.getLevel()*4)  ):
         game.textMessage("Congratulations! You have gained a level.")
     game.FX.scrollFromCenter(self.background, board_)
     return 'won'
     return 'won'
예제 #37
-1
파일: main.py 프로젝트: jvelez/KinderGame
	def HandleInput(self,event):
		if Mouse[MLC] == True or Mouse[MRC] == True:
			if PointRectIntersection2(Mouse[MX],Mouse[MY],self.rect):
				self.clicked = True
				if android:
					android.vibrate(0.04);
				Mouse[MLC] = Mouse[MRC] = False
		else:
			self.clicked = False