Beispiel #1
0
 def catch(self, target):
     """Is the potentially unlucky target actually unlucky?"""
     if hasattr(self, 'TRAP_SOUND'):
         sound.play_sound(self.TRAP_SOUND)
     roll = random.randint(1, 100)
     base_catch = getattr(self, 'BASE_CATCH')
     return roll > (100 - base_catch)
def check_collisions(game_settings, game_stats, scoreboard, screen, ship,
                     bullets, aliens):
    #Check for collisions between bullets and aliens, removes both
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    #updates the score
    if collisions:
        for aliens_hit in collisions.values():
            #checks whether the hit alien is destroyed and scores accordingly
            while aliens_hit:
                alien = aliens_hit.pop()
                if (alien.change_color()):
                    sound.play_sound(game_settings.hit_2)
                    aliens.add(alien)
                else:
                    sound.play_sound(game_settings.alien_destroyed)
                    game_stats.score += alien.point_value
                    scoreboard.prep_score()

        check_high_score(game_stats, scoreboard)

    #repopulate fleet if no aliens left
    if len(aliens) <= 0:
        bullets.empty()
        game_settings.increase_speed()

        #Increase the level
        game_stats.level += 1
        scoreboard.prep_level()

        create_fleet(game_settings, game_stats, screen, ship, aliens)
Beispiel #3
0
 def fire(self, level):
   if self.fire_delay == 0:
     play_sound("fire")
     self.fire_delay = SPIDER_FIRE_DELAY
     fire_direction = get_direction(self.attached)
     level.objects.append(Projectile(self.screen, self.x, self.y, fire_direction[0]*-SPIDER_PROJECTILE_SPEED, fire_direction[1]*-SPIDER_PROJECTILE_SPEED, SPIDER_DAMAGE, "energy"))
   return
Beispiel #4
0
    def move(self, x, y):
        # when Mario hits the Marijuana
        if common.value_arr(x, y) == "$":
            sound.play_sound("mb_sc.wav")
            for i in config.M_LIST:
                if i.x_pos == x or i.x_pos == x + 1 or i.x_pos == x - 1:
                    if i.y_pos == y or i.y_pos == y + 1 or i.y_pos == y - 1:
                        config.POINTS += 20
                        config.M_LIST.remove(i)
        try:

            if (x > common.R3 and x < common.R4):
                check.check_life(x, y, "Mario")
                self.refresh_out()
                super().move(x, y)
                self.print_out()

            else:
                movement.move_all(x - self.x_pos)
                check.check_life(self.x_pos, y, "Mario")
                self.refresh_out()
                super().move(self.x_pos, y, "Mario")
                self.print_out()

        except config.GapHere:
            raise config.DeadMario from None
Beispiel #5
0
 def damage_in_area(self, gameboard, wielder, target_pos):
     """For explosive weapons, affect foxes close to the target position"""
     if self.ammunition is not None:
         if self.ammunition <= 0:
             # Out of ammunition, so we don't get to shoot.
             return
         else:
             self.ammunition -= 1
     if hasattr(self, 'HIT_SOUND'):
         sound.play_sound(self.HIT_SOUND)
     if hasattr(self, 'ANIMATION'):
         self.ANIMATION(gameboard.tv, wielder)
     base_hit = self._get_parameter('BASE_HIT', wielder)
     range_penalty = self._get_parameter('RANGE_PENALTY', wielder)
     training_bonus = getattr(wielder, 'TRAINING', 0) * 10
     roll = random.randint(training_bonus + 1, 100)
     damaged_foxes = set()
     for fox in gameboard.foxes:
         if target_pos.dist(fox.pos) <= self.DAMAGE_RANGE:
             damage_penalty = self.DAMAGE_RANGE_PENALTY * fox.pos.dist(
                 target_pos)
             if roll > (100 - base_hit) + range_penalty * (
                     wielder.pos.dist(target_pos) + damage_penalty):
                 damaged_foxes.add(fox)
     for fox in damaged_foxes:
         fox.damage()
Beispiel #6
0
 def jump(self):
   if self.on_ground:
     play_sound("boing", 0.5)
     self.dy = -PLAYER_JUMP_ACC
   else:
     self.dy -= PLAYER_AIR_JUMP
     self.umbrella_on = True
Beispiel #7
0
 def die(self):
     """Play death animation, noises, whatever."""
     if hasattr(self, 'DEATH_SOUND'):
         sound.play_sound(self.DEATH_SOUND)
     if hasattr(self, 'DEATH_ANIMATION'):
         self.DEATH_ANIMATION(self.gameboard.tv, self.pos.to_tile_tuple())
     self._game_death()
Beispiel #8
0
 def next(self):
     if self.shape.at_bottom():
         play_sound('drop')
         self.check_line()
         self.shape.new()
         self.display_info()
     else:
         self.shape.move(0, 1)
Beispiel #9
0
 def next(self):
     if self.shape.at_bottom():
         play_sound('drop')
         self.check_line()
         self.shape.new()
         self.display_info()
     else:
         self.shape.move(0, 1)
 def jump(self):
   if (self.on_ground):
     self.dy = -PLAYER_JUMP_ACC
     play_sound("boing", 0.5)
   else:
     self.dy -= PLAYER_AIR_JUMP
     self.umbrella_on = True
   return
Beispiel #11
0
def opponentDecreased(remaining):
    print("Opponent ship sunk!")

    if client.opponentShipsPrev == 0:
        print("You win!")
        sound.play_sound("victory")

    displayRemaining(remaining)
Beispiel #12
0
def weDecreased(remaining):
    print("Shp sunk :(")

    if client.ourShipsPrev == 0:
        print("You lose.")
        sound.play_sound("loss")

    displayRemaining(remaining)
Beispiel #13
0
 def do_sell(chicken, update_button=None):
     # We try sell and egg
     if self.sell_one_egg(chicken):
         sound.play_sound("sell-chicken.ogg")
         # Force toolbar update
         self.toolbar.chsize()
         if update_button:
             update_button(chicken)
     return False
Beispiel #14
0
    def init(self):
        """Add some chickens to the farm"""
        sound.stop_background_music()
        self.game.gameboard.start_day()

        sound.play_sound("daybreak.ogg")
        # disable timer
        pygame.time.set_timer(constants.MOVE_FOX_ID, 0)
        sound.background_music("daytime.ogg")
 def take_damage(self, amount, x = None, y = None):
   last_life = self.life
   blood = DynamicObject.take_damage(self, amount, x, y)
   if self.current_animation != "dying":
     self.current_animation = "shouting"
     play_sound("augh")
   elif last_life > 0:
     play_sound("augh")
   return blood
Beispiel #16
0
 def jump(self):
   if (self.on_ground):
     self.dy = -PLAYER_JUMP_ACC
     self.on_ground = False
     play_sound("boing", 0.5)
   else:
     self.dy -= PLAYER_AIR_JUMP
     self.umbrella_on = True
   return
Beispiel #17
0
 def fire(self, level):
     if self.fire_delay == 0:
         play_sound("fire")
         self.fire_delay = SPIDER_FIRE_DELAY
         fire_direction = get_direction(self.attached)
         level.objects.append(
             Projectile(self.screen, self.x, self.y,
                        fire_direction[0] * -SPIDER_PROJECTILE_SPEED,
                        fire_direction[1] * -SPIDER_PROJECTILE_SPEED,
                        SPIDER_DAMAGE, "energy"))
     return
Beispiel #18
0
def worker_voice(event_voice):
    """音声再生のためのworker
    """
    while not stop:
        # event.set が実行されるまで待機
        event_voice.wait()
        event_voice.clear()
        logging.debug('voice start')
        text = text_generator.generate_text(working_state)
        # time.sleep(3)
        sound.play_sound(text)
        logging.debug('voice end')
Beispiel #19
0
def play_signal(signal, sample_rate):
    #write to a wav file
    wf = WavFile()
    #wf.data = state[:, 0]
    wf.data = signal
    wf.sample_rate = sample_rate
    wf.num_channels = 1

    md5 = get_signal_md5(signal)
    fname = '/tmp/%s.wav' % md5
    if not os.path.exists(fname):
        wf.to_wav(fname)
    play_sound(fname)
Beispiel #20
0
    def init(self):
        """Add some foxes to the farm"""
        sound.stop_background_music()
        self.game.gameboard.start_night()

        sound.play_sound("nightfall.ogg")

        # Add a timer to the event queue
        self.cycle_count = 0
        self.cycle_time = SLOW__SPEED
        pygame.time.set_timer(constants.MOVE_FOX_ID, self.cycle_time)
        sound.background_music("nighttime.ogg")

        self.dialog = None
Beispiel #21
0
 def run(self, elapse):
     self.draw()
     for e in pygame.event.get():
         if e.type == QUIT:
             return r'quit'
         elif e.type == KEYDOWN:
             if e.key == K_UP:
                 self.current = (self.current - 1) % len(self.OPTS)
                 play_sound('menu')
             elif e.key == K_DOWN:
                 self.current = (self.current + 1) % len(self.OPTS)
                 play_sound('menu')
             elif e.key == K_RETURN:
                 return self.OPTS[self.current].lower()
     return 'menu'
Beispiel #22
0
 def run(self, elapse):
     self.draw()
     for e in pygame.event.get():
         if e.type == QUIT:
             return 'quit'
         elif e.type == KEYDOWN:
             if e.key == K_UP:
                 self.current = (self.current - 1) % len(self.OPTS)
                 play_sound('menu')
             elif e.key == K_DOWN:
                 self.current = (self.current + 1) % len(self.OPTS)
                 play_sound('menu')
             elif e.key == K_RETURN:
                 return self.OPTS[self.current].lower()
     return 'menu'
Beispiel #23
0
def refreshGrid(checkOpponent=False):
    global grid, opponent, lastGrid, aiInGame

    client.updateGrid()
    updated = client.recv()
    grid.load(updated)

    if updated != lastGrid and not aiInGame:
        sound.play_sound("alert")

    lastGrid = updated

    if checkOpponent:
        client.updateOpponentGrid()
        updated = client.recv()
        opponent.load(updated)
Beispiel #24
0
 def do_sell(chicken, update_button=None):
     if not chicken:
         return False  # sanity check
     if len(self.chickens) == 1:
         msg = "You can't sell your last chicken!"
         TextDialog("Squuaaawwwwwk!", msg).open()
         return False
     for item in list(chicken.equipment):
         self.add_cash(item.sell_price())
         chicken.unequip(item)
     self.add_cash(self.level.sell_price_chicken)
     sound.play_sound("sell-chicken.ogg")
     if update_button:
         update_button(chicken, empty=True)
     self.remove_chicken(chicken)
     return True
Beispiel #25
0
def game_over():
    """
    Game over
    """
    sound.play_sound("nsmb_game_over.wav")
    restart_all()
    os.system("tput reset")
    print("MARIO GAME BY R.S.SUBBULAKSHMI\t\t\tPOINTS: " + str(config.POINTS) +
          "\t\t\tLIVES: " + str(config.LIVES) + "\t\t\tLEVEL: " +
          str(config.LEVEL) + "\n")
    if config.STAGE == "won":
        print("WON WON WON !!!\n")
    elif config.STAGE == "quit":
        print("QUIT !\n")
    else:
        print("LOST SORRY !\n")
def ship_hit(game_settings, game_stats, screen, scoreboard, ship, bullets,
             aliens):
    """if ship is hit, check if we still have lives left otherwise end the game"""
    if game_stats.ships_left > 0:
        game_stats.ships_left -= 1
        scoreboard.prep_lives()
        aliens.empty()
        bullets.empty()
        create_fleet(game_settings, game_stats, screen, ship, aliens)
        ship.center_ship()
        sound.play_sound(game_settings.ship_destroyed)
        sleep(1)
    else:
        game_stats.game_active = False
        sleep(1)
        gosf.game_over_screen(game_settings, game_stats, screen)
        pygame.mouse.set_visible(True)
Beispiel #27
0
 def hit(self, gameboard, wielder, target):
     """Is the potentially unlucky target actually unlucky?"""
     if self.ammunition is not None:
         if self.ammunition <= 0:
             # Out of ammunition, so we don't get to shoot.
             return
         else:
             self.ammunition -= 1
     if hasattr(self, 'HIT_SOUND'):
         sound.play_sound(self.HIT_SOUND)
     if hasattr(self, 'ANIMATION'):
         self.ANIMATION(gameboard.tv, wielder)
     training_bonus = getattr(wielder, 'TRAINING', 0) * 10
     roll = random.randint(training_bonus + 1, 100)
     base_hit = self._get_parameter('BASE_HIT', wielder)
     range_penalty = self._get_parameter('RANGE_PENALTY', wielder)
     return roll > (100 -
                    base_hit) + range_penalty * wielder.pos.dist(target.pos)
Beispiel #28
0
def select_ships(playernumber, ships, currentboard, AI):
    '''Adds a ship with the given length to the current players shipboard'''
    del shipcord[:]
    for a in range(ships):
        os.system('clear')
        if playernumber == 1:
            print('\x1b[6;30;42m' + 'Player ' + str(playernumber) + '\x1b[0m')
        elif playernumber == 2:
            if AI == 1:
                print('\x1b[6;30;43m' + "Computer" + '\x1b[0m')
            else:
                print('\x1b[6;30;43m' + 'Player ' + str(playernumber) +
                      '\x1b[0m')
        print()
        boardhandle.print_board(currentboard)
        addship(shiplength[a], currentboard, playernumber, AI)
        sound.play_sound("placement")
    return shipcord
Beispiel #29
0
    def act(self):
        if self.active and self.progress <= .5 + self.threshold and self.progress >= .5 - self.threshold:
            if not self.getting_input:
                global current_game
                current_game.play_chime()
            self.getting_input = True

        else:
            self.getting_input = False

        if not self.failure and not self.success and self.progress > .5 + self.threshold:
            self.failure = True
            r = random.choice(string.punctuation)
            self.parent.result_text += r
            self.lft.set_letter(r)
            self.rht.set_letter(r)
            sound.play_sound('../sfx/fail.ogg')
            self.set_all('plasma', False)
Beispiel #30
0
    def act(self):
        if self.active and self.progress <= 0.5 + self.threshold and self.progress >= 0.5 - self.threshold:
            if not self.getting_input:
                global current_game
                current_game.play_chime()
            self.getting_input = True

        else:
            self.getting_input = False

        if not self.failure and not self.success and self.progress > 0.5 + self.threshold:
            self.failure = True
            r = random.choice(string.punctuation)
            self.parent.result_text += r
            self.lft.set_letter(r)
            self.rht.set_letter(r)
            sound.play_sound("../sfx/fail.ogg")
            self.set_all("plasma", False)
Beispiel #31
0
    def set_alarm(self):
        # Read mins from config file
        if not self._work_mins:
            sec = 25 * 60
        else:
            sec = self._work_mins * 60

        logger = logging.getLogger("tosu")

        # starting sound effect & notification
        # the dict is passed into callback: self.alarm
        play_sound("scifi_start.wav")
        if self._nc:
            self._nc.notify("A task have been started", title="todo-summary")

        self._m1 = sec * 1 / 3
        self._m2 = sec * 2 / 3
        self._timer_handle = self.loop.set_alarm_in(0, self.timer, sec)
Beispiel #32
0
 def take_damage(self, amount, x = None, y = None):
   blood = []
   if (x == None):
     x = self.x
     y = self.y
   if self.destructable:
     self.life -= amount
     count = 0
     if self.current_animation != "dying":
       if (self.itemclass == "player"):
         self.current_animation = "shouting"
         play_sound("augh")
       while (count < amount):
         blood.append(Particle(self.screen, 15, x + random.uniform(-3, 3), y + random.uniform(-3, 3), 0, 0, 0.3, COLOR_BLOOD, 4))
         count += 1
     if self.life < 1:
       self.life = 0
       self.die()
   return blood
Beispiel #33
0
 def kill_line(self, filled = []):
     if len(filled)  == 0:
         return
     play_sound(str(len(filled)))
     mask = pygame.Surface((self.WIDTH, self.TILEW), SRCALPHA, 32)
     for i in xrange(5):
         if i % 2 == 0:
             mask.fill((255, 255, 255, 100))
         else:
             mask.fill((255, 255, 255, 200))
         self.screen.blit(self.board_image, self.START)
         for line in filled:
             self.screen.blit(mask,      \
                 (self.START[0], self.START[1]+line*self.TILEW))
             pygame.display.update()
         pygame.time.wait(80)
     #remove filled lines
     [self.board.pop(l) for l in sorted(filled, reverse=True)]
     #fill with blank lines
     [self.board.insert(0, [None]*self.W) for l in filled]
     self.get_score(len(filled))
Beispiel #34
0
 def kill_line(self, filled=[]):
     if len(filled) == 0:
         return
     play_sound(str(len(filled)))
     mask = pygame.Surface((self.WIDTH, self.TILEW), SRCALPHA, 32)
     for i in xrange(5):
         if i % 2 == 0:
             mask.fill((255, 255, 255, 100))
         else:
             mask.fill((255, 255, 255, 200))
         self.screen.blit(self.board_image, self.START)
         for line in filled:
             self.screen.blit(mask,      \
                 (self.START[0], self.START[1]+line*self.TILEW))
             pygame.display.update()
         pygame.time.wait(80)
     #remove filled lines
     [self.board.pop(l) for l in sorted(filled, reverse=True)]
     #fill with blank lines
     [self.board.insert(0, [None] * self.W) for l in filled]
     self.get_score(len(filled))
Beispiel #35
0
def render_text_dialogue(screen, string, phase, key='z'):
    """
    This function renders text partially.
    For fancy dialogue display.
    The phase value is the amount of characters shown.
    -1 phase means that the whole string is visible.
    """
    if phase == -1:
        phase = len(string)

    rendered_string = string[0:phase]
    string_image = render_text(rendered_string)
    string_rect = string_image.get_rect()
    string_rect.centerx = SCREEN_WIDTH / 2
    string_rect.centery = SCREEN_HEIGHT / 2

    if key == 'p':
        skip_image = Util.cached_images['key_p']
    else:
        skip_image = Util.cached_images['key_z']

    skip_rect = skip_image.get_rect()
    skip_rect.centerx = SCREEN_WIDTH / 2
    skip_rect.top = string_rect.bottom + 5

    bg_rect = pygame.Rect(string_rect.left - 10, string_rect.top - 5, string_rect.width + 20, string_rect.height + skip_rect.height + 15)
    bg_image = pygame.Surface((bg_rect.width, bg_rect.height))  
    bg_image.set_alpha(FADE_STATE_HALF)

    screen.blit(bg_image, bg_rect)
    screen.blit(string_image, string_rect)
    screen.blit(skip_image, skip_rect)

    if phase < len(string):
        phase += 1
        play_sound('click')
    else:
        return -1

    return phase
def main():
    # start screens and game informations
    os.system('clear')
    prints.startscreen()
    start = input("")
    prints.selecthelp(ships)
    start = input("")
    AI = prints.ai_or_player()
    sound.play_sound("start")
    # ship selection beginning
    currentboard = boardhandle.p1ship
    p1shipcord = deepcopy(
        shipboard_setup.select_ships(1, ships, currentboard, AI))
    os.system('clear')
    print()
    print()
    boardhandle.print_board(boardhandle.p1ship)
    confirm = input("Press enter to continue")
    currentboard = boardhandle.p2ship
    p2shipcord = deepcopy(
        shipboard_setup.select_ships(2, ships, currentboard, AI))
    os.system('clear')
    print()
    print()
    if AI == 1:
        pass
    else:
        boardhandle.print_board(boardhandle.p2ship)
        confirm = input("Press enter to continue")
        os.system('clear')
    # attack phase beginning
    playernumber = 1
    while True:
        alivep1 = 0
        alivep2 = 0
        attack.nextplayer(playernumber, AI)
        attack.attack(playernumber, currentboard, AI, p1shipcord, p2shipcord)
        if playernumber == 1:
            playernumber = 2
        else:
            playernumber = 1
        for i in range(1, 11):
            if "O" in boardhandle.p1ship[i]:
                alivep1 += 1
        for i in range(1, 11):
            if "O" in boardhandle.p2ship[i]:
                alivep2 += 1
        if alivep1 < 1:
            break
        if alivep2 < 1:
            break
    if alivep1 == 0:
        os.system('clear')
        prints.player2won()
        sound.play_sound("clap")
    elif alivep2 == 0:
        os.system('clear')
        prints.player1won()
        sound.play_sound("clap")
    time.sleep(5)
Beispiel #37
0
 def take_damage(self, amount, x=None, y=None):
     blood = []
     if (x == None):
         x = self.x
         y = self.y
     if self.destructable:
         self.life -= amount
         count = 0
         if self.current_animation != "dying":
             if (self.itemclass == "player"):
                 self.current_animation = "shouting"
                 play_sound("augh")
             while (count < amount):
                 blood.append(
                     Particle(self.screen, 15, x + random.uniform(-3, 3),
                              y + random.uniform(-3, 3), 0, 0, 0.3,
                              COLOR_BLOOD, 4))
                 count += 1
         if self.life < 1:
             self.life = 0
             self.die()
     return blood
Beispiel #38
0
    def fire(self):
        if self.refire > self.wepdef.refire:
            sound.play_sound(self.name+"_fire")

            self.refire=0

            xm, zm=rotate([1, 0], radians(self.parent.gun_rot[0]))

            x_offset=self.parent.gun_offset[0]
            y_offset=self.parent.gun_offset[1]*xm+self.parent.gun_offset[2]*zm
            z_offset=self.parent.gun_offset[2]*xm-self.parent.gun_offset[1]*zm

            x_offset, y_offset=rotate([x_offset, y_offset], -radians(self.parent.gun_rot[2]))

#            gun_rot=[self.parent.gun_rot[0], self.parent.gun_rot[2]]
            gun_rot=self.parent.rot

            for i in range(self.wepdef.bullets):
                world.spawn_bullet(Bullet(self.parent.pos[0]+x_offset, self.parent.pos[1]+y_offset, self.parent.pos[2]+1.8+z_offset, [gun_rot[0], gun_rot[1]], [crange(0, random.random(), 1, -self.wepdef.spread, self.wepdef.spread), crange(0, random.random(), 1, -self.wepdef.spread, self.wepdef.spread), crange(0, random.random(), 1, -self.wepdef.spread, self.wepdef.spread)], self.wepdef.bulletspeed))

            return True
        return False
Beispiel #39
0
	def tick(self):
		if not self.move_speed and not var.cleaning and not self.player:
			if self.pos[0]<=0: self.direction = 'east';self.pos[1]+=1
			elif self.pos[0]>=var.win_size[0]-1: self.direction = 'west';self.pos[1]+=1
		elif not self.move_speed and self.player:
			if self.pos[0]<=0: self.pos[0]=1
			elif self.pos[0]>=var.win_size[0]-1: self.pos[0]=var.win_size[0]-2
		
		general.active.tick(self)
		
		if self.life <= 0: sound.play_sound(var.snd_explode1);self.destroy()
		
		self.last_pos = [self.pos[0],self.pos[1]]
		
		for wep in self.weapons:
			wep.tick()
			if not self.player and self.pos[1]>=self.y_limit: self.shoot('south')
		
		for b in var.bullets:
			if b.owner.player == self.player: continue
			
			if b.pos == self.pos or b.pos == self.last_pos:
				self.life-=1
				b.destroy()
Beispiel #40
0
def render_text_dialogue(screen, string, phase):
    if phase == -1:
        phase = len(string)

    rendered_string = string[0:phase]
    string_image = render_text(rendered_string)
    rect = string_image.get_rect()
    rect.centerx = SCREEN_WIDTH / 2
    rect.centery = SCREEN_HEIGHT / 2
    screen.blit(string_image, rect)

    skip_image = Util.cached_images["dialogueskip"]
    skip_rect = skip_image.get_rect()
    skip_rect.centerx = SCREEN_WIDTH / 2
    skip_rect.top = rect.bottom + 5
    screen.blit(skip_image, skip_rect)

    if phase < len(string):
        phase += 1
        play_sound("click")
    else:
        return -1

    return phase
def render_text_dialogue(screen, string, phase, key = "z"):
  if phase == -1:
    phase = len(string)

  rendered_string = string[0:phase]
  string_image = render_text(rendered_string)
  string_rect = string_image.get_rect()
  string_rect.centerx = SCREEN_WIDTH / 2
  string_rect.centery = SCREEN_HEIGHT / 2

  if key == "p":
    skip_image = Util.cached_images["key_p"]
  else:
    skip_image = Util.cached_images["key_z"]

  skip_rect = skip_image.get_rect()
  skip_rect.centerx = SCREEN_WIDTH / 2
  skip_rect.top = string_rect.bottom + 5

  bg_rect = pygame.Rect(string_rect.left - 10, string_rect.top - 5, string_rect.width + 20, string_rect.height + skip_rect.height + 15)
  bg_image = pygame.Surface((bg_rect.width, bg_rect.height))  
  bg_image.set_alpha(FADE_STATE_HALF)

  screen.blit(bg_image, bg_rect)

  screen.blit(string_image, string_rect)

  screen.blit(skip_image, skip_rect)

  if phase < len(string):
    phase += 1
    play_sound("click")
  else:
    return -1

  return phase
Beispiel #42
0
    def move(self, x, y):
        try:
            check.check(x, y, "Enemy")
            self.refresh_out()
            super().move(x, y)
            self.print_out()
        except (config.GapHere, config.TouchBoundary):
            config.E_LIST.remove(self)
            self.refresh_out()
        except config.WallHere:
            pass
        except config.MarioAbove:
            # enemy getting killed because of mario jumping on it
            sound.play_sound("mb_touch.wav")
            config.E_LIST.remove(self)
            self.refresh_out()
            config.POINTS += 10

        except config.DeadMario:
            config.M.refresh_out()
            self.refresh_out()
            super().move(x, y)
            self.print_out()
            raise config.DeadMario from None
def collide_brick(brick_width, brick_height, brick_x, brick_y, x, y, xvel,
                  yvel):
    # top face
    flag = 0
    if ((x == (brick_x - brick_height - 1))
            and ((y >= brick_y - 1) and (y <= (brick_y + brick_width)))
            and (xvel > 0)):
        xvel *= -1
        flag = 1
        sound.play_sound()

    #bottom face
    elif ((x == brick_x) and ((y >= brick_y - 1) and (y <=
                                                      (brick_y + brick_width)))
          and (xvel < 0)):
        xvel *= -1
        flag = 1
        sound.play_sound()

    #left face
    elif ((y == brick_y - 1)
          and ((x >= (brick_x - brick_height - 1)) and (x <= brick_x))
          and (yvel > 0)):
        yvel *= -1
        flag = 1
        sound.play_sound()

    #right face
    elif ((y == (brick_y + brick_width))
          and ((x >= (brick_x - brick_height - 1)) and (x <= brick_x))
          and (yvel < 0)):
        yvel *= -1
        flag = 1
        sound.play_sound()

    l = []
    l.append(xvel)
    l.append(yvel)
    l.append(flag)
    return l
Beispiel #44
0
    def timer(self, loop, sec):
        # count down timer, it is a callback.
        # When called, it will register itself to be called after 1 sec.
        if sec == 0:
            self.clock_tick(sec)
            self._timer_handle = None

            if not self._break:
                # Start break timer
                cur = self.get_todo_focus()
                if cur != 0:
                    view = self.todo_pile.widget_list[cur]
                    view.update_time()

                if self._nc:
                    self._nc.notify("Time to break", title="todo-summary")
                # TODO make sound in cfg
                play_sound("horn.wav")
                self.footer.set_text("Coffee time...")

                self._m1 = None
                self._m2 = None
                self._break = True
                # Start break timer
                self._timer_handle = self.loop.set_alarm_in(1, self.timer, self._rest_mins * 60)
            else:
                # break stop
                # TODO play a different sound
                self._break = False
                if self._nc:
                    self._nc.notify("Break done", title="todo-summary")
                play_sound("paper.wav")

            logger = logging.getLogger("tosu")
            logger.debug("timer exit")
            return
        else:
            self.clock_tick(sec)

            # TODO make sound in cfg
            if sec == self._m1 or sec == self._m2:
                play_sound("paper.wav")

            logger = logging.getLogger("tosu")
            logger.debug("timer")
            # save handle for the newly set alarm in app
            self._timer_handle = self.loop.set_alarm_in(1, self.timer, sec - 1)
Beispiel #45
0
    def update(self, d):
        for w in self.weapons:
            w.update(d)

        self.recoil.update(d, 0)

        if self.get_control("shoot"):
            if self.weapons[self.weapon].fire():
                self.recoil.value=1

                l=-self.weapons[self.weapon].wepdef.knockback

                xm=cos(radians(self.rot[0]))
                zm=-sin(radians(self.rot[0]))
                self.vel[0]+=sin(radians(self.rot[1]))*xm*l
                self.vel[1]+=cos(radians(self.rot[1]))*xm*l
                self.vel[2]+=zm*l

        self.time+=d

        self.rot[0]=clamp(-90, self.rot[0], 90)
        speed=d*self.get_speed()

        walking=False

        if self.get_control("weapon_next"):
            self.weapon+=1
            self.recoil.value=0.4
        if self.get_control("weapon_prev"):
            self.weapon-=1
            self.recoil.value=0.4
            
        if self.weapon < 0:
            self.weapon+=len(self.weapons)
        elif self.weapon >= len(self.weapons):
            self.weapon-=len(self.weapons)

        if self.get_control("walk_forward"):
            self.vel[0]+=sin(radians(self.rot[1]))*speed
            self.vel[1]+=cos(radians(self.rot[1]))*speed
            walking=True

        if self.get_control("walk_backward"):
            self.vel[0]-=sin(radians(self.rot[1]))*speed
            self.vel[1]-=cos(radians(self.rot[1]))*speed
            walking=True

        if self.get_control("strafe_left"):
            self.vel[0]-=sin(radians(self.rot[1]+90))*speed
            self.vel[1]-=cos(radians(self.rot[1]+90))*speed
            walking=True

        if self.get_control("strafe_right"):
            self.vel[0]+=sin(radians(self.rot[1]+90))*speed
            self.vel[1]+=cos(radians(self.rot[1]+90))*speed
            walking=True

        self.vel[2]-=options.get("gravity", float)*d

        if self.hit[2]:
            self.jump=1
            
        if self.get_control("jump") and self.jump > 0:
            if options.get("player_superjump", bool) and not self.hit[2]:
                l=((self.vel[0]**2)+(self.vel[1]**2)+(self.vel[2]**2))**0.5
                l*=0.5
                xm=cos(radians(self.rot[0]))
                zm=-sin(radians(self.rot[0]))
                self.vel[0]+=sin(radians(self.rot[1]))*xm*l
                self.vel[1]+=cos(radians(self.rot[1]))*xm*l
                self.vel[2]+=zm*l
                self.vel[2]+=options.get("player_jump_force", float)*0.75
                self.jump-=1
            else:
                self.vel[2]+=options.get("player_jump_force", float)

        if world != None:
            boxes=world.hit([-0.5+self.pos[0], -0.5+self.pos[1], self.pos[2]+self.vel[2]*d, 1, 1, 2.0])
            self.hit[2]=False
            hit=False
            jump=False
            for b in boxes:
                if self.vel[2] > 0:
                    if self.pos[2] > b[3]-2:
                        self.pos[2]=b[3]-2
                else:
                    if b[0] == "jumppad":
                        self.vel=[b[7], b[8], b[9]]
                        sound.play_sound("jumppad")
                        jump=True
                    else:
                        if self.pos[2] < b[3]+b[6]:
                            self.pos[2]=b[3]+b[6]
                        self.hit[2]=True
                hit=True

            if hit and not jump:
                self.vel[2]=0

            boxes=world.hit([-0.5+self.pos[0]+self.vel[0]*d, -0.5+self.pos[1], self.pos[2], 1, 1, 2.0])

            height=-float("inf")
            self.hit[0]=False
            for b in boxes:
                if self.vel[0] > 0:
                    if self.pos[0] > b[1]-0.5:
                        self.pos[0]=b[1]-0.5
                else:
                    if self.pos[0] < b[1]+b[4]+0.5:
                        self.pos[0]=b[1]+b[4]+0.5
                if height < b[3]+b[6]:
                    height=b[3]+b[6]
                self.hit[0]=True

            boxes=world.hit([-0.5+self.pos[0], -0.5+self.pos[1]+self.vel[1]*d, self.pos[2], 1, 1, 2.0])

            if height < self.pos[2]+self.step_height and height > self.pos[2]:
                self.pos[2]=height
                self.hit[0]=False
                if self.vel[2] < 0:
                    self.vel[2]=0

            height=0

            self.hit[1]=False
            for b in boxes:
                if self.vel[1] > 0:
                    if self.pos[1] > b[2]-0.5:
                        self.pos[1]=b[2]-0.5
                else:
                    if self.pos[1] < b[2]+b[5]+0.5:
                        self.pos[1]=b[2]+b[5]+0.5
                if height < b[3]+b[6]:
                    height=b[3]+b[6]
                self.hit[1]=True

            if height < self.pos[2]+self.step_height and height > self.pos[2]:
                self.pos[2]=height
                self.hit[1]=False
                if self.vel[2] < 0:
                    self.vel[2]=0

            if self.hit[0]:
                self.vel[0]=0

            if self.hit[1]:
                self.vel[1]=0

        self.height.update(d, self.pos[2])

        self.pos[0]+=self.vel[0]*d
        self.pos[1]+=self.vel[1]*d
        self.pos[2]+=self.vel[2]*d

        self.gun_rotation_speed.update(d, 0)

        if self.get_control("shoot"):
            self.gun_rotation_speed.value=720

        self.vel[0]*=crange(0, d, self.damping[int(self.hit[2])], 1, 0)
        self.vel[1]*=crange(0, d, self.damping[int(self.hit[2])], 1, 0)
        self.vel[2]*=crange(0, d, self.damping[0], 1, 0)

        self.gun_rot[0]-=crange(0, d, 0.1, 0, self.gun_rot[0]-self.rot[0])
        self.gun_spin+=d*self.gun_rotation_speed.value
        self.gun_rot[2]-=crange(0, d, 0.1, 0, self.gun_rot[2]-self.rot[1])

        sway_clamp=5

        self.gun_rot[0]=clamp(self.rot[0]-sway_clamp, self.gun_rot[0], self.rot[0]+sway_clamp)
        self.gun_rot[2]=clamp(self.rot[1]-sway_clamp, self.gun_rot[2], self.rot[1]+sway_clamp)

        self.gun_rot[0]-=self.recoil.value*4
        self.gun_rot[1]=self.recoil.value*8

        self.gun_offset[0]=0.21*(1-self.get_zoom())
        self.gun_offset[1]=0.2-(self.recoil.value*0.08)
        self.gun_offset[2]=-0.24-(self.recoil.value*0.12)

        rot=sin(self.time*10)

        if not self.hit[2]:
            walking=0

        if self.gun_mult < walking:
            self.gun_mult+=d*10
        elif self.gun_mult > walking:
            self.gun_mult-=d*10

        self.gun_mult=clamp(0, self.gun_mult, 1)

        if self.zoom < self.get_control("scope"):
            self.zoom+=d*5
        elif self.zoom > self.get_control("scope"):
            self.zoom-=d*5

        self.zoom=clamp(0, self.zoom, 1)

        self.gun_offset[0]-=self.gun_mult*(sin(rot)*0.02)
        self.gun_offset[2]-=self.gun_mult*((cos(rot)*0.02)-0.02)

        sway_clamp=0.1
        sway_mult=0.004

        self.gun_sway[0].update(d, clamp(-sway_clamp, -self.vel[0]*sway_mult, sway_clamp))
        self.gun_sway[1].update(d, clamp(-sway_clamp, -self.vel[1]*sway_mult, sway_clamp))
        self.gun_sway[2].update(d, clamp(-sway_clamp, -self.vel[2]*sway_mult, sway_clamp))
Beispiel #46
0
def display():
    global screen, doGameLoop, allPlaced
    global chooseAI, smart_AI

    length = 0
    dragging = ""  # the ship name that is currently being dragged
    dragRotate = False  # if the current ship has been rotated

    pygame.mixer.music.stop()

    while doGameLoop:
        event = pygame.event.poll()

        if event.type == pygame.QUIT:
            doGameLoop = False
            sys.exit(0)

        elif event.type == pygame.MOUSEBUTTONUP and dragging != "":
            pos = pygame.mouse.get_pos()
            rel_pos = relativeToSquare(pos)

            index = 3
            if dragRotate:
                index = 2

            height = (unplaced[dragging][index] // c.Drawing.SIZE) - 1

            ship_pos = (rel_pos[0] + height, rel_pos[1])
            if dragRotate:
                ship_pos = (rel_pos[0], rel_pos[1] + height)

            if client.placeShip(rel_pos, ship_pos):
                unplaced.pop(dragging)

            dragging = ""
            dragRotate = False

            # Check to see if the window needs to be resized
            checkUnplaced()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            buttons = pygame.mouse.get_pressed()
            isLeft = buttons[0]

            # pygame returns mouse coordinates relative to the top left of the window
            # Since we need to map that to the coordinate of a square, divide the mouse coordinates by the square dimensions
            screen_pos = pygame.mouse.get_pos()
            if screen_pos[0] < grid_size:
                if not allPlaced:
                    continue

                # The user clicked inside the placed ship grid
                rel_pos = relativeToSquare(screen_pos)

                if isLeft:
                    state = client.fire(rel_pos)

                    if state != -1:
                        opponent.update(rel_pos, state)

                    if state == c.Grid.SHIP_HIT:
                        sound.play_sound("hit")
                    elif state == c.Grid.MISSED:
                        sound.play_sound("miss")

                else:
                    warn(f"Unknown mouse button. State of buttons: {buttons}")
                    continue
            else:
                # The user clicked outside the grid and must be attempting to drag a ship
                ship = relativeToShip(screen_pos)
                if ship != "":
                    dragging = ship

        elif event.type == pygame.MOUSEMOTION:
            if dragging != "":
                pos = pygame.mouse.get_pos()
                unplaced[dragging][0] = pos[0] - (c.Drawing.SIZE / 2.5)
                unplaced[dragging][1] = pos[1] - (c.Drawing.SIZE / 2.5)

        elif event.type == pygame.KEYDOWN:
            pressed = pygame.key.get_pressed()

            # Rotate dragged ship
            if (pressed[pygame.K_r] or pressed[pygame.K_e]) and dragging != "":
                unplaced[dragging][2], unplaced[dragging][3] = unplaced[
                    dragging][3], unplaced[dragging][2]
                dragRotate = not dragRotate

            # Quit
            elif pressed[pygame.K_q]:
                doGameLoop = False

            # Use ships from template 1
            elif pressed[pygame.K_1] and len(unplaced) == 5:
                client.placeShip((0, 2), (0, 6))  # carrier
                client.placeShip((2, 4), (2, 7))  # battleship
                client.placeShip((2, 1), (4, 1))  # cruiser
                client.placeShip((4, 8), (6, 8))  # cruiser
                client.placeShip((7, 3), (7, 4))  # patrol boat
                unplaced.clear()

                checkUnplaced()

            # Use ships from template 2
            elif pressed[pygame.K_2] and len(unplaced) == 5:
                client.placeShip((5, 8), (9, 8))
                client.placeShip((6, 2), (8, 2))
                client.placeShip((5, 5), (8, 5))
                client.placeShip((6, 0), (7, 0))
                client.placeShip((3, 7), (3, 9))

                unplaced.clear()

                checkUnplaced()

        backgroundNew = pygame.transform.scale(background, WINDOW_SIZE)
        screen.blit(backgroundNew, (0, 0))

        appleSprite = pygame.transform.scale(apple,
                                             (c.Drawing.SIZE, c.Drawing.SIZE))
        orangeSprite = pygame.transform.scale(orange,
                                              (c.Drawing.SIZE, c.Drawing.SIZE))
        strawberrySprite = pygame.transform.scale(
            strawberry, (c.Drawing.SIZE, c.Drawing.SIZE))
        watermelonSprite = pygame.transform.scale(
            watermelon, (c.Drawing.SIZE, c.Drawing.SIZE))

        # If all ships have been placed, draw our ships in the upper left and the opponents grid in the main screen
        if allPlaced:
            if (chooseAI):
                if (smart_AI):
                    client.send("smart_ai")
                else:
                    client.send("dumb_ai")
                chooseAI = False
            drawGrid(opponent)
            drawGrid(grid, True)
        else:
            drawGrid(grid)

        # Draw the ships (if any) that still need to be dragged into the grid
        for key in unplaced:
            if key == "carrier":
                for i in range(5):
                    if dragRotate:
                        screen.blit(
                            watermelonSprite,
                            (int(unplaced["carrier"][0]) + i * c.Drawing.SIZE,
                             int(unplaced["carrier"][1])))
                    else:
                        screen.blit(
                            watermelonSprite,
                            (int(unplaced["carrier"][0]),
                             int(unplaced["carrier"][1]) + i * c.Drawing.SIZE))

            elif key == "battleship":
                for i in range(4):
                    if dragRotate:
                        screen.blit(appleSprite,
                                    (int(unplaced["battleship"][0]) +
                                     i * c.Drawing.SIZE,
                                     int(unplaced["battleship"][1])))
                    else:
                        screen.blit(appleSprite,
                                    (int(unplaced["battleship"][0]),
                                     int(unplaced["battleship"][1]) +
                                     i * c.Drawing.SIZE))

            elif key == "cruiser1":
                for i in range(3):
                    if dragRotate:
                        screen.blit(
                            orangeSprite,
                            (int(unplaced["cruiser1"][0]) + i * c.Drawing.SIZE,
                             int(unplaced["cruiser1"][1])))
                    else:
                        screen.blit(orangeSprite,
                                    (int(unplaced["cruiser1"][0]),
                                     int(unplaced["cruiser1"][1]) +
                                     i * c.Drawing.SIZE))

            elif key == "cruiser2":
                for i in range(3):
                    if dragRotate:
                        screen.blit(
                            orangeSprite,
                            (int(unplaced["cruiser2"][0]) + i * c.Drawing.SIZE,
                             int(unplaced["cruiser2"][1])))
                    else:
                        screen.blit(orangeSprite,
                                    (int(unplaced["cruiser2"][0]),
                                     int(unplaced["cruiser2"][1]) +
                                     i * c.Drawing.SIZE))

            elif key == "patrol":
                for i in range(2):
                    if dragRotate:
                        screen.blit(
                            strawberrySprite,
                            (int(unplaced["patrol"][0]) + i * c.Drawing.SIZE,
                             int(unplaced["patrol"][1])))
                    else:
                        screen.blit(
                            strawberrySprite,
                            (int(unplaced["patrol"][0]),
                             int(unplaced["patrol"][1]) + i * c.Drawing.SIZE))

        # Render ("flip") the display
        clock.tick(1000)

        pygame.display.flip()
    def run(self,nextlevel):
        WIDTH = 420
        HEIGHT = 440
        game_area = self.screen.subsurface(20, 20, WIDTH, HEIGHT)
        score_area = self.screen.subsurface(460, 20, 160, 60)
        pig_area = self.screen.subsurface(460, 90, 160, 370)
        if nextlevel == 1:
            while True:
                for e in pygame.event.get():
                    if e.type == QUIT:
                        return 'quit'
                    if e.type == MOUSEBUTTONUP:
                        if self.is_over(e.pos, (WIDTH/2-20, HEIGHT/2+60)) and e.button == 1:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game1'
                    if e.type == KEYUP:
                        if e.key == K_RETURN:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game1'

                self.screen.blit(self.background, (0,0))                       
                game_area.fill((0,0,0))
                score_area.fill((0,0,0))
                pig_area.fill((0,0,0))
                mouse_position = pygame.mouse.get_pos()
                myprint(game_area, u'Next Level: 1', (WIDTH/2-85, HEIGHT/2-70),size='enl')
                myprint(game_area, u'还是健身菜鸟的斜方怪', (WIDTH/2-83, HEIGHT/2-35))
                if self.is_over(mouse_position, (WIDTH/2-20, HEIGHT/2+60)):
                    pygame.draw.rect(game_area, (255,127,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                else:
                    pygame.draw.rect(game_area, (0,0,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                pygame.display.update()
        if nextlevel == 2:
            while True:
                for e in pygame.event.get():
                    if e.type == QUIT:
                        return 'quit'
                    if e.type == MOUSEBUTTONUP:
                        if self.is_over(e.pos, (WIDTH/2-20, HEIGHT/2+60)) and e.button == 1:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game2'
                    if e.type == KEYUP:
                        if e.key == K_RETURN:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game2'
                game_area.fill((0,0,0))
                mouse_position = pygame.mouse.get_pos()
                myprint(game_area, u'Next Level: 2', (WIDTH/2-85, HEIGHT/2-70),size='enl')
                myprint(game_area, u'斜方怪变得强大了', (WIDTH/2-70, HEIGHT/2-35))
                if self.is_over(mouse_position, (WIDTH/2-20, HEIGHT/2+60)):
                    pygame.draw.rect(game_area, (255,127,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                else:
                    pygame.draw.rect(game_area, (0,0,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                pygame.display.update()
        if nextlevel == 3:
            while True:
                for e in pygame.event.get():
                    if e.type == QUIT:
                        return 'quit'
                    if e.type == MOUSEBUTTONUP:
                        if self.is_over(e.pos, (WIDTH/2-20, HEIGHT/2+60)) and e.button == 1:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game3'
                    if e.type == KEYUP:
                        if e.key == K_RETURN:
                            play_sound('go')
                            pygame.mixer.music.play(-1)
                            return 'game3'
                game_area.fill((0,0,0))
                mouse_position = pygame.mouse.get_pos()
                myprint(game_area, u'Next Level: 3', (WIDTH/2-85, HEIGHT/2-70),size='enl')
                myprint(game_area, u'斜方怪大怒:噩梦来临', (WIDTH/2-85, HEIGHT/2-35))
                if self.is_over(mouse_position, (WIDTH/2-20, HEIGHT/2+60)):
                    pygame.draw.rect(game_area, (255,127,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                else:
                    pygame.draw.rect(game_area, (0,0,0), (WIDTH/2-40, HEIGHT/2+40, 80, 30))
                    pygame.draw.rect(game_area, (255,255,255), (WIDTH/2-40, HEIGHT/2+40, 80, 30), 2)
                    myprint(game_area, 'Go(Enter)', (WIDTH/2-19, HEIGHT/2+48), size='dk')
                pygame.display.update()
        if nextlevel == 4:
            pygame.mixer.music.stop()
            while True:
                for e in pygame.event.get():
                    if e.type == QUIT:
                        return 'quit'
                game_area.fill((0,0,0))
                mouse_position = pygame.mouse.get_pos()
                myprint(game_area, u'斜方怪练不出满意的斜方肌,抑郁而终', (WIDTH/2-155, HEIGHT/2-20))
                myprint(game_area, u'CONGRATULATIONS', (WIDTH/2-105, HEIGHT/2))
                pygame.display.update()
Beispiel #48
0
 def play_chime(self):
     sound.play_sound("../sfx/chime" + str(min(11, 1 + self.success_count)) + ".ogg")
Beispiel #49
0
    def run(self, info_mode):

        if info_mode==1:
            
            mypig = pig.Pig()
            star_pig = pig.Pig((140,220))
            clock = pygame.time.Clock()
            grey = (139, 129, 76)

            while True:
                
                for e in pygame.event.get():
                    if e.type == QUIT:
                        return 'quit'
                    if e.type == MOUSEBUTTONUP:
                        # print 'up'
                        if self.is_over(e.pos, (120,395)) and e.button == 1:
                            play_sound('menu')
                            self.show_star = not self.show_star
                        if self.is_over(e.pos, (550,395)) and e.button == 1:
                            play_sound('go')
                            return 'next1'
                        if self.is_over(e.pos, (40,395)) and e.button == 1:
                            play_sound('menu')
                            if self.show_info == 2:
                                self.show_info = 1
                            else:
                                self.show_info = 2
                        if self.is_over(e.pos, (180,399), 32) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 3     #左加20
                        if self.is_over(e.pos, (220,403), 26) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 4     #右加20
                        if self.is_over(e.pos, (250,403), 26) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 5     #左加10
                        if self.is_over(e.pos, (280,399), 32) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 6     #右加10
                        if self.is_over(e.pos, (320,400), 32) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 7     #表扬 speed*2
                        if self.is_over(e.pos, (360,403), 26) and e.button == 1:
                            play_sound('menu')
                            self.show_info = 8     #手汗
                            star_pig.sweat = True
                        
                        # if star
                        # show info = 3,4,5,6,7,


                past_second = clock.tick(30) / 1000.0
                mouse_position = pygame.mouse.get_pos()

                self.screen.blit(self.background, (0,0))
                


                pig_area = self.screen.subsurface(20, 20, 290, 340)
                pig_area.fill((0,0,0))

                if self.show_info == 2:
                    star_pig.shy = False
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 3:
                    star_pig.shy = False
                    if star_pig.dynamic_tra_start1[0] != 113:
                        star_pig.dynamic_tra_start1 = (133-20, 156)
                        star_pig.dynamic_tra_start2 = (147-20, 156)
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 4:
                    star_pig.shy = False
                    if star_pig.dynamic_tra_start1[0] != 153:
                        star_pig.dynamic_tra_start1 = (133+20, 156)
                        star_pig.dynamic_tra_start2 = (147+20, 156)
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 5:
                    star_pig.shy = False
                    if star_pig.dynamic_tra_start1[0] != 123:
                        star_pig.dynamic_tra_start1 = (133-10, 156)
                        star_pig.dynamic_tra_start2 = (147-10, 156)
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 6:
                    star_pig.shy = False
                    if star_pig.dynamic_tra_start1[0] != 143:
                        star_pig.dynamic_tra_start1 = (133+10, 156)
                        star_pig.dynamic_tra_start2 = (147+10, 156)
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 7:
                    star_pig.shy = True
                    star_pig.draw_dynamic_pig(pig_area, (140,220), past_second, hand_speed = 1000., neck_speed = 60.)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                elif self.show_info == 8:
                    star_pig.shy = False
                    if star_pig.dynamic_tra_start1[1] < 100:
                        star_pig.sweat = True
                        halfneck = 182-(156-star_pig.dynamic_tra_start1[1]+26)/2
                        star_pig.dynamic_tra_start1 = (133, halfneck)
                        star_pig.dynamic_tra_start2 = (147, halfneck)
                    if star_pig.sweat:
                        star_pig.draw_dynamic_pig(pig_area, (140,220), 0.)
                    else:
                        star_pig.draw_dynamic_pig(pig_area, (140,220), past_second)
                    if star_pig.info_area_restart:
                        star_pig.dynamic_tra_start1 = (133, 156)
                        star_pig.dynamic_tra_start2 = (147, 156)
                        star_pig.info_area_restart = False
                else:
                    mypig.drawpig(pig_area, (140,220), past_second)
                    self.draw_arrow(pig_area, (190,205), (220,220))
                    myprint(pig_area, u'左手举不动了', (200,225), size='c1ss')
                    myprint(pig_area, u'斜方怪还在坚持!', (190,240), size='c1ss')
                    self.draw_arrow(pig_area, (170,165), (202,150))
                    myprint(pig_area, u'斜方怪拥有', (202,130), size='c1ss')
                    myprint(pig_area, u'傲人的斜方肌', (208,145), size='c1ss')
                    self.draw_arrow(pig_area, (110,215), (80, 220))
                    myprint(pig_area, u'只用粉色肚兜', (10,225), size='c1ss')
                    myprint(pig_area, u'是他的原则', (15,240), size='c1ss')




                info_area = self.screen.subsurface(330, 20, 290, 340)
                info_area.fill((0,0,0))              
                if self.show_info == 1:
                    myprint(info_area, u'“一二一二,唔噢噢哦~~”', (10, 10), color=(255,127,0))
                    myprint(info_area, u'!!这里原本是猪哥的房间...', (10, 40))
                    myprint(info_area, u'...怎么变成了一头怪兽!等等,最', (10, 60))
                    myprint(info_area, u'近猪哥整天举哑铃,难,难道说!', (10, 80))
                    myprint(info_area, u'“唔噢噢哦~愚蠢的人类。我是沉', (10, 110), color=(255,127,0))
                    myprint(info_area, u'睡了很久的斜方怪。这个人对于斜', (10, 130), color=(255,127,0))
                    myprint(info_area, u'方肌的执着唤醒了我。他的意识已', (10, 150), color=(255,127,0))
                    myprint(info_area, u'经被我吞噬。从此这副身体由我来', (10, 170), color=(255,127,0))
                    myprint(info_area, u'控制。我会锻炼出更强壮的斜方肌', (10, 190), color=(255,127,0))
                    myprint(info_area, u'不久的将来,地球将会被我们斜方', (10, 210), color=(255,127,0))
                    myprint(info_area, u'星彻底占领!唔噢噢哦~~', (10, 230), color=(255,127,0))
                    myprint(info_area, u'要抓紧练起来了!一二一二......”', (10, 250), color=(255,127,0))
                    myprint(info_area, u'...我是认真想的设定。总之猪哥,', (10, 280))
                    myprint(info_area, u'我不会让你白白牺牲的。地球就', (10, 300))
                    myprint(info_area, u'交给我来保护吧!', (10, 320))
                elif self.show_info == 2:
                    myprint(info_area, u'随着时间,斜方肌会越来越长。', (10, 40))
                    myprint(info_area, u'你要躲避斜方怪的哑铃攻击,同时', (10, 60))
                    myprint(info_area, u'不断寻找星星,防止斜方怪锻炼出', (10, 80))
                    myprint(info_area, u'自豪的斜方肌。', (10, 100))
                    myprint(info_area, u'移动:上下左右', (10, 130), color=(255,127,0))
                    myprint(info_area, u'暂停:空格', (10, 150),color=(255,127,0))
                    myprint(info_area, u'星星对斜方肌的影响:', (10, 180))
                    myprint(info_area, u'向左长', (10, 200))
                    self.drawitem(info_area, 'star1.png', (100,201), angle=-1, s=True)
                    self.drawitem(info_area, 'star3.png', (120,201), angle=-1, s=True)
                    myprint(info_area, u'向右长', (10, 220))
                    self.drawitem(info_area, 'star2.png', (100,221), angle=-1, s=True)
                    self.drawitem(info_area, 'star4.png', (120,221), angle=-1, s=True)
                    myprint(info_area, u'加速长', (10, 240))
                    self.drawitem(info_area, 'star5.png', (100,241), angle=-1, s=True)
                    myprint(info_area, u'降低一半', (10, 260))
                    self.drawitem(info_area, 'star6.png', (100,261), angle=-1, s=True)
                    myprint(info_area, u'点击下方星星图标查看具体效果。', (10, 290))
                elif self.show_info == 3:
                    myprint(info_area, u'“斜方怪,右边的斜方肌还不行”', (10, 40))
                    myprint(info_area, u'“soga”', (10, 70), color=(255,127,0))
                    myprint(info_area, u'黄色星星效果:', (10, 120))
                    myprint(info_area, u'使右边一边的斜方肌大涨', (10, 140))
                    myprint(info_area, u'一旦一边的斜方肌大出另一边很多,', (10, 180))
                    myprint(info_area, u'斜方肌失去平衡回归原点,', (10, 200))
                    myprint(info_area, u'斜方怪就得重新练起拉。', (10, 220))
                elif self.show_info == 4:
                    myprint(info_area, u'“斜方怪,左边的斜方肌搞起”', (10, 40))
                    myprint(info_area, u'“专攻左边!”', (10, 70), color=(255,127,0))
                    myprint(info_area, u'灰色星星效果:', (10, 120))
                    myprint(info_area, u'使左边一边的斜方肌大涨', (10, 140))
                elif self.show_info == 5:
                    myprint(info_area, u'“右边还差一点点哦”', (10, 40))
                    myprint(info_area, u'“没问题!一二一二...”', (10, 70), color=(255,127,0))
                    myprint(info_area, u'绿色星星效果:', (10, 120))
                    myprint(info_area, u'使右边一边的斜方肌小涨', (10, 140))
                elif self.show_info == 6:
                    myprint(info_area, u'“太帅了斜方怪!左边再一点点...”', (10, 40))
                    myprint(info_area, u'“ok”', (10, 70), color=(255,127,0))
                    myprint(info_area, u'冰冻星星效果:', (10, 120))
                    myprint(info_area, u'使左边一边的斜方肌小涨', (10, 140))
                elif self.show_info == 7:
                    myprint(info_area, u'“斜方肌已经完美了”', (10, 40))
                    myprint(info_area, u'“还,还好。谢谢。”', (10, 70), color=(255,127,0))
                    myprint(info_area, u'没想到斜方怪竟然害羞了,反而练', (10, 100))
                    myprint(info_area, u'得更快了', (10, 120))
                    myprint(info_area, u'象棋星星效果:', (10, 160))
                    myprint(info_area, u'使斜方肌增长速度加倍,', (10, 180))
                    myprint(info_area, u'持续时间到下一个星星', (10, 200))
                elif self.show_info == 8:
                    myprint(info_area, u'“啊啊啊手汗手汗,都是手汗。”', (10, 40), color=(255,127,0))
                    myprint(info_area, u'火焰星星效果:', (10, 80))
                    myprint(info_area, u'斜方怪手汗太多抓不住哑铃。', (10, 100))
                    myprint(info_area, u'回到一半的斜方肌长度,斜方怪在', (10, 120))
                    myprint(info_area, u'原地不动等汗干。', (10, 140))







                item_area = self.screen.subsurface(20, 380, 600, 70)
                item_area.fill((0,0,0))
                if self.is_over(mouse_position, (40,395)):
                    self.drawitem(item_area, 'home2.png', (20,15))
                else:
                    self.drawitem(item_area, 'home.png', (20,15))
                myprint(item_area, u'操作介绍', (19, 5), size='c1ss')
                if self.is_over(mouse_position, (120,395)):
                    item_area.fill(grey, (100,17,48,45))

                self.drawitem(item_area, 'box48.png', (100,15))
                myprint(item_area, u'道具介绍', (99, 4), size='c1ss')

                if self.show_star:
                    speed = 600.
                    self.angle += past_second * speed
                    self.try_draw_star('star1.png', mouse_position, (180,399), 32, self.angle, item_area)
                    self.try_draw_star('star2.png', mouse_position, (220,403), 26, self.angle, item_area)
                    self.try_draw_star('star3.png', mouse_position, (250,403), 26, self.angle, item_area)
                    self.try_draw_star('star4.png', mouse_position, (280,399), 32, self.angle, item_area)
                    self.try_draw_star('star5.png', mouse_position, (320,400), 32, self.angle, item_area)
                    self.try_draw_star('star6.png', mouse_position, (360,403), 26, self.angle, item_area)
                    #self.try_draw_star('star7.png', mouse_position, (390,400), 32, self.angle, item_area)
                else:
                    myprint(item_area, 'click to open', (200, 50), size='dk')
                    self.draw_arrow(item_area, (154, 45), (195, 55))

                if self.is_over(mouse_position, (550,395)):
                    self.drawitem(item_area, 'play2.png', (530,15))
                else:
                    self.drawitem(item_area, 'play.png', (538,23))
                myprint(item_area, u'准备好了', (529, 4), size='c1ss')



                pygame.display.update()
Beispiel #50
0
  def run(self, menu_choice = 0):
    done = False

    clock = pygame.time.Clock()

    self.screen.blit(self.bgscreen, (0, 0))      #Renders the menu background, usually the faded out game display
                                                 #Or a black screen
    #Menu loop

    while not done:

      # Pygame event and keyboard input processing
      for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
          menu_choice = MENU_QUIT
          done = True
        elif (event.type == KEYDOWN and event.key == K_DOWN) or (event.type == JOYAXISMOTION and event.axis == 1 and event.value > 0.7):
          if menu_choice + 1 < len(self.menu_items):
            menu_choice += 1
            play_sound("click")
        elif (event.type == KEYDOWN and event.key == K_UP) or (event.type == JOYAXISMOTION and event.axis == 1 and event.value < -0.7):
          if menu_choice > 0:
            menu_choice -= 1
            play_sound("click")
        elif (event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN)) or (event.type == JOYBUTTONDOWN and (event.button == 0 or event.button == 1)):
          done = True

      #Menu rendering

      #Menu offset value centers the menu when the maximum amount of choices is not visible

      if len(self.menu_items) < MENU_MAX_VISIBLE:
        menu_offset = -(len(self.menu_items) - 5) * 10
      else:
        menu_offset = -(MENU_MAX_VISIBLE - 5) * 10

      menu_bg = pygame.image.load(data.picpath("menu", "bg")).convert_alpha()
      rect = menu_bg.get_rect()
      rect.centerx = SCREEN_WIDTH / 2
      rect.top = GUI_MENU_TOP
      self.screen.blit(menu_bg, rect)

      if self.heading_text != None:
        menu_head = render_text(self.heading_text)
        rect = menu_head.get_rect()
        rect.centerx = SCREEN_WIDTH / 2
        rect.top = GUI_MENU_TOP + 50 + menu_offset
        self.screen.blit(menu_head, rect)

      #If the menu choice is greater than the second last menu item on screen,
      #the menu must be scrolled:
      if menu_choice > (MENU_MAX_VISIBLE - 1):
        current_menu_index = menu_choice - MENU_MAX_VISIBLE
        if (menu_choice + 1) < len(self.menu_items):
          current_menu_index += 1
      else:
        current_menu_index = 0

      menu_visible = 0

      while (not (menu_visible > MENU_MAX_VISIBLE or (current_menu_index) == len(self.menu_items))):
        m = self.menu_items[current_menu_index]
        if (menu_choice == current_menu_index):
          menu_image = render_text(m, COLOR_GUI_HILIGHT, COLOR_GUI_DARK)
        else:
          menu_image = render_text(m, COLOR_GUI)
        rect = menu_image.get_rect()
        rect.centerx = SCREEN_WIDTH / 2
        rect.top = GUI_MENU_TOP + 60 + (menu_visible + 1) * 20 + menu_offset
        self.screen.blit(menu_image, rect)
        current_menu_index += 1
        menu_visible += 1

      #Display, clock

      pygame.display.flip()

      clock.tick(FPS)

    return menu_choice
Beispiel #51
0
  def run(self, menu_choice = 0):
    done = False

    clock = pygame.time.Clock()

    menu_items = ["Quit", "Sound: " + bool_to_str(Variables.vdict["sound"]), "Dialogue: " + bool_to_str(Variables.vdict["dialogue"]) ]

    count = 0

    while (count <= Variables.vdict["unlocked"] and count < TOTAL_LEVELS):
      menu_items.append("Level " + str(count + 1))
      count += 1
      
    if self.score != None:
      menu_image = render_text("Your final score: " + str(self.score), COLOR_GUI)
      rect = menu_image.get_rect()
      rect.centerx = SCREEN_WIDTH / 2
      rect.top = GUI_MENU_TOP - 25
      self.screen.blit(menu_image, rect)

    while not done:

      # Pygame event and keyboard input processing
      for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
          menu_choice = MENU_QUIT
          done = True
        elif (event.type == KEYDOWN and event.key == K_DOWN) or (event.type == JOYAXISMOTION and event.axis == 1 and event.value > 0.7):
          if menu_choice + 4 < len(menu_items):
            menu_choice += 1
            play_sound("click")
        elif (event.type == KEYDOWN and event.key == K_UP) or (event.type == JOYAXISMOTION and event.axis == 1 and event.value < -0.7):
          if menu_choice + 3 > 0:
            menu_choice -= 1
            play_sound("click")
        elif (event.type == KEYDOWN and (event.key == K_z or event.key == K_SPACE or event.key == K_RETURN)) or (event.type == JOYBUTTONDOWN and (event.button == 0 or event.button == 1)):
          done = True

      #Menu rendering
      
      menu_offset =  -(len(menu_items) - 6) * 10

      menu_bg = pygame.image.load(data.picpath("menu", "bg")).convert_alpha()
      rect = menu_bg.get_rect()
      rect.centerx = SCREEN_WIDTH / 2
      rect.top = GUI_MENU_TOP
      self.screen.blit(menu_bg, rect)

      menu_head = render_text("Which way is up?")
      rect = menu_head.get_rect()
      rect.centerx = SCREEN_WIDTH / 2
      rect.top = GUI_MENU_TOP + 50 + menu_offset
      self.screen.blit(menu_head, rect)

      current_menu_index = -3

      for m in menu_items:
        if (menu_choice == current_menu_index):
          color = COLOR_GUI_HILIGHT
        else:
          color = COLOR_GUI
        menu_image = render_text(m, color)
        rect = menu_image.get_rect()
        rect.centerx = SCREEN_WIDTH / 2
        rect.top = GUI_MENU_TOP + 60 + (current_menu_index + 4) * 20 + menu_offset
        self.screen.blit(menu_image, rect)
        current_menu_index += 1

      #Display, clock

      pygame.display.flip()

      clock.tick(FPS)

    return menu_choice
Beispiel #52
0
def run(screen, level_number = 0, score = None, joystick = None):
  done = False
  objects = []
  particles = []

  if score == None:
    score = Score(0)

  level = Level(screen, str(level_number))

  objects = level.get_objects()
  player = level.get_player()
  objects.append(player)

  player.life = score.life

  clock = pygame.time.Clock()

  end_trigger = END_NONE
  scripted_event_on = False

  #There's no music at the moment:
  #pygame.mixer.music.load( data.filepath(os.path.join("music", "music.ogg")) )
  #pygame.mixer.music.play(-1)

  scripted_events = level.get_scripted_events()
  current_scripted_event = None

  scripted_event_trigger = TRIGGER_LEVEL_BEGIN

  '''  for ev in scripted_events:
    if ev.trigger_type == "level_begin":
      scripted_event_on = True
      current_scripted_event = ev
      current_scripted_event_element = None

  text = None
  phase = 0
  cleared = False        # Clearing dialog boxes'''

  flip_wait = -1

  pygame.mixer.init()

  keys_released = {}

  keys_released["K_z"] = True
  keys_released["K_DOWN"] = True
  keys_released["K_UP"] = True
  keys_released["J_B0"] = True
  keys_released["J_B1"] = True

  while (end_trigger == END_NONE):

    # Pygame event and keyboard input processing
    for event in pygame.event.get():
      if event.type == QUIT:
        end_trigger = END_HARD_QUIT
      if (event.type == KEYDOWN and event.key == K_ESCAPE):
        end_trigger = END_QUIT

    keys = pygame.key.get_pressed()
    inputs = [False, False, False, False, False, False, 0.0]

    trigger = TRIGGER_NONE

    if keys[K_LEFT]:
      inputs[LEFT] = True

    if keys[K_RIGHT]:
      inputs[RIGHT] = True

    if keys[K_DOWN]:
      if keys_released["K_DOWN"]:
        inputs[DOWN] = True
      keys_released["K_DOWN"] = False
    else:
      keys_released["K_DOWN"] = True

    if keys[K_z]:
      inputs[UP] = True
      if keys_released["K_z"]:
        inputs[JUMP] = True
      keys_released["K_z"] = False
    else:
      keys_released["K_z"] = True

    if keys[K_UP]:
      inputs[UP] = True
      if keys_released["K_UP"]:
        inputs[JUMP] = True
      keys_released["K_UP"] = False
    else:
      keys_released["K_UP"] = True

    if keys[K_F10]:
      inputs[SPECIAL] = True

    if joystick != None:   # Parse joystick input
      
      axis0 = joystick.get_axis(0)

      if axis0 < -0.1:
        inputs[LEFT] = True
        inputs[ANALOG] = -axis0

      if axis0 > 0.1:
        inputs[RIGHT] = True
        inputs[ANALOG] = axis0

      if joystick.get_button(0):
        inputs[UP] = True
        if keys_released["J_B0"]:
          inputs[JUMP] = True
        keys_released["J_B0"] = False
      else:
        keys_released["J_B0"] = True

      if joystick.get_button(1):
        if keys_released["J_B1"]:
          inputs[DOWN] = True
        keys_released["J_B1"] = False
      else:
        keys_released["J_B1"] = True


    if scripted_event_on:
      if inputs[JUMP] or inputs[DOWN]:
        cleared = True

    moved = False

    analog_multiplier = 1

    if not scripted_event_on and not level.flipping:
      if inputs[LEFT]:
        player.move((-PLAYER_MAX_ACC, 0))
        moved = True

      if inputs[RIGHT]:
        player.move((PLAYER_MAX_ACC, 0))
        moved = True

      if inputs[JUMP]:
        if (player.on_ground):
          count = 0
          while (count < 5):
            count += 1
            particles.append(Particle(screen, 10, player.rect.centerx - player.dx / 4 + random.uniform(-3, 3), player.rect.bottom, -player.dx * 0.1, -0.5, 0.3, COLOR_DUST, 4))
          player.jump()

      if inputs[UP] and not player.on_ground:
        player.jump()

      if inputs[DOWN]:
        pick_up_item = level.pick_up(player.x, player.y)
        if pick_up_item != None:
          play_sound("coins")
          player.inventory.append(pick_up_item)
          scripted_event_trigger = pick_up_item.itemclass

        trigger = level.trigger(player.x, player.y)

      if inputs[SPECIAL]:
        trigger = TRIGGER_FLIP

    if not moved or (player.current_animation == "dying" and player.on_ground):
      player.dec((PLAYER_MAX_ACC, 0))

    if trigger == TRIGGER_FLIP:
      if flip_wait == -1:
        flip_wait = 0
        play_sound("woosh")

    if flip_wait != -1:
      flip_wait += 1
      if flip_wait > FLIP_DELAY:
        flip_wait = -1
        level.flip()
        for o in objects:
          o.flip()
        for p in particles:
          p.flip()

    #Rendering and updating objects:

    if scripted_event_trigger == TRIGGER_NONE:
      scripted_event_trigger = level.update()
    else:
      level.update()
    level.render()

    if not scripted_event_on:
      for o in objects:
        if o.dead and o.itemclass != "player":
          objects.remove(o)
          continue
        new_particles = o.update(level)
        if o.itemclass == "projectile":
          if player.rect.collidepoint(o.x, o.y) and o.current_animation == "default":
            new_particles = player.take_damage(o.damage)
            o.die()
        if new_particles != None:
          for p in new_particles:
            particles.append(p)

    for o in objects:
      o.render()

    for p in particles:
      p.update()
      p.render()
      if p.dead:
        particles.remove(p)

    #Dust effect:

    if (player.current_animation == "walking"):
      particles.append(Particle(screen, 10, player.rect.centerx - player.dx / 2 + random.uniform(-2, 2), player.rect.bottom, -player.dx * 0.1, 0.1, 0.3))

    #Rendering GUI on top of everything else:

    render_gui(screen, player.life, score.score, (5, 5))

    # Scripted event triggering:

    if scripted_event_trigger != TRIGGER_NONE:
      if player.on_ground:
        for ev in scripted_events:
          if ev.trigger_type == scripted_event_trigger:
            scripted_event_on = True
            current_scripted_event = ev
            current_scripted_event_element = None
            text = None
            phase = 0
            cleared = False        # Clearing dialog boxes
            player.dy = 0
            player.dx = 0
            player.update()
            scripted_event_trigger = TRIGGER_NONE

    # Scripted event processing:

    if scripted_event_on:
      if (current_scripted_event_element == None) or (current_scripted_event_element.finished):

        current_scripted_event_element = current_scripted_event.next_element()

        if current_scripted_event_element.event_type == "end":
          scripted_event_on = False
          current_scripted_event_element = None

      else:

        if not Variables.vdict["dialogue"]:  #Dialogue skipping
          while (current_scripted_event_element.event_type == "dialogue" or current_scripted_event_element.event_type == "player"):
            current_scripted_event_element.finished = True
            current_scripted_event_element = current_scripted_event.next_element()
            if current_scripted_event_element.event_type == "end":
              current_scripted_event_element.finished = True

        if current_scripted_event_element.event_type == "wait":
          current_scripted_event_element.finished = True

        if current_scripted_event_element.event_type == "dialogue":
          if text == None:
            text = current_scripted_event_element.text
            phase = 0
          phase = render_text_dialogue(screen, text, phase)
          if (phase == -1) and cleared:
            current_scripted_event_element.finished = True
            phase = 0
            cleared = False
            text = None
          if cleared:
            phase = -1
            cleared = False

        if current_scripted_event_element.event_type == "player":
          if current_scripted_event_element.text == "orientation":
            player.orientation = current_scripted_event_element.orientation
          current_scripted_event_element.finished = True

        if current_scripted_event_element.event_type == "change_level":
          end_trigger = END_NEXT_LEVEL
          score.score += (level_number + 1) * 11 * player.life
          current_scripted_event_element.finished = True

    if player.dead:
      end_trigger = END_LOSE

    #Display, clock

    pygame.display.flip()

    clock.tick(FPS)

  score.life = player.life #To make the player's health stay the same to the next level

  return end_trigger
def run(screen, level_name = "w0-l0", score_mod = 0, score = None, joystick = None):

  if (Variables.vdict["devmode"]):
    edit_utils = Edit_utils()

  done = False
  objects = []
  particles = []

  if score == None:
    score = Score(0)

  #try:
  level = Level(screen, level_name)
  #except:
  #  error_message("Couldn't open level '" + level_name + "'")
  #  return END_QUIT

  objects = level.get_objects()
  player = level.get_player()
  objects.append(player)

  player.life = score.life

  clock = pygame.time.Clock()

  end_trigger = END_NONE
  scripted_event_on = False

  #There's no music at the moment:
  #pygame.mixer.music.load( data.filepath(os.path.join("music", "music.ogg")) )
  #pygame.mixer.music.play(-1)

  scripted_events = level.get_scripted_events()
  current_scripted_event = None

  scripted_event_trigger = TRIGGER_LEVEL_BEGIN

  flip_wait = -1

  keys_released["K_z"] = True
  keys_released["K_p"] = True
  keys_released["K_s"] = True
  keys_released["K_DOWN"] = True
  keys_released["K_LEFT"] = True
  keys_released["K_RIGHT"] = True
  keys_released["K_UP"] = True
  keys_released["J_B0"] = True
  keys_released["J_B1"] = True

  fading = True
  fade_target = FADE_STATE_NONE
  Util.fade_state = FADE_STATE_BLACK

  flip_trigger_position = (0, 0)

  changing_level = False

  paused = False

  #Main game loop

  while (end_trigger == END_NONE or fading):

    # Pygame event and keyboard input processing
    for event in pygame.event.get():
      if event.type == QUIT:
        end_trigger = END_HARD_QUIT
      if (event.type == KEYDOWN and event.key == K_ESCAPE):
        end_trigger = END_QUIT
        if fading == False:
          fading = True
        fade_target = FADE_STATE_HALF

    inputs = parse_inputs(joystick)

    trigger = None

    if scripted_event_on:
      if inputs.has_key("JUMP") or inputs.has_key("DOWN"):
        cleared = True

    moved = False

    add_time = False #The ingame time counter toggle - this is False when the player can't control the character

    if not scripted_event_on and not level.flipping and not fading and not paused \
    and player.current_animation != "dying" and player.current_animation != "exit":
      #There isn't anything special going on: player can control the character
      #Translates input to commands to the player object
      add_time = True
      if inputs.has_key("LEFT"):
        player.move((-PLAYER_MAX_ACC, 0))
        moved = True

      if inputs.has_key("RIGHT"):
        player.move((PLAYER_MAX_ACC, 0))
        moved = True

      if inputs.has_key("JUMP"):
        if (player.on_ground):
          count = 0
          while (count < 5):
            count += 1
            particles.append(Particle(screen, 10, player.rect.centerx - player.dx / 4 + random.uniform(-3, 3), player.rect.bottom, -player.dx * 0.1, -0.5, 0.3, level.dust_color, 4))
          player.jump()

          #The blobs always try to jump when the player jumps

          for o in objects:
            if o.itemclass == "blob":
              o.jump()

      if inputs.has_key("UP") and not player.on_ground:
        player.jump()

      if inputs.has_key("DOWN"):
        pick_up_item = level.pick_up(player.x, player.y)
        if pick_up_item != None:
          play_sound("coins")
          player.inventory.append(pick_up_item)
          scripted_event_trigger = pick_up_item.itemclass

        #If the level is not flipping at the moment, the player can trigger stuff in the level
        if flip_wait == -1:
          trigger = level.trigger(player.x, player.y)

      #Debug command for flipping:
      if inputs.has_key("SPECIAL"):
        trigger = Trigger(TRIGGER_FLIP, player.x, player.y)

    if inputs.has_key("PAUSE") and player.current_animation != "dying":
      paused = not paused

    #Decelerates the player, if he doesn't press any movement keys or when he is dead and on the ground
    if ((player.current_animation != "dying" and not moved) or (player.current_animation == "dying" and player.on_ground)) and not paused:
      player.dec((PLAYER_MAX_ACC, 0))

    if trigger != None and trigger.trigger_type == TRIGGER_FLIP:
      if flip_wait == -1:
        flip_wait = 0
        flip_trigger_position = (trigger.x, trigger.y)
        play_sound("woosh")

    if flip_wait != -1 and not paused:
      flip_wait += 1
      if flip_wait > FLIP_DELAY:
        flip_direction = flip_direction_from_position(flip_trigger_position)
        flip_wait = -1
        level.flip(flip_direction)
        for o in objects:
          o.flip(flip_direction)
        for p in particles:
          p.flip()

    #Dust effect rising from the character's feet:

    if (player.current_animation == "walking"):
      particles.append(Particle(screen, 10, player.rect.centerx - player.dx / 2 + random.uniform(-2, 2), player.rect.bottom, -player.dx * 0.1, 0.1, 0.3, level.dust_color))

    #Updating level and objects:

    if scripted_event_trigger == None:
      scripted_event_trigger = level.update()
    else:
      level.update()

    #Objects are only updated when there's not a scripted event going on

    normal_updating = not scripted_event_on and not fading and not paused

    if changing_level:
      player.update(level)
    elif normal_updating:
      for o in objects:
        if o.dead and o.itemclass != "player":
          objects.remove(o)
          continue
        new_particles = o.update(level)
        if o.itemclass == "projectile":
          if player.rect.collidepoint(o.x, o.y) and o.current_animation == "default":
            new_particles = player.take_damage(o.damage)
            o.die()
        if type(new_particles) == list: #Sometimes the type of the return value is int (hackity hack)
          if new_particles != None:
            for p in new_particles:
              particles.append(p)

    if normal_updating or changing_level:
      for p in particles:
        p.update()
        if p.dead:
          particles.remove(p)

    #Rendering level - background and tiles
    level.render()

    #Rendering objects and particles
    for o in objects:
      if o.itemclass == "player":
        o.render(None, None, (fading or paused) )
      else:
        o.render(None, None, (scripted_event_on or fading or paused) )
      #On special conditions the animations aren't updated. The player is updated on a scripted event, others are not.

    for p in particles:
      p.render()

    #Rendering GUI on top of game graphics:
    if (not paused) or (not Variables.vdict["devmode"]):
      render_gui(screen, player.life, score.score, (5, 5))

    # Scripted event triggering:

    if scripted_event_trigger != None:
      if player.on_ground:
        for ev in scripted_events:
          if ev.trigger_type == scripted_event_trigger:
            scripted_event_on = True
            current_scripted_event = ev
            current_scripted_event_element = None
            text = None
            phase = 0
            cleared = False        # Clearing dialog boxes
            player.dy = 0
            player.dx = 0
            player.update()
            scripted_event_trigger = None

    # Scripted event processing:

    if scripted_event_on and not fading and not paused:
      if (current_scripted_event_element == None) or (current_scripted_event_element.finished):

        current_scripted_event_element = current_scripted_event.next_element()

        if current_scripted_event_element.event_type == "end":
          scripted_event_on = False
          current_scripted_event_element = None

      else:

        if not Variables.vdict["dialogue"]:  #Dialogue skipping
          while (current_scripted_event_element.event_type == "dialogue" or current_scripted_event_element.event_type == "player"):
            current_scripted_event_element.finished = True
            current_scripted_event_element = current_scripted_event.next_element()
            if current_scripted_event_element.event_type == "end":
              current_scripted_event_element.finished = True

        if current_scripted_event_element.event_type == "wait":
          current_scripted_event_element.finished = True
        elif current_scripted_event_element.event_type == "dialogue":
          if text == None:
            text = current_scripted_event_element.text
            phase = 0
          phase = render_text_dialogue(screen, text, phase)
          if (phase == -1) and cleared:
            current_scripted_event_element.finished = True
            phase = 0
            cleared = False
            text = None
          if cleared:
            phase = -1
            cleared = False
        elif current_scripted_event_element.event_type == "player":
          if current_scripted_event_element.text == "orientation":
            player.orientation = current_scripted_event_element.orientation
          current_scripted_event_element.finished = True
        elif current_scripted_event_element.event_type == "change_level":
          score.score += (5 + score_mod) * ((player.life + 4) / 5 + 12)
          score.levels += 1
          current_scripted_event_element.finished = True
          if player.current_animation != "gone":
            player.exit()

    if player.current_animation == "exit":
      changing_level = True
    elif changing_level:
      end_trigger = END_NEXT_LEVEL
      fading = True
      fade_target = FADE_STATE_BLACK


    if player.dead:
      end_trigger = END_LOSE
      fading = True
      fade_target = FADE_STATE_HALF

    #And finally, rendering the pause button:

    if paused:
      if (Variables.vdict["devmode"]):
        change = edit_utils.update(inputs)
        level.change(change)
        edit_utils.render(screen)
      else:
        render_text_dialogue(screen, "Game paused. Press P to continue.", -1, "p")

    #Render fading on top of everything else:

    if (fading or Util.fade_state != FADE_STATE_NONE):
      if fade_to_black(screen, fade_target):
        #Fading finished
        fading = False

    if(add_time):
      score.time += 1

    #Display, clock

    pygame.display.flip()

    clock.tick(FPS)

  #Main game loop finished

  score.life = player.life #To make the player's health stay the same to the next level

  return end_trigger