示例#1
0
def input_map_size():
    """
    Prompts player to input map size.

    Returns:
        map_size (int)
    """

    logger.info(text.dungeon_size_promt)
    logger.debug("expecting map size input from user")
    user_input = input().lower()

    map_size = None

    while not map_size:

        if (user_input.isdigit() and int(user_input) >= MIN_MAP_SIZE
                and int(user_input) <= MAX_MAP_SIZE):
            map_size = int(user_input)

        else:
            for key in map_sizes.keys():
                if user_input.lower() == key:
                    map_size = map_sizes[key]

        if not map_size:
            logger.debug("incorrect map size input from user")
            logger.info(text.dungeon_size_hint)
            logger.debug("expecting map size input from user")
            user_input = input()

    return map_size
示例#2
0
def save_game(ai_game):
    """
    Save the game to a file
    """
    # Open file and save data
    with open(get_save_file(ai_game), 'wb') as save_file:
        pickle.dump(ai_game.stats.high_score, save_file)

    logger.info('Saved High Score: {}'.format(ai_game.stats.high_score))
示例#3
0
 def reset_stats(self):
     """
     Initialize the stats that can be changed during the game
     """
     self.ships_left = self.ai_settings.ship_limit
     self.score = 0
     self.level = 1
     logger.info('Game Stats reset - Ship Limit: {} - Score: {}'.format(
         self.ships_left, self.score))
示例#4
0
def get_number_of_rows(ai_settings, ship_height, alien_height):
    """
    Determine the number of rows of aliens that fit on the screen
    """
    available_space_y = (ai_settings.screen_height - (3 * alien_height) -
                         ship_height)
    logger.debug('Available Screen Y Space: {}'.format(available_space_y))

    number_of_rows = int(available_space_y / (2 * alien_height))
    logger.info('Number of Alien Rows: {}'.format(number_of_rows))

    return number_of_rows
示例#5
0
def load_game(ai_game):
    """
    Load the game file
    """
    # Try to open file and load data
    try:
        with open(get_save_file(ai_game), 'rb') as save_file:
            ai_game.stats.high_score = pickle.load(save_file)

        logger.info('High Score Loaded: {}'.format(ai_game.stats.high_score))
    except FileNotFoundError:
        logger.info('Save file not found')
示例#6
0
def get_number_aliens_x(ai_settings, alien_width):
    """
    Determine the number of aliens that fit in a row
    """
    # Create a border at both screen edges equal to the width of an alien
    available_space_x = ai_settings.screen_width - 2 * alien_width
    logger.debug('Available Screen X Space: {}'.format(available_space_x))

    # Space between each alien is equal to the width of an alien
    number_aliens_x = int(available_space_x / (2 * alien_width))
    logger.info('Number of Aliens per Row: {}'.format(number_aliens_x))

    return number_aliens_x
    def print_map(self):
        """
        Prints map
        """
        printed_map = [[row[i] for row in self.cells]
                       for i in range(self.height)]

        printed_map.reverse()

        map_string = ""

        for row in printed_map:
            map_string = "\n".join([map_string, " ".join(row)])

        logger.info(map_string)
示例#8
0
def end_game(ai_game=None, error=False):
    """
    End the game, saving the high score to a pickle file
    """
    logger.info('Ending Game')

    if ai_game:
        # Save the highscore before exiting
        save_game(ai_game)

    pygame.quit()

    if error:
        sys.exit(1)
    else:
        sys.exit()
示例#9
0
    def screen(self):
        """
        Create a game screen and set the caption
        :return: pygame.display
        """
        if not self._screen:
            # Create the game screen
            screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
            logger.info('Screen created with H: {} W: {}'.format(
                self.settings.screen_height, self.settings.screen_width))

            # Set screen caption
            pygame.display.set_caption('Alien Invasion')

            self._screen = screen

        return self._screen
    def init_new_game(self):
        """
        Initializes new games
        """
        logger.info(text.new_game_start)
        input()
        logger.info(text.administration)
        input()
        logger.info(text.enter_proficiency_prompt)
        user_input = input().lower()

        if user_input in DungeonGame.player.proficiencies:
            DungeonGame.player.proficiency = user_input
        else:
            DungeonGame.player.proficiency = "none"

        logger.info(text.enter_dungeon_width_prompt)
        width = input_number_from_boundaries(DungeonGame.MIN_MAP_WIDTH,\
         DungeonGame.MAX_MAP_WIDTH)

        logger.info(text.enter_dungeon_height_prompt)
        height = input_number_from_boundaries(DungeonGame.MIN_MAP_HEIGHT,\
         DungeonGame.MAX_MAP_HEIGHT)

        size = width * height

        number_of_treasures = max (size * DungeonGame.treasure_rarity,\
         DungeonGame.treasure_to_win)
        number_of_traps = min (size - number_of_treasures - 1, size * DungeonGame.trap_rarity)

        traps = Trap.generate_traps(number_of_traps)

        starting_position = Position.generate_random_position(width, height)

        DungeonGame.dmap.initialize(height, width, number_of_treasures, traps, starting_position)

        DungeonGame.player.health = DungeonGame.default_health
        DungeonGame.player.bag = 0
        DungeonGame.player.position = starting_position
        DungeonGame.player.discovered_map.initialize_discovered_map(height, width,\
         starting_position)

        self.respawn_enemy()
def process_yes_no_input():
    """
    Processes input that shoul be either accept or decline

    return: (bool) True for accept, False for decline
    """
    user_input = input().lower()

    if user_input == "y" or user_input == "yes":
        return True

    elif user_input == "n" or user_input == "no":
        return False

    logger.info(wrong_y_n_input)

    user_input = input().lower()

    if user_input == "y" or user_input == "yes":
        return True

    return False
def process_yes_no_input():
    """
    Processes input that shoul be either accept or decline

    return: (bool) True for accept, False for decline
    """
    user_input = input().lower()

    if user_input == "y" or user_input == "yes":
        return True

    elif user_input == "n" or user_input =="no":
        return False

    logger.info("Enter 'y' or 'yes' for yes, anything else for no.")

    user_input = input().lower()

    if user_input == "y" or user_input == "yes":
        return True

    return False
def input_number_from_boundaries(min_value, max_value):
    """
    Prompts user to enter integer in given boundaries.

    return: int from given boundaries that is entered by user
    """

    while True:
        try:
            number = int(input())
        except ValueError:
            logger.debug("non-numeric input from user")
            logger.info("please enter number between {} {}".
            format(min_value, max_value))
        else:
            if number >= min_value and number <= max_value:
                break
            else:
                logger.debug("input from user out of specified bounds")
                logger.info("please enter number between {} {}".
                format(min_value, max_value))

    return number
def input_number_from_boundaries(min_value, max_value):
    """
    Prompts user to enter integer in given boundaries.

    return: int from given boundaries that is entered by user
    """
    user_input = input().lower()

    number = None

    while not number and number != 0:

        if (user_input.isdigit() and int(user_input) >= min_value
                and int(user_input) <= max_value):
            number = int(user_input)

        if not number:
            logger.debug("incorrect input from user")
            logger.info("please enter number between {} {}".format(
                min_value, max_value))

            user_input = input()

    return number
示例#15
0
    def increase_speed(self):
        """
        Increase the speed settings and the points per kill
        """
        self.ship_speed_factor *= self.speedup_scale
        self.bullet_speed_factor *= self.speedup_scale
        self.alien_speed_factor *= self.speedup_scale

        self.alien_points = int(self.alien_points * self.score_scale)

        logger.info('SpeedUp - Bullet Speed: {:3.3}'.format(
            self.bullet_speed_factor))
        logger.info('SpeedUp - Alien Speed: {:3.3}'.format(
            self.alien_speed_factor))
        logger.info('SpeedUp - Ship Speed: {:3.3}'.format(
            self.ship_speed_factor))
        logger.info('SpeedUp - Kill Points: {:3}'.format(self.alien_points))
示例#16
0
def run_game():
    """
    Initiate the pygame, settings, and create a screen object
    """
    logger.info('Game Loaded')

    pygame.init()

    ai_game = AlienInvasion()

    game_core.load_game(ai_game)

    # Start the main loop for the game
    while True:
        # Watch for keyboard and mouse events
        user_events.check_events(ai_game)

        if ai_game.stats.game_active:
            ai_game.ship.update()
            ship_functions.update_bullets(ai_game)
            fleet_functions.update_aliens(ai_game)

        # Redraw the screen and flip to new
        game_core.update_screen(ai_game)
示例#17
0
    def initialize_dynamic_settings(self):
        """
        Initialize the settings that change throughout the game
        """
        self.ship_speed_factor = 1.5
        self.bullet_speed_factor = 3
        self.alien_speed_factor = 1

        # fleet_direction of 1 is right; -1 is left
        self.fleet_direction = 1

        # Scoring settings
        self.alien_points = 50

        logger.info('Initial - Bullet Speed: {:3}'.format(
            self.bullet_speed_factor))
        logger.info('Initial - Alien Speed: {:3}'.format(
            self.alien_speed_factor))
        logger.info('Initial - Ship Speed: {:3}'.format(
            self.ship_speed_factor))
        logger.info('Initial - Kill Points: {:3}'.format(self.alien_points))
    def process_hostile_encounter(self, hostile_entity):
        """
        Resolves Player's encounter with Trap or Enemy.
        """
        logger.info(choice(hostile_entity.encounter_description))

        if DungeonGame.player.proficiency in hostile_entity.fight_description.keys():
            logger.info(choice(hostile_entity.fight_description[DungeonGame.player.proficiency]))
        else:
            logger.info(choice(hostile_entity.fight_description["other"]))

        is_damaged = DungeonGame.player.proficiency_immunity[DungeonGame.player.proficiency]\
         != hostile_entity.enemy_type

        if is_damaged:
            DungeonGame.player.take_damage()

        if DungeonGame.player.is_alive():
            if DungeonGame.player.proficiency in hostile_entity.survive_description.keys():
                logger.info(choice(hostile_entity.survive_description[DungeonGame.player.proficiency]))
            else:
                logger.info(choice(hostile_entity.survive_description["other"]))

        else:
            if DungeonGame.player.proficiency in hostile_entity.defeat_description.keys():
                logger.info(choice(hostile_entity.defeat_description[DungeonGame.player.proficiency]))
            else:
                logger.info(choice(hostile_entity.defeat_description["other"]))
    def process_room(self):
        """
        Resolves possible trap encounters and prints feedback.
        """

        #to prevent room and enemy encounter texts from mixing
        while DungeonGame.is_enemy_encounter_being_processed:
            pass

        if not self.player.is_alive():
            return        

        logger.info(text.tell_position.format(DungeonGame.player.position.x,\
         DungeonGame.player.position.y))

        current_cell = DungeonGame.dmap.cell(DungeonGame.player.position)

        if not current_cell:
            logger.debug("processing non-existant room!")
            return

        logger.debug("entered cell {}".format(current_cell))


        current_cell = DungeonMap.cells_dict[current_cell]

        if current_cell.legend in trap_legends:
            self.process_hostile_encounter(current_cell)

            if not self.player.is_alive():
                return
        else:
            logger.info(choice(current_cell.encounter_description))

            if current_cell.legend == treasure_cell.legend:
                DungeonGame.player.bag += 1

        if DungeonGame.dmap.cell(DungeonGame.player.position) != entrance_cell.legend:
            DungeonGame.dmap.assign_cell(DungeonGame.player.position, empty_cell.legend)

        is_trap_nearby = DungeonGame.dmap.check_for_adjacent_types(DungeonGame.player.position,\
         trap_legends)

        is_treasure_nearby = DungeonGame.dmap.check_for_adjacent_types(DungeonGame.player.position,\
         treasure_cell.legend)

        if is_trap_nearby and not is_treasure_nearby:
            logger.info(choice(text.adjacent_trap))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["trap near"])

        elif not is_trap_nearby and is_treasure_nearby:
            logger.info(choice(text.adjacent_treasure))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["treasure near"])

        elif is_trap_nearby and is_treasure_nearby:
            logger.info(choice(text.adjacent_trap))
            logger.info(choice(text.also))
            logger.info(choice(text.adjacent_treasure))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["treasure and trap near"])

        elif DungeonGame.dmap.cell(DungeonGame.player.position) == entrance_cell.legend:
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
            DungeonMap.discovery_dict["entrance"])
        else:
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["empty"])
    def process_player_commands(self):
        """
        Process player commands.
        """
        logger.info(text.action_prompt)
        user_input = input().lower()

        while (not user_input in DungeonGame.actions_cheat.keys()
         and not user_input in DungeonGame.actions_cheat.values()):
            logger.info(text.action_wrong)
            print_dictionary(DungeonGame.actions)
            user_input = input().lower()

        if user_input in DungeonGame.actions_cheat.keys():
            user_input = DungeonGame.actions_cheat[user_input]

        if user_input in DungeonGame.action_to_position.keys():
            move_position = DungeonGame.player.position + DungeonGame.action_to_position[user_input]

            if not DungeonGame.dmap.is_position_in_map(move_position):
                logger.info(choice(text.no_passage))
            else:
                DungeonGame.player.position = move_position
                self.process_room()

        elif user_input == "m":
            map_to_print = deepcopy(DungeonGame.player.discovered_map)
            map_to_print.assign_cell(DungeonGame.player.position, "p")
            map_to_print.print_map()

        elif user_input == "lg":
            print_dictionary(DungeonMap.discovery_dict)

        elif user_input == "h":
            logger.info(text.health_check)
            logger.info(text.health_description[DungeonGame.player.health])

        elif user_input == "b":
            logger.info(text.treasure_check.format(DungeonGame.player.bag))

        elif user_input == "ld":
            if isfile("./{}.pickle".format(DungeonGame.player.name)):
                self.load_game()
                logger.info(choice(text.load_ingame))
            else:
                logger.info(choice(text.on_no_save_file))

        elif user_input == "sv":
            logger.info(choice(text.on_save_1))
            self.save_game()
            logger.info(choice(text.on_save_2))

        elif user_input == "e":
            logger.info(choice(text.lets_end_this))
            while DungeonGame.player.is_alive():
                DungeonGame.player.take_damage()

        elif user_input == "cheat":
            map_to_print = deepcopy(DungeonGame.dmap)
            map_to_print.assign_cell(DungeonGame.player.position, "p")
            map_to_print.print_map()
"""main module for Dungeon Game
"""

import pickle
import os.path

import terrain
import game
from game_logger import logger


start_row = 0
start_col = 0
squares_map = []

logger.info("Welcome to the game!")

while True:

    logger.info("Type \"new\" to start new game")
    logger.info("Type \"load\" to load saved game")
    command = input()

    if command == "new":

        scale = input("Enter map scale: ")
        start_row, start_col, squares_map = terrain.generate(int(scale))
        logger.debug("new game created")
        break

    elif command == "load":
示例#22
0
def game_loop():
    """
    Game loop.
    """

    while True:

        is_game_started = False

        is_player_alive = True
        treasure_collected = 0

        if os.path.isfile("./{}".format(SAVE_FILE_NAME)):

            logger.info(text.load_or_new_game_prompt)
            user_input = input().lower()

            if (user_input == "load"):

                dmap, discovered_map, pos_x, pos_y,\
                treasure_collected = load_game()

                treasure_number = map_generator.count_tiles_of_type(
                    dmap, 'treasure')

                is_game_started = True

                logger.info(random.choice(text.load_game_start))

                input()

                dmap, discovered_map, pos_x, pos_y, treasure_number,\
                treasure_collected, is_player_alive= \
                    enter_room(dmap, discovered_map, pos_x, pos_y,
                    random.choice(text.enter_room_wake_up), treasure_number,
                    treasure_collected, is_player_alive)

        if not is_game_started:

            logger.info(text.start)
            input()
            dmap, discovered_map, pos_x, pos_y, treasure_number = init_game()
            logger.debug("new game initialized")
            total_treasure = treasure_number

            logger.info(random.choice(text.go_to_dungeon))
            input()
            logger.info(random.choice(text.enter_dungeon))
            input()

            dmap, discovered_map, pos_x, pos_y, treasure_number,\
            treasure_collected, is_player_alive= \
                enter_room(dmap, discovered_map, pos_x, pos_y, text.entrance, treasure_number,
                treasure_collected, is_player_alive)

        while is_player_alive and treasure_number != 0:

            dmap, discovered_map, pos_x, pos_y, treasure_number,\
            treasure_collected, is_player_alive = \
                process_player_commands(dmap, discovered_map, pos_x, pos_y,
                treasure_number, treasure_collected, is_player_alive)

        input()

        if is_player_alive:
            logger.info(random.choice(text.won))
            logger.debug("player won")
        else:
            logger.info(random.choice(text.lost))
            logger.debug("player lost")

            logger.info(
                text.game_statistics.format(
                    *
                    [treasure_collected, treasure_collected +
                     treasure_number]))

        input()

        map_generator.print_dungeon_map(dmap)
        logger.info(text.end_map_description)

        input()

        logger.info(text.play_again_prompt)
        logger.debug("expecting play again confirmation input from user")
        user_input = input().lower()

        if user_input == 'y' or user_input == 'yes':
            logger.debug("user decides to play again")
            continue
        elif user_input == 'n' or user_input == 'no':
            logger.debug("user decides not to play again")
            break

        logger.info(text.play_again_hint)
        logger.debug("incorrect input from user")
        logger.debug("expecting play again confirmation input from user")
        user_input = input().lower()

        if user_input != 'y' and user_input != 'yes':
            logger.debug("user decides not to play again")
            break

        logger.debug("user decides to play again")
示例#23
0
def process_player_commands(dmap, discovered_map, pos_x, pos_y,
                            treasure_number, treasure_collected,
                            is_player_alive):
    """
    Process player commands.
    """

    logger.info(text.action_prompt)
    user_input = input().lower()

    while not user_input in actions.keys(
    ) and not user_input in actions.values():
        logger.info(text.action_wrong)
        logger.debug("user enters incorrect input")
        user_input = input().lower()

    if user_input == 'view map' or user_input == actions['view map']:

        logger.debug("player views map")
        printed_map = copy.deepcopy(discovered_map)
        printed_map[pos_x][pos_y] = map_generator.tiles['player']
        map_generator.print_dungeon_map(printed_map)
        logger.info(text.legend_prompt)
        user_input = input().lower()

        if user_input == 'l':
            logger.debug("player views legend")
            input(text.legend)

    elif user_input == 'save' or user_input == actions['save']:
        logger.debug("user attempts save game")
        save_game(dmap, discovered_map, pos_x, pos_y, treasure_collected)
        logger.info(random.choice(text.fall_asleep_1))
        logger.info(random.choice(text.fall_asleep_2))

    elif user_input == 'load' or user_input == actions['load']:
        logger.debug("user attempts load game")

        if os.path.isfile("./{}".format(SAVE_FILE_NAME)):

            dmap, discovered_map, pos_x, pos_y,\
            treasure_collected = load_game()

            logger.info(random.choice(text.load_game_ingame))

            dmap, discovered_map, pos_x, pos_y, treasure_number,\
            treasure_collected, is_player_alive = \
                enter_room(dmap, discovered_map, pos_x, pos_y,
                random.choice(text.enter_room_wake_up), treasure_number,
                treasure_collected, is_player_alive)
        else:
            logger.debug("no save file exist to load")
            logger.info(random.choice(text.no_save_file_ingame))

    else:

        for direction in directions.keys():

            if (" ".join(['go', direction]) == user_input
                    or actions["".join(['go ', direction])] == user_input):
                logger.debug("player attemots to go {} to".format(
                    direction, pos_x + directions[direction][0],
                    pos_y + directions[direction][1]))

                if map_generator.is_position_in_map(
                        dmap, pos_x + directions[direction][0],
                        pos_y + directions[direction][1]):

                    pos_x += directions[direction][0]
                    pos_y += directions[direction][1]


                    dmap, discovered_map, pos_x, pos_y, treasure_number,\
                    treasure_collected, is_player_alive = \
                               enter_room(dmap, discovered_map, pos_x, pos_y, direction_opposites[direction],
                               treasure_number, treasure_collected, is_player_alive)

                else:
                    logger.info(random.choice(text.no_passage))

                    logger.debug("player can't go {} to".format(
                        direction, pos_x + directions[direction][0],
                        pos_y + directions[direction][1]))

                break

    return dmap, discovered_map, pos_x, pos_y, treasure_number, treasure_collected, is_player_alive
    def process_room(self):
        """
        Resolves possible trap encounters and prints feedback.
        """
        logger.info(text.tell_position.format(DungeonGame.player.position.x,\
         DungeonGame.player.position.y))

        current_cell = DungeonGame.dmap.cell(DungeonGame.player.position)

        if not current_cell:
            logger.debug("processing non-existant room!")
            return

        logger.debug("entered cell {}".format(current_cell))

        current_cell = DungeonMap.cells_dict[current_cell]

        logger.info(choice(current_cell.description))
        input()

        if current_cell.legend == treasure_cell.legend:
            DungeonGame.player.bag += 1

        elif current_cell.legend in trap_legends:
            if DungeonGame.player.proficiency in current_cell.fight_description.keys(
            ):
                logger.info(
                    choice(current_cell.fight_description[
                        DungeonGame.player.proficiency]))
            else:
                logger.info(choice(current_cell.fight_description["other"]))
            input()

            is_damaged = DungeonGame.player.proficiency_immunity[
                DungeonGame.player.proficiency] != current_cell.trap_type

            if is_damaged:
                DungeonGame.player.take_damage()

            if DungeonGame.player.is_alive():
                if DungeonGame.player.proficiency in current_cell.survive_description.keys(
                ):
                    logger.info(
                        choice(current_cell.survive_description[
                            DungeonGame.player.proficiency]))
                else:
                    logger.info(
                        choice(current_cell.survive_description["other"]))
                input()

            else:
                if DungeonGame.player.proficiency in current_cell.defeat_description.keys(
                ):
                    logger.info(
                        choice(current_cell.defeat_description[
                            DungeonGame.player.proficiency]))
                else:
                    logger.info(
                        choice(current_cell.defeat_description["other"]))
                input()
                return

        if DungeonGame.dmap.cell(
                DungeonGame.player.position) != entrance_cell.legend:
            DungeonGame.dmap.assign_cell(DungeonGame.player.position,
                                         empty_cell.legend)

        is_trap_nearby = DungeonGame.dmap.check_for_adjacent_types(DungeonGame.player.position,\
         trap_legends)

        is_treasure_nearby = DungeonGame.dmap.check_for_adjacent_types(DungeonGame.player.position,\
         treasure_cell.legend)

        if is_trap_nearby and not is_treasure_nearby:
            logger.info(choice(text.adjacent_trap))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["trap near"])
            input()

        elif not is_trap_nearby and is_treasure_nearby:
            logger.info(choice(text.adjacent_treasure))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["treasure near"])
            input()

        elif is_trap_nearby and is_treasure_nearby:
            logger.info(choice(text.adjacent_trap))
            logger.info(choice(text.also))
            logger.info(choice(text.adjacent_treasure))
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["treasure and trap near"])
            input()

        elif DungeonGame.dmap.cell(
                DungeonGame.player.position) == entrance_cell.legend:
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
            DungeonMap.discovery_dict["entrance"])
        else:
            DungeonGame.player.discovered_map.assign_cell(DungeonGame.player.position,\
             DungeonMap.discovery_dict["empty"])
def run(start_row, start_col, squares_map):
    """run the game

        function is proceeded until player finds a treasure or enters a trap

    Arguments:
        start_row int -- start position row
        start_col int -- start position column
        squares_map [str] -- game map
    """

    logger.info("Type \"up/down/left/right\" to move")
    logger.info("Type \"save\" to save current game")

    border = len(squares_map) - 1

    curr_row = start_row
    curr_col = start_col

    while True:

        if squares_map[curr_row][curr_col] == 't':

            logger.debug("player has found a treasure")
            logger.debug("game ends")
            logger.info("You have entered a trap!")
            break

        if squares_map[curr_row][curr_col] == '*':

            logger.debug("player has entered a trap")
            logger.debug("game ends")
            logger.info("You have found a treasure!")
            break

        if _structure_is_near('t', curr_row, curr_col, squares_map):

            logger.debug("trap is within one square")
            logger.info('There is a trap within one square!')

        if _structure_is_near('*', curr_row, curr_col, squares_map):

            logger.debug("treasure is within one square")
            logger.info('There is a treasure within one square!')

        moved = False

        while not moved:

            command = input("What to do?: ")

            if command == 'up':

                if curr_row == 0:

                    logger.info("You are already on top of the map!")
                    _write_move_fail_to_log(command)

                else:

                    moved = True
                    curr_row -= 1
                    logger.info("Moving up")

            elif command == 'down':

                if curr_row == border:

                    logger.info("You are already on bottom of the map!")
                    _write_move_fail_to_log(command)

                else:

                    moved = True
                    curr_row += 1
                    logger.info("Moving down")

            elif command == 'right':

                if curr_col == border:

                    msg = "You are already on the right border of the map!"
                    logger.info(msg)
                    _write_move_fail_to_log(command)

                else:

                    moved = True
                    curr_col += 1
                    logger.info("Moving right")

            elif command == 'left':

                if curr_col == 0:

                    msg = "You are already on the left border of the map!"
                    logger.info(msg)
                    _write_move_fail_to_log(command)

                else:

                    moved = True
                    curr_col -= 1
                    logger.info("Moving left")

            elif command == "save":

                with open("sav.txt", "wb") as savefile:

                    data_to_save = [curr_row, curr_col, squares_map]
                    pickle.dump(data_to_save, savefile, protocol=0)
                    logger.info("Saved succesfully")

            else:
                logger.info(F"Unknown command: {command}")

            if moved:

                logger.debug(F"moved {command}")
                cur_pos_msg = F"current position: ({curr_row}, {curr_col})"
                logger.debug(cur_pos_msg)
    def game_loop(self):
        """
        Game loop.
        """

        while True:

            logger.info(text.enter_name_prompt)

            name = input()
            name = list(filter(lambda c: c.isalpha(), name))
            name = "".join(name)

            if not name:
                name = "Anonymous"

            DungeonGame.player.name = name

            is_load_game = False

            if isfile("./{}.pickle".format(DungeonGame.player.name)):
                logger.info(text.load_game_on_start_prompt)
                is_load_game = process_yes_no_input()

            if is_load_game:
                self.load_game()
                logger.info(choice(text.load_on_start))
            else:
                self.init_new_game()

            threading.Thread(target=self.process_enemy).start()

            self.process_room()

            while not self.is_game_ended():
                self.process_player_commands()


            if DungeonGame.player.is_alive():
                logger.info(choice(text.won))
                logger.debug("DungeonGame.player won")
            else:
                logger.info(choice(text.lost))
                logger.debug("DungeonGame.player lost")

            input()

            logger.info(text.end_map_description)
            map_to_print = deepcopy(DungeonGame.dmap)
            map_to_print.assign_cell(DungeonGame.player.position, "p")
            map_to_print.print_map()
            print_dictionary(DungeonMap.cells_dict_explained)
            input()

            logger.info(text.play_again_prompt)

            is_play_again = process_yes_no_input()

            if not is_play_again:
                logger.debug("user exits game")
                break

            logger.debug("user decides to play again")
示例#27
0
def enter_room(dmap, discovered_map, pos_x, pos_y, direction, treasure_number,
               treasure_collected, is_player_alive):
    """
    Process entering the room.
    """

    logger.info(text.enter_room.format(direction))
    logger.info(text.tell_position.format(pos_x, pos_y))
    logger.debug("player enters {},{}".format(pos_x, pos_y))

    if dmap[pos_x][pos_y] == map_generator.tiles['empty']:
        logger.info(random.choice(text.no_encounter))
        logger.debug("player encounters nothing at {},{}".format(pos_x, pos_y))

    elif dmap[pos_x][pos_y] == map_generator.tiles['trap']:
        logger.info(random.choice(text.trap_encounter))
        logger.debug("player encounters trap at {},{}".format(pos_x, pos_y))
        is_player_alive = False

    elif dmap[pos_x][pos_y] == map_generator.tiles['treasure']:
        logger.info(random.choice(text.treasure_encounter))
        logger.debug("player encounters treasure at {},{}".format(
            pos_x, pos_y))
        treasure_number -= 1
        treasure_collected += 1
        if treasure_number == 0:
            logger.debug("player collects final treasure at {},{}".format(
                pos_x, pos_y))

    if not is_player_alive:
        logger.debug("player dies at {},{}".format(pos_x, pos_y))
        return dmap, discovered_map, pos_x, pos_y, treasure_number, treasure_collected, is_player_alive

    is_adjustant_traps = check_for_adjacent_type(dmap, pos_x, pos_y, 'trap')
    is_adjustant_treasure = check_for_adjacent_type(dmap, pos_x, pos_y,
                                                    'treasure')

    if is_adjustant_traps and not is_adjustant_treasure:
        logger.info(random.choice(text.adjacent_trap))
        discovered_map[pos_x][pos_y] = map_generator.tiles['bordering trap']

    elif not is_adjustant_traps and is_adjustant_treasure:
        logger.info(random.choice(text.adjacent_treasure))
        discovered_map[pos_x][pos_y] = map_generator.tiles[
            'bordering treasure']

    elif is_adjustant_treasure and is_adjustant_traps:
        discovered_map[pos_x][pos_y] = map_generator.tiles[
            'bordering treasure and trap']
        logger.info(random.choice(text.adjacent_trap))
        logger.info(random.choice(text.also))
        logger.info(random.choice(text.adjacent_treasure))

    else:
        discovered_map[pos_x][pos_y] = map_generator.tiles['empty']

    return dmap, discovered_map, pos_x, pos_y, treasure_number, treasure_collected, is_player_alive
示例#28
0
    """
    logger.info('Game Loaded')

    pygame.init()

    ai_game = AlienInvasion()

    game_core.load_game(ai_game)

    # Start the main loop for the game
    while True:
        # Watch for keyboard and mouse events
        user_events.check_events(ai_game)

        if ai_game.stats.game_active:
            ai_game.ship.update()
            ship_functions.update_bullets(ai_game)
            fleet_functions.update_aliens(ai_game)

        # Redraw the screen and flip to new
        game_core.update_screen(ai_game)


if __name__ == '__main__':
    try:
        run_game()
    except (SystemExit):
        logger.info('System Exited')
    except:
        logger.exception('Traceback Triggered')
        game_core.end_game(error=True)