Esempio n. 1
0
    def _on_alien_killed(self, alien):
        self.stats.increase_score(alien.alien_stats.points)
        self.scoreboard.set_dirty()

        # update music
        next_music = self.bg_music
        num_variations = len(sounds.bg_music_names)

        # 0 - 0.33 -> 2
        # 0.33 -> 0.66 -> 1
        # 0.66 -> 1 = 0

        for i in range(num_variations):
            # 2 1 0
            if self.fleet.alive_ratio < 1. / (i + 1):
                next_music = sounds.bg_music_names[i]

        if next_music != self.bg_music:
            # change music track
            sounds.play_music(next_music)
            self.bg_music = next_music

            if self.fleet.alive_ratio < 0.33:
                pygame.mixer_music.set_volume(
                    1.0)  # play music loudly for almost-dead fleet
def show_credits():
    print('-' * save_load.divider_size)

    try:
        sounds.play_music('../Music/Credits Music for an 8-bit RPG.ogg')

        # Display the credits one line at a time with specific lengths
        # of time in between each line. Syncs up with the music!
        with open('../Credits.txt') as f:
            for number, line in enumerate(f):
                print(''.join(line.split("\n")))
                main.smart_sleep([0.75])

            main.smart_sleep(3)

            sounds.play_music('../Music/Title Screen.flac')

    except FileNotFoundError:
        # Display this is the Credits.txt file couldn't be found
        logging.exception(
            f'Error finding credits.txt on {time.strftime("%m/%d/%Y at %H:%M:%S")}:'
        )
        print('The "credits.txt" file could not be found.')
        main.s_input("\nPress enter/return ")

    except OSError:
        # If there is a problem opening the Credits.txt file, but it does exist,
        # display this message and log the error
        logging.exception(
            f'Error loading credits.txt on {time.strftime("%m/%d/%Y at %H:%M:%S")}:'
        )
        print('There was a problem opening "credits.txt".')
        main.s_input("\nPress enter/return ")
def show_history():
    # Display side-story lore and the history of Pythonia
    print('-' * save_load.divider_size)
    main.s_input('Press enter/return after each line to advance the text ')
    print('-' * save_load.divider_size)

    try:
        sounds.play_music('../Music/CopperNickel.ogg')

        # Display each line one at a time, and require the pressing of enter
        # on lines that aren't solely whitespace
        with open('../peasant_lore.txt', encoding='utf-8') as f:
            for line in f:
                if ''.join(char for char in line.split(" ") if char.isalnum()):
                    main.s_input(''.join(line.split("\n")))
                else:
                    print(''.join(line.split("\n")))

        sounds.play_music('../Music/Title Screen.flac')

    except FileNotFoundError:
        logging.exception(
            f'Error finding peasant_lore.txt on {time.strftime("%m/%d/%Y at %H:%M:%S")}:'
        )
        print('The "peasant_lore.txt" file could not be found.')

    except OSError:
        logging.exception(
            f'Error loading peasant_lore.txt on {time.strftime("%m/%d/%Y at %H:%M:%S")}:'
        )
        print('There was an problem opening "peasant_lore.txt".')

    print('-' * save_load.divider_size)
Esempio n. 4
0
def game_loop():
    party_info['music'] = tiles.find_cell_with_tile_id(
        party_info['current_tile'].tile_id).music
    sounds.play_music(party_info['music'])

    while True:
        if not towns.search_towns():
            print('-' * save_load.divider_size)

        available_dirs = game_ui()

        while True:
            party_info['gamestate'] = 'overworld'
            command = s_input(
                'Input Command (type "help" to view command list): ').lower()

            if command == "debug-menu":
                debug_command()

            elif any(map(command.startswith, [x[0] for x in available_dirs])):
                move_command(available_dirs, command[0])

                break

            elif command.startswith('p'):
                stats_command()

            elif command.startswith('m'):
                magic_command()

            elif command.startswith('i'):
                inv_command()

            elif command.startswith('t'):
                tools_command()

            elif command.startswith('l'):
                look_command()

            elif command.startswith('r'):
                recheck_command()

            elif command.startswith('c'):
                title_screen.edit_settings()

            elif command.startswith('h'):
                help_command()

            else:
                continue

            available_dirs = game_ui()
def show_title():
    title_logo = f"""\
  ____                            _       _
 |  _ \ ___  __ _ ___  __ _ _ __ | |_ ___( )
 | |_) / _ \/ _` / __|/ _` | '_ \| __/ __|/
 |  __/  __/ (_| \__ \ (_| | | | | |_\__ \\
 |_|   \___|\__,_|___/\__,_|_| |_|\__|___/
         _                           _
        / \   ___  ___ ___ _ __  ___(_) ___  _ __
       / _ \ / __|/ __/ _ \ '_ \/ __| |/ _ \| '_ \\
      / ___ \\\__ \ (_|  __/ | | \__ \ | (_) | | | |
     /_/   \_\___/\___\___|_| |_|___/_|\___/|_| |_|
Peasants' Ascension {game_version} -- Programmed by TheFrozenMawile using Python
Licensed under the GNU GPLv3: [https://www.gnu.org/copyleft/gpl.html]
Check here often for updates: [http://www.reddit.com/r/PeasantsAscension/]
{'-'*save_load.divider_size}"""

    sounds.play_music('../Music/Title Screen.flac')

    print(title_logo)

    while True:
        # Give the user a choice of keys to press to do specific actions
        choice = main.s_input(
            '[P]lay Game | [S]ettings | [C]redits | [L]ore | [E]xit | Input Letter: '
        ).lower()

        if choice.startswith('p'):
            return

        if choice.startswith("s") and not main.do_debug:
            edit_settings()
            print(title_logo)

        if choice.startswith('c') and not main.do_debug:
            show_credits()
            print(title_logo)

        if choice.startswith('l') and not main.do_debug:
            show_history()
            print(title_logo)

        if choice.startswith('e') and not main.do_debug:
            # Exit the game
            pygame.quit()
            sys.exit()
Esempio n. 6
0
def check_play_button(settings, screen, stats,play_button,mouse_x,mouse_y,ship,aliens,bullets,sb):
    """Starts game if button is clicked on"""
    if play_button.rect.collidepoint(mouse_x,mouse_y) and not stats.game_active:
        #Hide mouse while in game
        pygame.mouse.set_visible(False)
        settings.dynamic_settings_reset()
        stats.reset_stats()
        s.play_music()
        
        #Reset scoreboard
        sb.prep_score()
        sb.prep_highscore()
        sb.prep_level()
        sb.prep_ships()
        
        stats.game_active = True
        
        #Resets the game state
        bullets.empty()
        aliens.empty()
        create_army(settings,screen,ship,aliens)
        ship.center_ship()
Esempio n. 7
0
 def start(self):
     sounds.play_music(self.bg_music)
Esempio n. 8
0
File: maze.py Progetto: kxtells/Maze
FPS = 60
clock = pygame.time.Clock ()
window = pygame.display.set_mode(size)
pygame.display.set_caption("MAZE")
iconimg = pygame.image.load(getdatapath()+"icon.png").convert_alpha()
pygame.display.set_icon(iconimg)

PLAYER = cPlayer.cPlayer(10,10,10,10)
LEVEL = cLevel.cLevel()

show_menu = True
show_credits = False
endgame = False
fullscreen = False

SOUNDS.play_music(9)
MESSAGE = cMsg.cMsg("TEST",window)


#
# Menus
#

#Main Menu
main_menu_texts = 'Boring', 'Easy' , 'Normal' , 'Difficult' , 'Extreme', 'Insane'
main_menu = cMenu(main_menu_texts,"Difficulty",0,blue,red)
main_menu_img1 = pygame.image.load(getdatapath()+"img/arrkeys.png").convert_alpha()
esckey_img = pygame.image.load(getdatapath()+"img/esckey.png").convert_alpha()
mkey_img = pygame.image.load(getdatapath()+"img/mkey.png").convert_alpha()
pkey_img = pygame.image.load(getdatapath()+"img/pkey.png").convert_alpha()
skey_img = pygame.image.load(getdatapath()+"img/skey.png").convert_alpha()
Esempio n. 9
0
 def on_continue(self):
     sounds.play_music()
     director.pop()
Esempio n. 10
0
def after_battle(is_boss):
    # Assess the results of the battle
    print('-' * save_load.divider_size)

    for unit in enabled_pcus + m_list:
        if unit.hp <= 0 and 'dead' not in unit.status_ail:
            unit.hp = 0
            unit.status_ail = ['dead']

    while True:
        # If the monster wins...
        if any(['dead' not in m.status_ail for m in m_list]) and all(
            ['dead' in x.status_ail for x in enabled_pcus]):
            sounds.play_music('../Music/Power-Up.ogg')

            print(
                f'Despite your best efforts, the {units.monster.name} has killed your party.'
            )
            print('-' * save_load.divider_size)

            auto_yes = False
            while True:
                if auto_yes:
                    y_n = 'y'

                else:
                    y_n = main.s_input(
                        'Do you wish to continue playing? | Y/N: ').lower()

                if y_n.startswith('y'):
                    # If you die, you return to the last town visited or 0'N, 0'W if you haven't been to a town yet.

                    main.party_info['current_tile'] = main.party_info[
                        'prev_town']
                    units.heal_pcus(1)

                    sounds.play_music(main.party_info['music'])

                    return

                elif y_n.startswith('n'):
                    while True:
                        y_n = main.s_input(
                            'Are you sure you want to quit and lose unsaved progress? |  Y/N: '
                        ).lower()

                        if y_n.startswith('n') or main.do_debug:
                            auto_yes = True

                            break

                        elif y_n.startswith('y'):
                            pygame.quit()
                            sys.exit()

        # If the player wins...
        elif all(['dead' in m.status_ail for m in m_list]) and any(
            ['dead' not in x.status_ail for x in enabled_pcus]):
            sounds.play_music('../Music/Python_RM.ogg')

            if is_boss:
                print(f'The almighty {units.monster.name} has been slain!')
                units.defeated_bosses.append(units.monster.boss_id)
                units.monster.upon_defeating()

            else:
                print(
                    f'The {units.monster.name} falls to the ground, dead as a stone.'
                )

            # Formulas for item, gold, and experience drops
            gold_drops = math.ceil(
                sum([max(1, x.gold, 2.5 * x.lvl) for x in m_list]))
            expr_drops = math.ceil(
                sum([max(1, y.experience, 1.5**y.lvl) / 2 for y in m_list]))
            item_drops = []

            for monster in m_list:
                for item in monster.items:
                    item_drops.append((monster.name, item))

            main.party_info['gp'] += gold_drops
            main.s_input(f'Your party has gained {gold_drops} GP! ')

            # Each party member gets their own XP
            for character in enabled_pcus:
                character.exp += expr_drops
                main.s_input(f'{character.name} gained {expr_drops} XP! ')

            # Each monster can drop their own item
            for drop in item_drops:
                main.s_input(
                    f"The {drop[0]} dropped a {items.find_item_with_id(drop[1]).name}! "
                )
                items.add_item(drop[1])

            for character in enabled_pcus:
                character.level_up()

            sounds.play_music(main.party_info['music'])

            return

        else:
            units.player.hp = 1
            units.player.status_ail = ['alive']

            continue
Esempio n. 11
0
def battle_system(is_boss=False):
    global m_list
    global enabled_pcus
    global turn_counter

    enabled_pcus = [
        x for x in [
            units.player, units.solou, units.chili, units.chyme, units.storm,
            units.adorine, units.parsto
        ] if x.enabled
    ]
    turn_counter = 0

    # Bosses use a different battle music than when battling normal enemies
    if is_boss:
        m_list = ([units.monster] +
                  units.monster.lackies) if units.monster.lackies else [
                      units.monster
                  ]

        print(units.monster.ascii_art % '')

        if len(m_list) > 2:
            print(
                f'The legendary {units.monster.name} and its lackys have awoken!'
            )

        elif len(m_list) == 2:
            print(
                f'The legendary {units.monster.name} and its lacky have awoken!'
            )

        else:
            print(f'The legendary {units.monster.name} has awoken!')

        sounds.play_music('../Music/Terrible Tarantuloid.ogg')

        main.smart_sleep(0.35)

    else:
        # Add monsters to the battle.
        m_list = [units.monster]
        if random.randint(0, 1):
            m_list.append(units.monster_2)

            if random.randint(0, 1):
                m_list.append(units.monster_3)

        print(units.monster.ascii_art % '')

        if len(m_list) == 3:
            print(
                f'A {units.monster.name} and 2 other monsters suddenly appeared out of nowhere!'
            )

        elif len(m_list) == 2:
            print(
                f'A {units.monster.name} and 1 other monster suddenly appeared out of nowhere!'
            )

        else:
            print(f'A {units.monster.name} suddenly appeared out of nowhere!')

        sounds.play_music('../Music/Ruari 8-bit Battle.ogg')

        main.smart_sleep(1)

    # Record the player's non-hp/mp stats (e.g. defense)
    # So they can go back to normal after the battle
    set_temp_stats()
    main.party_info['gamestate'] = 'battle'

    # While all active party members are alive, continue the battle
    while any([mstr.hp > 0 for mstr in m_list]) and any(
        [char.hp > 0 for char in enabled_pcus]):
        turn_counter += 1

        # A list of the battle participants sorted by speed. Updates once per turn.
        speed_list = sorted(m_list + enabled_pcus,
                            key=lambda x: 0.5 * x.spd
                            if "paralyzed" in x.status_ail else x.spd,
                            reverse=True)

        # Display HP, MP, Levels, and Statuses for all battle participants
        bat_stats()

        for num, character in enumerate(enabled_pcus):
            # If any of your party members are at less than 20% health, play a small jingle
            if 0 < character.hp <= 0.20 * character.max_hp:
                print(
                    f"Warning: {character.name}'s HP is low, heal as soon as possible!\n"
                )
                sounds.health_low.play()
                main.smart_sleep(1)

            # Let each awake and alive character choose their move
            if 'dead' not in character.status_ail:
                character.player_choice()

                if num + 1 < len(
                    [x for x in enabled_pcus if 'dead' not in x.status_ail]):
                    print('-' * save_load.divider_size)

        # Make sure each participant in the battle goes according to who's fastest
        for char in speed_list:
            if 'dead' not in char.status_ail:
                if all(x.hp <= 0 for x in m_list):
                    break

                print('-' * save_load.divider_size)

                if ((isinstance(char, units.PlayableCharacter)
                     and char.battle_turn() == 'Ran')
                        or (isinstance(char, units.Monster)
                            and char.base_turn() == 'Ran')):
                    return

                if any(x.hp > 0 for x in enabled_pcus):
                    if any(x.hp > 0
                           for x in m_list) and 'dead' not in char.status_ail:
                        main.s_input('\nPress enter/return ')

                    elif all(x.hp <= 0 for x in m_list):
                        break

                else:
                    break

            # Check if any characters died on the participants turn
            for char_2 in speed_list:
                if isinstance(
                        char_2, units.PlayableCharacter
                ) and char_2.hp <= 0 and 'dead' not in char_2.status_ail:
                    char_2.hp = 0
                    char_2.status_ail = ['dead']
                    sounds.ally_death.play()

                    print('-' * save_load.divider_size)
                    print(f"{char_2.name} has fallen to the monsters!")
                    main.s_input("\nPress enter/return ")

                if isinstance(
                        char_2, units.Monster
                ) and char_2.hp <= 0 and 'dead' not in char_2.status_ail:
                    char_2.hp = 0
                    char_2.status_ail = ['dead']
                    sounds.enemy_death.play()

                    print('-' * save_load.divider_size)
                    print(f"The {char_2.name} was defeated by your party!")
                    main.s_input("\nPress enter/return ")

    after_battle(is_boss)
Esempio n. 12
0
    def __init__(self, input_state, starfield=None):
        super().__init__(input_state)
        self.font = pygame.font.SysFont(None, Menu.TitleSize)
        self.starfield = starfield or Starfield()
        self.title = Group()
        # create "Space Invaders" logo

        # green "SPACE"
        space_title = StaticAnimation(
            self.font.render("SPACE", True, config.green_color))
        space_title.rect.centerx = config.screen_rect.centerx
        space_title.rect.centery = config.screen_height // 8

        # white "INVADERS"
        self.font = pygame.font.SysFont(None, Menu.TitleSize // 2)
        invaders_title = StaticAnimation(
            self.font.render("INVADERS", True, pygame.Color('white')))
        invaders_title.rect.left = space_title.rect.left + space_title.rect.width // 8
        invaders_title.rect.top = space_title.rect.bottom + 10

        self.title.add(space_title, invaders_title)

        last_y = config.screen_height - config.screen_height // 3
        self.options = Group()
        self.font = pygame.font.SysFont(None, Menu.MenuItemSize)

        # create options
        for option in [("Play Space Invaders", self._play_game),
                       ("High Scores", self._view_high_scores),
                       ("Quit", self._quit)]:
            option_sprite = StaticAnimation(
                self.font.render(option[0], True, config.text_color))
            option_sprite.callback = option[1]

            option_sprite.rect.centerx = config.screen_width // 2
            option_sprite.rect.top = last_y

            last_y = option_sprite.rect.bottom + Menu.MenuItemSpacing
            self.options.add(option_sprite)

        # create a small sprite to use as menu item selector
        left_selector = config.atlas.load_static("selector")

        # need to flip the arrow...
        right_selector = StaticAnimation(
            pygame.transform.flip(left_selector.image, True, False))
        right_selector.rect.left = config.screen_width

        self.selectors = Group(left_selector, right_selector)

        # point values for aliens
        self.aliens = Group()

        y_pos = invaders_title.rect.bottom + 50

        for alien_stats in config.alien_stats:
            alien = config.atlas.load_animation(
                alien_stats.sprite_name).frames[0]
            spr = self._create_point_sprite(alien, alien_stats.points, y_pos)
            self.aliens.add(spr)
            y_pos = spr.rect.bottom + 10

        ufo = config.atlas.load_animation("ufo").frames[0]
        spr = self._create_point_sprite(ufo, "???", y_pos)

        self.aliens.add(spr)

        # finish creating state values
        self.next_state = None
        self._set_selected(0)

        pygame.mouse.set_visible(True)
        sounds.play_music(sounds.menu_music_name)
Esempio n. 13
0
 def music(self):
     sounds.play_music(self.music_file)
Esempio n. 14
0
 def on_continue(self):
     sounds.play_music()
     director.pop()