예제 #1
0
def create_items_from_file(item_filename):
    """
    Creates an items dict of the form in the module docstring
    from a file of the form:

    Types:
        Helmet
        Armor
        Sword
        Shield
        Ring

    1
    Name:
    Name of Item 1
    Description:
    Description of Item 1
    Category:
    Category of Item 1
    Strength: Num_Strength (1-4)
    Type:
    Type of Item 1

    2
    Name:
    Name of Item 2
    Description:
    Description of Item 2
    Category:
    Category of Item 2
    Strength: Num_Strength (1-4)
    Type:
    Type of Item 2

    etc.
    """
    with open(item_filename, 'r') as item_file:
        raw_items = item_file.readlines()

    items = {category: {strength: [] for strength in bumped_range(4)}
             for category in CATEGORIES}

    line_num = 0
    current_item_num = 1

    types = set()

    assert raw_items[line_num] == 'Types:\n'
    line_num += 1

    while raw_items[line_num][0:4] == '    ':
        types.add(raw_items[line_num].strip())
        line_num += 1

    line_num += 1  # Swallow \n between sections

    while line_num < len(raw_items) - 1:

        current_item_num_str = str(current_item_num) + '\n'
        assert current_item_num_str == raw_items[line_num]

        line_num += 1  # Advance to Name:\n
        assert raw_items[line_num] == 'Name:\n'

        line_num += 1  # Advance to Name text
        name = raw_items[line_num].strip()

        line_num += 1  # Advance to Description:\n
        assert raw_items[line_num] == 'Description:\n'

        line_num += 1  # Advance to Description text.
        description = ''
        while raw_items[line_num] != 'Category:\n':
            description += raw_items[line_num].strip() + ' '
            line_num += 1

        assert raw_items[line_num] == 'Category:\n'

        line_num += 1  # Advance to Category text
        category = raw_items[line_num].strip()
        assert category in CATEGORIES

        line_num += 1  # Advance to Strength: Num\n
        assert raw_items[line_num][0:10] == 'Strength: '

        try:
            strength = int(raw_items[line_num].strip()[10:])
        except ValueError:
            print raw_items[line_num]
            raise

        line_num += 1  # Advance to Type:\n
        assert raw_items[line_num] == 'Type:\n'

        line_num += 1  # Advance to Type Text
        item_type = raw_items[line_num].strip()
        assert item_type in types

        line_num += 2

        current_item_num += 1
        new_item = ItemTemplate(name, description, category,
                                strength, item_type)
        items[category][strength].append(new_item)

    for _, i in items.iteritems():
        for _, j in i.iteritems():
            shuffle(j)
    return items
예제 #2
0
파일: Game.py 프로젝트: reem/commonplace
    def play_turn(self):
        "Plays a turn of the game."
        self.turn_count += 1
        print "Turn {0.turn_count}:\n".format(self)

        self.player.health += int(self.player.max_health / 5)
        spaced_print("You healed {} hp.".format(
            int(self.player.max_health / 5)))

        spaced_print("Location:", pre=False)
        print self.current_room.full_info()

        while True:
            main_choice = prompt(self.current_room.valid_options + ['player'])
            # Valid options are:
            #    doors -- poem and regular
            #    items -- regular
            #    monsters -- regular
            #    player -- poem and regular
            #    treasure -- poem
            #    guardian -- poem
            #    charactercs -- regular, but not included.

            # Could be better implemented with a callback pattern but there are
            # time constraints here.
            if main_choice == 'doors':
                spaced_print(format_objects(self.current_room.doors))
                door_choice = prompt(self.current_room.doors.keys() + ['back'])

                if door_choice == 'back':
                    continue

                self.current_room = self.current_room.doors[door_choice]
                break

            elif main_choice == 'items':
                assert_with_dump(self.current_room, BrainRoom,
                                 callback=isinstance)

                spaced_print(format_objects(self.current_room.items))
                item_choice = prompt(
                    bumped_range(len(self.current_room.items)) + ['back'])

                if item_choice == 'back':
                    continue

                item_index = int(item_choice) - 1
                current_item = self.current_room.items[item_index]

                spaced_print(str(current_item))
                item_action = prompt(['info', 'take', 'back'])

                if item_action == 'back':
                    continue
                elif item_action == 'take':
                    self.player.inventory.append(
                        self.current_room.items.pop(item_index))
                    continue
                elif item_action == 'info':
                    spaced_print(current_item.full_info())
                    continue

            elif main_choice == 'player':
                spaced_print(self.player.full_info())
                player_choice = prompt(["inventory", "back"])

                if player_choice == 'back':
                    continue
                elif player_choice == 'inventory':
                    spaced_print("Inventory:\n{}".format(format_objects(
                        self.player.inventory)))
                    inventory_choice = prompt([str(i)
                                               for i in bumped_range(
                                                   len(self.player.inventory))
                                               ] + ['back'])

                    if inventory_choice == 'back':
                        continue

                    inventory_choice = int(inventory_choice) - 1
                    if inventory_choice in range(len(self.player.inventory)):

                        inventory_item = self.player.inventory[
                            inventory_choice]
                        if isinstance(inventory_item, BaseEquipment):
                            spaced_print(inventory_item.full_info())
                            item_choice = prompt(['equip', 'back'])

                            if item_choice == 'back':
                                continue
                            elif item_choice == 'equip':
                                assert_with_dump(self.player.equipped,
                                                 inventory_item.eq_type,
                                                 callback=contains)
                                self.player.equip(inventory_item,
                                                  inventory_item.eq_type)

                        elif isinstance(inventory_item, BaseTreasure):
                            spaced_print(inventory_item.full_info())
                            treasure_choice = prompt(['back'])

                            if treasure_choice == 'back':
                                continue

            elif main_choice == 'monsters':
                assert_with_dump(self.current_room, BrainRoom,
                                 callback=isinstance)

                spaced_print("Monsters:\n{}".format(
                    format_objects(self.current_room.monsters)))
                monster_choice = prompt([str(i)
                                         for i in bumped_range(len(
                                             self.current_room.monsters))] \
                                        + ['back'])

                if monster_choice == 'back':
                    continue

                monster_index = int(monster_choice) - 1
                if monster_index in range(len(
                        self.current_room.monsters)):

                    current_monster = self.current_room.monsters[monster_index]
                    spaced_print(current_monster.full_info())
                    monster_action = prompt(['attack', 'back'])

                    if monster_action == 'back':
                        continue
                    else:
                        try:
                            fight(self.player, current_monster)
                        except MonsterDeadException:
                            spaced_print("The monster dropped:\n\n{}".format(
                                current_monster.drop))
                            self.player.inventory.append(current_monster.drop)
                            del self.current_room.monsters[monster_index]
                        except AbortFightException:
                            spaced_print("You escaped.")

            elif main_choice == 'guardian':
                assert_with_dump(self.current_room, PoemRoom,
                                 callback=isinstance)

                spaced_print("Guardian:\n\n{}".format(
                    self.current_room.guardian.full_info()))
                guardian_choice = prompt(['attack', 'back'])

                if guardian_choice == 'back':
                    continue

                spaced_print("You cannot run from a guardian. You must fight.",
                             pre=False)

                sleep(0.3)

                try:
                    fight(self.player, self.current_room.guardian,
                          monster_name='guardian', can_run=False)
                except MonsterDeadException:
                    if self.current_room.guardian.monster_type == 'FinalBoss':
                        raise FinalBossDeadException

                    spaced_print("The guardian dropped:\n\n{}".format(
                        self.current_room.guardian.drop))
                    self.player.inventory.append(
                        self.current_room.guardian.drop)
                    self.current_room.guardian = None

            elif main_choice == 'treasure':
                if self.current_room.guardian is not None:
                    spaced_print("You must defeat the guardian first.",
                                 pre=False)
                    continue
                spaced_print("Treasure:\n{}".format(
                    str(self.current_room.treasure)))
                treasure_choice = prompt(['take', 'back'])

                if treasure_choice == 'back':
                    continue
                elif treasure_choice == 'take':
                    spaced_print(self.current_room.treasure.full_info())
                    print "You acquired {}".format(
                        self.current_room.treasure.name)
                    self.player.inventory.append(self.current_room.treasure)
                    self.current_room.treasure = None