Exemplo n.º 1
0
 def apply(self):
     entity = Entity(self.entity, response)
     gv.kg.player_location.add_entity(entity)
Exemplo n.º 2
0
    def place_entities(self, room, entities, max_monsters_per_room,
                       max_items_per_room):
        # Get a random number of monsters
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)

        # Monster cycle
        for i in range(number_of_monsters):
            # Choose a random location in the room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if (entity.x == x and entity.y == y)
            ]):
                if randint(0, 100) < 80:
                    fighter_component = Fighter(hp=10,
                                                defense=0,
                                                power=3,
                                                xp=35)
                    ai_component = BasicMonster()

                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.desaturated_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                else:
                    fighter_component = Fighter(hp=16,
                                                defense=1,
                                                power=4,
                                                xp=100)
                    ai_component = BasicMonster()

                    monster = Entity(x,
                                     y,
                                     'T',
                                     libtcod.desaturated_green,
                                     'Troll',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)

                entities.append(monster)

        # Item cycle
        for i in range(max_items_per_room):
            # Choose a random location
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if (entity.x == x and entity.y == y)
            ]):
                item_chance = randint(0, 100)

                if item_chance < 70:
                    item_component = Item(use_function=heal, amount=4)
                    item = Entity(x,
                                  y,
                                  '!',
                                  libtcod.violet,
                                  'Healing Potion lv.1',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_chance < 80:
                    item_component = Item(
                        use_function=cast_fireball,
                        targeting=True,
                        targeting_message=Message(
                            'Left-click a target tile for the fireball, or right-click to cancel.',
                            libtcod.light_cyan),
                        damage=12,
                        radius=3)
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.red,
                                  'Fireball Scroll lv.1',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_chance < 90:
                    item_component = Item(
                        use_function=cast_confusion,
                        targeting=True,
                        targeting_message=Message(
                            'Left-click a target tile for the confusion, or right-click to cancel.',
                            libtcod.light_cyan))
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.light_pink,
                                  'Confusion Scroll',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                else:
                    item_component = Item(use_function=cast_lightning,
                                          damage=20,
                                          maximum_range=5)
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.yellow,
                                  'Lightning Scroll lv.1',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                entities.append(item)
Exemplo n.º 3
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150)
    }

    player = Entity(int(screen_width / 2), int(screen_height / 2), '@',
                    libtcod.white)
    npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), '@',
                 libtcod.yellow)
    entities = [npc, player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        render_all(con, entities, game_map, screen_width, screen_height,
                   colors)

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move

            if not game_map.is_blocked(player.x + dx, player.y + dy):
                player.move(dx, dy)

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
Exemplo n.º 4
0
	def place_entities(self, room, entities):
		max_monsters_per_room = from_dungeon_level([[2, 1], [4, 4], [6, 6], [8, 10]], self.dungeon_level)
		max_items_per_room = from_dungeon_level([[1, 1], [2, 6]], self.dungeon_level)
		max_equipment_items_per_room = from_dungeon_level([[1, 4]], self.dungeon_level)

		number_of_equipment_items = randint(0, max_equipment_items_per_room)
		number_of_monsters = randint(0, max_monsters_per_room)
		number_of_items = randint(0, max_items_per_room)

		monster_chances = {
			'goblin': from_dungeon_level([[80, 1], [60, 3], [30, 5], [0, 7]], self.dungeon_level),
			'orc': from_dungeon_level([[40, 2], [50, 3], [30, 7]], self.dungeon_level),
			'troll': from_dungeon_level([[20, 3], [40, 5], [60, 7]], self.dungeon_level),
			'basilisk': from_dungeon_level([[20, 7], [30, 9], [80, 11]], self.dungeon_level)
		}


		#Terrium, Ferrium, Aurium
		item_chances = {
			'healing_potion': from_dungeon_level([[15, 1], [10, 8]], self.dungeon_level),
			'greater_healing_potion': from_dungeon_level([[30, 8]], self.dungeon_level),
			'terrium_sword': from_dungeon_level([[5, 4]], self.dungeon_level),
			'terrium_shield': from_dungeon_level([[15, 4]], self.dungeon_level),
			'terrium_chestplate': from_dungeon_level([[15, 5]], self.dungeon_level),
			'terrium_leg_armor': from_dungeon_level([[15, 4]], self.dungeon_level),
			'terrium_helmet': from_dungeon_level([[20, 3]], self.dungeon_level),
			'terrium_amulet': from_dungeon_level([[10, 7]], self.dungeon_level),
			'lightning_spell': from_dungeon_level([[25, 4]], self.dungeon_level),
			'fireball_spell': from_dungeon_level([[30, 5]], self.dungeon_level),
			'confusion_spell': from_dungeon_level([[25, 2]], self.dungeon_level),
			'sleep_spell': from_dungeon_level([[25, 4]], self.dungeon_level),
			'sleep_aura': from_dungeon_level([[30, 10]], self.dungeon_level)
		}

		equipment_item_chances = {
			'equipment_health_potion': from_dungeon_level([[25, 4]], self.dungeon_level)
		}

		for i in range(number_of_monsters):
			x = randint(room.x1 + 1, room.x2 - 1)
			y = randint(room.y1 + 1, room.y2 - 1)

			if not any([entity for entity in entities if entity.x == x and entity.y == y]):
				monster_choice = random_choice_from_dict(monster_chances)

				if monster_choice == 'goblin':
					fighter_component = Fighter(hp=5, defense=0, power=2, magic=0, xp=20)
					ai_component = BasicMonster()
					monster = Entity(x, y, 'g', libtcod.darker_chartreuse, 'Goblin', blocks=True,
						render_order=RenderOrder.ACTOR, fighter=fighter_component, ai=ai_component)
				elif monster_choice == 'orc':
					fighter_component = Fighter(hp=10, defense=0, power=4, magic=0, xp=40)
					ai_component = BasicMonster()
					monster = Entity(x, y, 'o', libtcod.desaturated_green, 'Orc', blocks=True,
						render_order=RenderOrder.ACTOR, fighter=fighter_component, ai=ai_component)
				elif monster_choice == 'troll':
					fighter_component = Fighter(hp=20, defense=2, power=8, magic=0, xp=100)
					ai_component = BasicMonster()
					monster = Entity(x, y, 'T', libtcod.darker_green, 'Troll', blocks=True, fighter=fighter_component,
						render_order=RenderOrder.ACTOR, ai=ai_component) 
				else:
					fighter_component = Fighter(hp=40, defense=5, power=16, magic=0, xp=200)
					ai_component = BasicMonster()
					monster = Entity(x, y, 'B', libtcod.darker_red, 'Basilisk', blocks=True, fighter=fighter_component,
						render_order=RenderOrder.ACTOR, ai=ai_component)

				entities.append(monster)

		for i in range(number_of_items):
			x = randint(room.x1 + 1, room.x2 - 1)
			y = randint(room.y1 + 1, room.y2 - 1)

			if not any([entity for entity in entities if entity.x == x and entity.y == y]):
				item_choice = random_choice_from_dict(item_chances)

				if item_choice == 'healing_potion':
					item_component = Item(use_function=heal, amount=20)
					item = Entity(x, y, '&', libtcod.violet, "health potion", render_order=RenderOrder.ITEM, item=item_component)
				elif item_choice == 'greater_healing_potion':
					item_component = Item(use_function=heal, amount=40)
					item = Entity(x, y, '&', libtcod.red, "greater healing potion", render_order=RenderOrder.ITEM, item=item_component)
				elif item_choice == 'terrium_sword':
					equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=randint(2, 4))
					item = Entity(x, y, '/', libtcod.darker_orange, "terrium sword", equippable=equippable_component)
				elif item_choice == 'terrium_shield':
					equippable_component = Equippable(EquipmentSlots.OFF_HAND, defense_bonus=randint(1, 2))
					item = Entity(x, y, '[', libtcod.darker_orange, "terrium shield", equippable=equippable_component)
				elif item_choice == 'terrium_chestplate':
					equippable_component = Equippable(EquipmentSlots.CHEST, defense_bonus=randint(2, 3))
					item = Entity(x, y, 'M', libtcod.darker_orange, "terrium chestplate", equippable=equippable_component)
				elif item_choice == 'terrium_leg_armor':
					equippable_component = Equippable(EquipmentSlots.LEGS, defense_bonus=randint(1, 2))
					item = Entity(x, y, 'H', libtcod.darker_orange, "terrium leg armor", equippable=equippable_component)
				elif item_choice == 'terrium_helmet':
					equippable_component = Equippable(EquipmentSlots.HEAD, defense_bonus=randint(1, 2))
					item = Entity(x, y, '^', libtcod.darker_orange, "terrium helmet", equippable=equippable_component)
				elif item_choice == 'terrium_amulet':
					equippable_component = Equippable(EquipmentSlots.AMULET, magic_bonus=randint(1, 4))
					item = Entity(x, y, '*', libtcod.darker_orange, "terrium amulet", equippable=equippable_component)
				elif item_choice == 'fireball_spell':
					item_component = Item(use_function=cast_fireball, targeting=True, targeting_message=Message("Left click a target tile for the fireball, or right click to cancel.", libtcod.light_cyan), damage=15, radius=3)
					item = Entity(x, y, '#', libtcod.red, "Fireball Spell", render_order=RenderOrder.ITEM, item=item_component)
				elif item_choice == 'confusion_spell':
					item_component = Item(use_function=cast_confusion, targeting=True, targeting_message=Message("Left click an enemy to confuse it, or right click to cancel.", libtcod.light_cyan))
					item = Entity(x, y, '#', libtcod.light_pink, "Confusion Spell", render_order=RenderOrder.ITEM, item=item_component)
				elif item_choice == 'sleep_spell':
					item_component = Item(use_function=cast_sleep, targeting=True, targeting_message=Message("Left click an enemy to make it fall asleep, or right click to cancel.", libtcod.light_cyan))
					item = Entity(x, y, '#', libtcod.light_azure, "Sleep Spell", render_order=RenderOrder.ITEM, item=item_component)
				elif item_choice == 'sleep_aura':
					item_component = Item(use_function=cast_sleep_aura, targeting=True, targeting_message=Message("Left click a target tile to cast the sleep aura, or right click to cancel.", libtcod.light_cyan), radius=3)
					item = Entity(x, y, '#', libtcod.light_azure, "Sleep Aura Spell", render_order=RenderOrder.ITEM, item=item_component)
				else:
					item_component = Item(use_function=cast_lightning, damage=30, maximum_range=5)
					item = Entity(x, y, '#', libtcod.blue, "Lightning Spell", render_order=RenderOrder.ITEM, item=item_component)
				entities.append(item)

		'''
Exemplo n.º 5
0
    def place_entities(self, room, entities):
        # first number indicates how many, second indicates after which dungeon level: ie [2,1] indicates starting with the first level, 2 things can spawn
        max_monsters_per_room = from_dungeon_level(
            [[1, 1], [2, 2], [3, 4], [4, 9], [5, 14]], self.dungeon_level)
        max_items_per_room = from_dungeon_level([[1, 1], [2, 7]],
                                                self.dungeon_level)

        # Get a random number of monsters
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)

        monster_chances = {
            'small':
            from_dungeon_level([[80, 1], [50, 9], [30, 11], [10, 13]],
                               self.dungeon_level),
            'medium':
            from_dungeon_level([[15, 3], [30, 5], [60, 7], [80, 12]],
                               self.dungeon_level),
            'large':
            from_dungeon_level([[10, 6], [20, 8], [30, 10]],
                               self.dungeon_level),
            'boss':
            from_dungeon_level([[5, 15]], self.dungeon_level)
            # add in 'boss' which changes its element randomly each turn
        }

        # Define chance for each type
        monster_type_chances = {
            'blank': 25,
            'fire': 25,
            'air': 25,
            'ice': 25,
            'lightning': 25,
            'earth': 25,
            'psychic': 25,
            'water': 25
        }

        item_chances = {
            'healing_potion': 50,
            # 'gold': self.dungeon_level*100,
            'dagger': 2,
            'shield': 2
            #'art_sword': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'art_shield': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'math_sword': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'math_shield': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'science_sword': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'science_shield': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'english_sword': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'english_shield': from_dungeon_level([[5, 1]], self.dungeon_level),
            #'lightning_scroll': from_dungeon_level([[25, 4]], self.dungeon_level),
            #'fireball_scroll': from_dungeon_level([[25, 6]], self.dungeon_level),
            #'confusion_scroll': from_dungeon_level([[10, 2]], self.dungeon_level)
        }

        for i in range(number_of_monsters):
            # Choose a random location in the room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                monster_choice = random_choice_from_dict(monster_chances)
                monster_type_choice = random_choice_from_dict(
                    monster_type_chances)  # Get random type of monsters

                if monster_choice == 'boss':
                    fighter_component = Fighter(hp=500,
                                                defense=10,
                                                power=30,
                                                blank_element=0,
                                                name='Corrupted Guardian',
                                                xp=1,
                                                element='blank')
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     259,
                                     libtcod.white,
                                     'Corrupted Guardian',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)

                elif monster_choice == 'small':
                    if monster_type_choice == 'blank':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    blank_element=5,
                                                    name='exto sprite',
                                                    xp=1,
                                                    element='blank')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         275,
                                         libtcod.white,
                                         'exto sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'fire':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    fire_element=10,
                                                    name='infernus sprite',
                                                    xp=1,
                                                    element='fire')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         268,
                                         libtcod.white,
                                         'infernus sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'air':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    air_element=10,
                                                    name='sonus sprite',
                                                    xp=1,
                                                    element='air')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         270,
                                         libtcod.white,
                                         'sonus sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'ice':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    ice_element=10,
                                                    name='glacius sprite',
                                                    xp=1,
                                                    element='ice')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         271,
                                         libtcod.white,
                                         'glacius sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'lightning':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    lightning_element=randint(
                                                        5, 15),
                                                    name='fara sprite',
                                                    xp=1,
                                                    element='lightning')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         272,
                                         libtcod.white,
                                         'fara sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'earth':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    earth_element=10,
                                                    name='stowne sprite',
                                                    xp=1,
                                                    element='earth')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         273,
                                         libtcod.white,
                                         'stowne sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'psychic':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    psychic_element=10,
                                                    name='hex sprite',
                                                    xp=1,
                                                    element='psychic')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         274,
                                         libtcod.white,
                                         'hex sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'water':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=0,
                                                    water_element=10,
                                                    name='vapore sprite',
                                                    xp=1,
                                                    element='water')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         269,
                                         libtcod.white,
                                         'vapore sprite',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                elif monster_choice == 'medium':
                    if monster_type_choice == 'blank':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    blank_element=10,
                                                    name='noxis pool',
                                                    xp=2,
                                                    element='blank')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         283,
                                         libtcod.white,
                                         'noxis pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'fire':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    fire_element=15,
                                                    name='magmis pool',
                                                    xp=2,
                                                    element='fire')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         276,
                                         libtcod.white,
                                         'magmis pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'air':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    air_element=15,
                                                    name='tumul pool',
                                                    xp=2,
                                                    element='air')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         278,
                                         libtcod.white,
                                         'tumul pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'ice':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    ice_element=15,
                                                    name='iglis pool',
                                                    xp=2,
                                                    element='ice')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         279,
                                         libtcod.white,
                                         'iglis pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'lightning':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    lightning_element=randint(
                                                        10, 20),
                                                    name='galva pool',
                                                    xp=2,
                                                    element='lightning')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         280,
                                         libtcod.white,
                                         'galva pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'earth':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    earth_element=15,
                                                    name='vivus pool',
                                                    xp=2,
                                                    element='earth')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         281,
                                         libtcod.white,
                                         'vivus pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'psychic':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    psychic_element=15,
                                                    name='manos pool',
                                                    xp=2,
                                                    element='psychic')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         282,
                                         libtcod.white,
                                         'manos pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'water':

                        fighter_component = Fighter(hp=50,
                                                    defense=5,
                                                    power=0,
                                                    water_element=15,
                                                    name='azure pool',
                                                    xp=2,
                                                    element='water')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         277,
                                         libtcod.white,
                                         'azure pool',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                elif monster_choice == 'large':
                    if monster_type_choice == 'blank':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=0,
                                                    blank_power=15,
                                                    name='Aeon',
                                                    xp=4,
                                                    element='blank')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         292,
                                         libtcod.white,
                                         'Aeon',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'fire':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    fire_element=20,
                                                    name='Kindra',
                                                    xp=4,
                                                    element='fire')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         284,
                                         libtcod.white,
                                         'Kindra',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'air':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    air_element=20,
                                                    name='Huricus',
                                                    xp=4,
                                                    element='air')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         286,
                                         libtcod.white,
                                         'Huricus',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'ice':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    ice_element=20,
                                                    name='Flaik',
                                                    xp=4,
                                                    element='ice')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         288,
                                         libtcod.white,
                                         'Flaik',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'lightning':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    lightning_element=randint(
                                                        20, 30),
                                                    name='Astra',
                                                    xp=4,
                                                    element='lightning')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         289,
                                         libtcod.white,
                                         'Astra',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'earth':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    earth_element=20,
                                                    name='Oria',
                                                    xp=4,
                                                    element='earth')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         290,
                                         libtcod.white,
                                         'Oria',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'psychic':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    psychic_element=20,
                                                    name='Genis',
                                                    xp=4,
                                                    element='psychic')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         291,
                                         libtcod.white,
                                         'Genis',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'water':

                        fighter_component = Fighter(hp=100,
                                                    defense=10,
                                                    power=3,
                                                    water_element=20,
                                                    name='Aquifis',
                                                    xp=4,
                                                    element='water')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         285,
                                         libtcod.white,
                                         'Aquifis',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)
                entities.append(monster)

        for i in range(number_of_items):
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                item_choice = random_choice_from_dict(item_chances)

                if item_choice == 'healing_potion':
                    item_component = Item(use_function=heal,
                                          amount=self.dungeon_level * 10)
                    item = Entity(x,
                                  y,
                                  262,
                                  libtcod.white,
                                  'Relaxing Tea + ' + str(self.dungeon_level),
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                # if item_choice == 'gold':
                # amount = self.dungeon_level*randint(3,6)*3+randint(1,10)
                # fighter_component = Fighter(hp=1, defense=-99, power=0, lightning_element=amount, name=str(amount) + ' Gold Coins', xp = 0)
                # ai_component = None
                # item = Entity(x, y, 261, libtcod.white, str(amount) + ' Gold Coins', blocks = True,
                # render_order=RenderOrder.ITEM, fighter=fighter_component, ai=ai_component)
                if item_choice == 'dagger':
                    equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                                      power_bonus=int(
                                                          self.dungeon_level))
                    item = Entity(x,
                                  y,
                                  266,
                                  libtcod.white,
                                  'Elemental Absorber + ' +
                                  str(self.dungeon_level),
                                  equippable=equippable_component)
                if item_choice == 'shield':
                    equippable_component = Equippable(
                        EquipmentSlots.OFF_HAND,
                        defense_bonus=int(self.dungeon_level),
                        max_hp_bonus=self.dungeon_level * 5)
                    item = Entity(x,
                                  y,
                                  264,
                                  libtcod.white,
                                  'Elemental Deflector + ' +
                                  str(self.dungeon_level),
                                  equippable=equippable_component)
                # elif item_choice == 'art_sword':
                # equippable_component = Equippable(EquipmentSlots.MAIN_HAND, art_power_bonus=5)
                # item = Entity(x, y, 267, libtcod.white, 'Paintbrush', equippable=equippable_component)
                # elif item_choice == 'art_shield':
                # equippable_component = Equippable(EquipmentSlots.OFF_HAND, art_defense_bonus=4)
                # item = Entity(x, y, 268, libtcod.white, 'Pallete Clipboard', equippable=equippable_component)
                # elif item_choice == 'math_sword':
                # equippable_component = Equippable(EquipmentSlots.MAIN_HAND, math_power_bonus=5)
                # item = Entity(x, y, 269, libtcod.white, 'Ruler', equippable=equippable_component)
                # elif item_choice == 'math_shield':
                # equippable_component = Equippable(EquipmentSlots.OFF_HAND, math_defense_bonus=4)
                # item = Entity(x, y, 270, libtcod.white, 'Measuring Clipboard', equippable=equippable_component)
                # elif item_choice == 'science_sword':
                # equippable_component = Equippable(EquipmentSlots.MAIN_HAND, science_power_bonus=5)
                # item = Entity(x, y, 271, libtcod.white, 'Calculator', equippable=equippable_component)
                # elif item_choice == 'science_shield':
                # equippable_component = Equippable(EquipmentSlots.OFF_HAND, science_defense_bonus=4)
                # item = Entity(x, y, 272, libtcod.white, 'Vial Clipboard', equippable=equippable_component)
                # elif item_choice == 'english_sword':
                # equippable_component = Equippable(EquipmentSlots.MAIN_HAND, english_power_bonus=5)
                # item = Entity(x, y, 273, libtcod.white, 'Dictionary', equippable=equippable_component)
                # elif item_choice == 'english_shield':
                # equippable_component = Equippable(EquipmentSlots.OFF_HAND, english_defense_bonus=4)
                # item = Entity(x, y, 274, libtcod.white, 'Report Clipboard', equippable=equippable_component)

                entities.append(item)
Exemplo n.º 6
0
def main():
    pg.init()
    screen = pg.display.set_mode(SCREEN_SIZE)
    pg.display.set_caption('2D camera test')

    clock = pg.time.Clock()

    world = World()
    camera_margin = (50, 20)
    camera = Camera2D(camera_margin, (SCREEN_WIDTH - camera_margin[0] * 2,
                                      SCREEN_HEIGHT - camera_margin[1] * 2),
                      world)
    # camera = Camera2D(Vector2(), (SCREEN_WIDTH, SCREEN_HEIGHT), world)

    dot = Entity(Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
    world.add_entity(dot)

    dot2 = Entity(Vector2(SCREEN_WIDTH / 2 + 20, SCREEN_HEIGHT / 2 + 20))
    world.add_entity(dot2)

    dot3 = Entity(Vector2())
    world.add_entity(dot3)

    player_pos = Vector2(dot.position) + Vector2(20, -30)
    player = PlayerEntity(player_pos)
    world.add_entity(player)

    dot4 = Entity(player_pos + Vector2(-50, 50))
    world.add_entity(dot4)
    dot5 = Entity(player_pos + Vector2(50, -50))
    world.add_entity(dot5)

    tile1 = tiles.GroundTileEntity(player_pos, tiles.BRICK_TILE)
    world.add_entity(tile1)

    begin = Vector2(tile1.position)
    x_offset = Vector2(tiles.TILE_SPACING, 0)
    y_offset = Vector2(0, tiles.TILE_SPACING)
    tile2 = tiles.GroundTileEntity(begin, tiles.BRICK_TILE)
    world.add_entity(tile2)
    world.add_entity(tiles.GroundTileEntity(begin + x_offset,
                                            tiles.BRICK_TILE))
    world.add_entity(
        tiles.GroundTileEntity(begin + x_offset * 2, tiles.BRICK_TILE))
    world.add_entity(
        tiles.GroundTileEntity(begin + x_offset * 2 + y_offset,
                               tiles.BRICK_TILE))

    camera.entity_follow = player

    while True:
        for event in pg.event.get():
            handle_event(event)
            camera.handle_event(event)

        seconds_passed = clock.tick(FPS) / 1000
        world.update(seconds_passed)
        camera.update(seconds_passed)
        # camera.center_on(player.position)

        screen.fill(pg.Color('black'))
        camera.render(screen)
        pg.display.update()
    def place_entities(self, room, entities):
        max_monsters_per_room = from_dungeon_level([[2, 1], [3, 4], [5, 6]],
                                                   self.dungeon_level)
        max_items_per_room = from_dungeon_level([[1, 1], [2, 4]],
                                                self.dungeon_level)

        # Get a random number of monsters
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)

        monster_chances = {
            'orc':
            80,
            'troll':
            from_dungeon_level([[15, 3], [30, 5], [60, 7]], self.dungeon_level)
        }

        item_chances = {
            'healing_potion': 35,
            'sword': from_dungeon_level([[5, 4]], self.dungeon_level),
            'shield': from_dungeon_level([[15, 8]], self.dungeon_level),
            'lightning_scroll': from_dungeon_level([[25, 4]],
                                                   self.dungeon_level),
            'fireball_scroll': from_dungeon_level([[25, 6]],
                                                  self.dungeon_level),
            'confusion_scroll': from_dungeon_level([[10, 2]],
                                                   self.dungeon_level)
        }
        for i in range(number_of_monsters):
            # choose a random location in the room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                monster_choice = random_choice_from_dict(monster_chances)

                if monster_choice == 'orc':
                    fighter_component = Fighter(hp=20,
                                                defense=0,
                                                power=4,
                                                xp=35)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.desaturated_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                else:
                    fighter_component = Fighter(hp=30,
                                                defense=2,
                                                power=8,
                                                xp=100)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'T',
                                     libtcod.darker_green,
                                     'Troll',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                entities.append(monster)

        for i in range(number_of_items):
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)
            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                item_choice = random_choice_from_dict(item_chances)

                if item_choice == 'healing_potion':
                    item_component = Item(use_function=heal, amount=40)
                    item = Entity(x,
                                  y,
                                  '!',
                                  libtcod.violet,
                                  'Healing Potion',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                elif item_choice == 'sword':
                    equipment_component = Equippable(Equipment_slots.MAIN_HAND,
                                                     power_bonus=3)
                    item = Entity(x,
                                  y,
                                  '/',
                                  libtcod.sky,
                                  'Sword',
                                  equippable=equipment_component)

                elif item_choice == 'shield':
                    equipment_component = Equippable(Equipment_slots.OFF_HAND,
                                                     defense_bonus=1)
                    item = Entity(x,
                                  y,
                                  '[',
                                  libtcod.darker_orange,
                                  'Shield',
                                  equippable=equipment_component)

                elif item_choice == 'fireball_scroll':
                    item_component = Item(
                        use_function=cast_fireball,
                        targeting=True,
                        targeting_message=Message(
                            'Left-click a target tile for the fireball, or right-click to cancel.',
                            libtcod.light_cyan),
                        damage=25,
                        radius=3)
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.red,
                                  'Fireball Scroll',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                elif item_choice == 'confusion_scroll':
                    item_component = Item(
                        use_function=cast_confuse,
                        targeting=True,
                        targeting_message=Message(
                            'Left-click an enemy to confuse it, or right-click to cancel.',
                            libtcod.light_cyan))
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.light_pink,
                                  'Confusion Scroll',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                else:
                    item_component = Item(use_function=cast_lightning,
                                          damage=40,
                                          maximum_range=5)
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.yellow,
                                  'Lightning Scroll',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                entities.append(item)
Exemplo n.º 8
0
 def test_create_symbol(self):
     entity = Entity('libfreertos.a', 'croutine',
                     'prvCheckPendingReadyList')
     self.assertEqual(Entity.Specificity.SYMBOL, entity.specificity)
Exemplo n.º 9
0
    def test_compare_different_specificity(self):
        # Different specificity: NONE < ARCHIVE < OBJ < SYMBOL
        entity_a = Entity()
        entity_b = Entity('libfreertos.a')
        self.assertLess(entity_a, entity_b)

        entity_a = Entity('libfreertos.a')
        entity_b = Entity('libfreertos.a', 'croutine')
        self.assertLess(entity_a, entity_b)

        entity_a = Entity('libfreertos.a', 'croutine')
        entity_b = Entity('libfreertos.a', 'croutine',
                          'prvCheckPendingReadyList')
        self.assertLess(entity_a, entity_b)

        entity_a = Entity(Entity.ALL)
        entity_b = Entity('libfreertos.a')
        self.assertLess(entity_a, entity_b)

        entity_a = Entity('libfreertos.a', Entity.ALL)
        entity_b = Entity('libfreertos.a', 'croutine')
        self.assertLess(entity_a, entity_b)

        entity_a = Entity('libfreertos.a', 'croutine', Entity.ALL)
        entity_b = Entity('libfreertos.a', 'croutine',
                          'prvCheckPendingReadyList')
        self.assertLess(entity_a, entity_b)
Exemplo n.º 10
0
def get_game_variables(constants):  #플레이어 능력치 선언부 player stat
    fighter_component = Fighter(hp=4000,
                                sp=100,
                                dt=0,
                                ac=10,
                                dice='1d4t',
                                power='',
                                acc='1d20t',
                                STR=1,
                                DEX=3,
                                CON=2,
                                INT=1,
                                fort=0,
                                refl=0,
                                will=0,
                                melee=1,
                                gun=1,
                                light=2,
                                dark=2,
                                tec=0,
                                lore=1,
                                xp=0,
                                lpower='',
                                dpower='',
                                luck=5)
    inventory_component = Inventory(26)
    #플레이어 char랑 컴포넌트 선언부
    level_component = Level()
    equipment_component = Equipment()
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component,
                    level=level_component,
                    equipment=equipment_component)
    entities = [player]
    #시작 장비
    equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                      base_dice='1d6t',
                                      power_bonus='0',
                                      DEX_weapon=True,
                                      luck_bonus=5,
                                      ranged_weapon=True)
    dagger = Entity(0,
                    0,
                    '-',
                    libtcod.sky,
                    '경쇠뇌',
                    equippable=equippable_component)
    player.inventory.add_item(dagger)
    player.equipment.toggle_equip(dagger)

    game_map = GameMap(constants['map_width'], constants['map_height'])
    game_map.make_map(constants['max_rooms'], constants['room_min_size'],
                      constants['room_max_size'], constants['map_width'],
                      constants['map_height'], player, entities)

    #camera
    camera = Camera(
        x=0,
        y=0,
        width=constants['screen_width'],
        height=constants['screen_height'],
        map_width=constants['map_width'],
        map_height=constants['map_height'],
    )
    camera.update(player)

    message_log = MessageLog(constants['message_x'],
                             constants['message_width'],
                             constants['message_height'])

    game_state = GameStates.PLAYERS_TURN

    return player, entities, game_map, message_log, game_state
Exemplo n.º 11
0
def get_game_variables(constants, names_list, colors_list):

    #Build player entity
    fighter_component = Fighter(hp=100, defense=0, power=1, speed=5)
    inventory_component = Inventory(24)
    level_component = Level()
    equipment_component = Equipment()
    player = Entity(0,
                    0,
                    256,
                    libtcod.white,
                    "Player",
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component,
                    level=level_component,
                    equipment=equipment_component)
    player.character_name = constants['player_name']
    entities = [player]

    #Starting Inventory, sprite
    origin = constants['options_origin']

    #HEKIN QUIVER
    item_component = Item(use_function=use_quiver,
                          stackable=False,
                          flammable=True,
                          description="A quiver for storing arrows.",
                          effect="Firing preference is currently unassigned.")
    item = Entity(0,
                  0,
                  394,
                  colors_list[names_list['Quiver']],
                  'Quiver',
                  item=item_component)
    player.inventory.items.append(item)

    if origin == "Adventurer":
        player.char = 256

        #sword
        item_component = Item(use_function=None,
                              stackable=False,
                              description="A short, one-handed sword.")
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=3)
        item = Entity(0,
                      0,
                      369,
                      colors_list[names_list['Sword']],
                      'Sword',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #shield
        item_component = Item(use_function=None,
                              stackable=False,
                              description="A small, round, metal shield.")
        equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                          defense_bonus=1)
        item = Entity(0,
                      0,
                      375,
                      colors_list[names_list['Shield']],
                      'Shield',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #10 gold
        item_component = Item(
            use_function=None,
            stackable=True,
            count=20,
            description=
            "Yanno, gold coins! For procuring goods and/or services!")
        item = Entity(0,
                      0,
                      365,
                      colors_list[names_list['Gold']],
                      'Gold',
                      render_order=RenderOrder.ITEM,
                      item=item_component)
        player.inventory.add_item(item, names_list)
        player.gold_collected = 20

    elif origin == "Ranger":
        player.char = 258

        #3x Pos. Arrow
        hit_component = PoisonShot(2, 1, 10)
        ammo_component = Ammo(hit_function=hit_component, retrievable=True)
        item_component = Item(use_function=use_arrow(),
                              stackable=True,
                              count=3,
                              ammo=ammo_component,
                              flammable=True,
                              range=0,
                              description="Poison-coated arrow. Icky!")
        item = Entity(0,
                      0,
                      378,
                      colors_list[names_list['Arrow']],
                      'Poison Arrow',
                      item=item_component)
        player.inventory.items.append(item)

        #10x. Arrow
        hit_component = BasicShot(2)
        ammo_component = Ammo(hit_function=hit_component, retrievable=True)
        item_component = Item(use_function=None,
                              stackable=True,
                              count=10,
                              ammo=ammo_component,
                              flammable=True,
                              range=0,
                              description="Arrow. Pewpew!")
        item = Entity(0,
                      0,
                      378,
                      colors_list[names_list['Arrow']],
                      'Arrow',
                      item=item_component)
        player.inventory.items.append(item)

        #Bow
        item_component = Item(use_function=None,
                              stackable=False,
                              flammable=True,
                              ammo=["Arrow", "Poison Arrow"],
                              range=5,
                              description="A small, low-range bow.")
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=0)
        item = Entity(0,
                      0,
                      377,
                      colors_list[names_list['Short Bow']],
                      'Short Bow',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

    elif origin == "Merchant":
        player.char = 260
        #staff
        item_component = Item(
            use_function=None,
            stackable=False,
            description=
            "A two-handed (but actually one-handed) wooden staff, perfect for whacking things with."
        )
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(0,
                      0,
                      372,
                      libtcod.sky,
                      'Staff',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #merchants bag
        item_component = Item(
            use_function=None,
            stackable=False,
            description=
            "A large leather satchel with many pockets and reinforced compartments.",
            effect="Increases carrying capacity by 24.")
        equippable_component = Equippable(EquipmentSlots.ACC1,
                                          capacity_bonus=24)
        item = Entity(0,
                      0,
                      364,
                      libtcod.darker_orange,
                      'Merchants Bag',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #100 gold
        item_component = Item(
            use_function=None,
            stackable=True,
            count=100,
            description=
            "Yanno, gold coins! For procuring goods and/or services!")
        item = Entity(0,
                      0,
                      365,
                      libtcod.dark_yellow,
                      'Gold',
                      render_order=RenderOrder.ITEM,
                      item=item_component)
        player.inventory.add_item(item, names_list)
        player.gold_collected = 100

    elif origin == "Criminal":
        player.char = 262
        #dagger
        item_component = Item(
            use_function=None,
            stackable=False,
            description="A small, rusty dagger. Probably unsafe to handle.",
            effect="This thing was made for doing stabs.")
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=2)
        item = Entity(0,
                      0,
                      368,
                      libtcod.sky,
                      'Dagger',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #fingerless gloves
        item_component = Item(
            use_function=None,
            stackable=False,
            description=
            "These definitely had fingers when they were made, but they don't now.",
            effect="Increases speed by 3")
        equippable_component = Equippable(EquipmentSlots.ACC1, speed_bonus=3)
        item = Entity(0,
                      0,
                      382,
                      libtcod.darker_orange,
                      'Fingerless Gloves',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #30 gold
        item_component = Item(
            use_function=None,
            stackable=True,
            count=30,
            description=
            "Yanno, gold coins! For procuring goods and/or services!")
        item = Entity(0,
                      0,
                      365,
                      libtcod.dark_yellow,
                      'Gold',
                      render_order=RenderOrder.ITEM,
                      item=item_component)
        player.inventory.add_item(item, names_list)
        player.gold_collected = 30

    elif origin == "Tourist":
        player.char = 264
        #cargo shorts
        item_component = Item(
            use_function=None,
            stackable=False,
            description=
            "These are more pockets than they are shorts, which you're ok with.",
            effect="Increases carrying capacity by 8.")
        equippable_component = Equippable(EquipmentSlots.ACC1,
                                          capacity_bonus=8)
        item = Entity(0,
                      0,
                      395,
                      libtcod.darker_orange,
                      'Cargo Shorts',
                      equippable=equippable_component,
                      item=item_component)
        player.equipment.list.append(item)

        #10 gold
        item_component = Item(
            use_function=None,
            stackable=True,
            count=10,
            description=
            "Yanno, gold coins! For procuring goods and/or services!")
        item = Entity(0,
                      0,
                      365,
                      libtcod.dark_yellow,
                      'Gold',
                      render_order=RenderOrder.ITEM,
                      item=item_component)
        player.inventory.add_item(item, names_list)
        player.gold_collected = 10

    game_map = GameMap(constants['map_width'], constants['map_height'])
    game_map.make_map(constants['max_rooms'], constants['room_min_size'],
                      constants['room_max_size'], constants['map_width'],
                      constants['map_height'], player, entities, names_list,
                      colors_list)

    message_log = MessageLog(constants['message_x'],
                             constants['message_width'],
                             constants['message_height'])

    game_state = GameStates.PLAYERS_TURN

    return player, entities, game_map, message_log, game_state
Exemplo n.º 12
0
def get_club_choices(item_choice, wp_en, x, y, disp_name):
    item = None
    if item_choice == 'Wooden Club' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=3)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Mace' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Warhammer' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Morning Star' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Spiked Flail' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Giant Club' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Auger' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)
    elif item_choice == 'Mjolnir' + wp_en:
        equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                          power_bonus=1)
        item = Entity(x,
                      y,
                      '!',
                      libtcod.black,
                      disp_name,
                      equippable=equippable_component)

    return item
Exemplo n.º 13
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10
    max_monsters_per_room = 3

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    player = Entity(0, 0, '@', libtcod.white)
    entities = [player]
    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)
    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room)

    fov_recompute = True
    fov_map = initialize_fov(game_map)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(con, entities, game_map, fov_map, fov_recompute,
                   screen_width, screen_height, colors)
        fov_recompute = False
        libtcod.console_flush()
        clear_all(con, entities)

        action = handle_keys(key)
        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move
            if not game_map.is_blocked(player.x + dx, player.y + dy):
                player.move(dx, dy)
                fov_recompute = True
        if exit:
            return True
        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
Exemplo n.º 14
0
def main():
    """
    The main game process
    """

    # these variables will define the dimensions of the console and map
    screen_width = 80
    screen_height = 50

    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    map_width = 80
    map_height = 43

    # configure the number of rooms per map and their sizes
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3

    # set the colours for the map blocks
    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    # create entity objects for the player and an NPC, then poke them in
    # an array
    fighter_component = Fighter(hp=30, defense=2, power=5)
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    "Player",
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component)
    entities = [player]

    # set the default font and colour values for the console
    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    # move the console into a variable so that we can manipulate it a bit better
    con = libtcod.console_new(screen_width, screen_height)
    panel = libtcod.console_new(screen_width, panel_height)

    # create the object which contains the map
    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    # listen for the most recent Keyboard and Mouse events
    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN

    # main game loop, will continue looping until some action closes the window
    while not libtcod.console_is_window_closed():
        # check to see which events were received from the inputs
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        # compute the field of view values for the player
        if fov_recompute:
            recompute_fov(fov_map, player.position_x, player.position_y,
                          fov_radius, fov_light_walls, fov_algorithm)

        # main rendering command - calculates and paints the various elements
        # appearing in the console
        render_all(con, panel, entities, player, game_map, fov_map,
                   fov_recompute, message_log, screen_width, screen_height,
                   bar_width, panel_height, panel_y, mouse, colors)

        fov_recompute = False

        # flush the contents of the console to the screen
        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.position_x + dx
            destination_y = player.position_y + dy
            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        # If the exit signal is received, close the game
        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                message_log.add_message(message)

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYERS_TURN
Exemplo n.º 15
0
def main():
    constants = get_constants()

    libtcod.console_set_custom_font(
        'tiledfont.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD, 32, 10)

    libtcod.console_init_root(constants['screen_width'],
                              constants['screen_height'],
                              constants['window_title'], False)

    # load the custom font rows
    load_customfont()

    # assign the custom font rows numbers to text (for easier calling when defining entities with custom tiles)
    # defining tiles (rather than numbers)
    wall_tile = 257  #note: see render_functions for where the wall and floor tiles are defined, these are not used.
    floor_tile = 256
    player_tile = 258
    quiz_tile = 259
    exam_tile = 260
    healingpotion_tile = 261
    sword_tile = 263
    shield_tile = 264
    stairsdown_tile = 265
    dagger_tile = 266

    fighter_component = Fighter(hp=30, defense=1, power=3, name='Guardian')
    inventory_component = Inventory(8)
    level_component = Level()
    equipment_component = Equipment()
    player = Entity(0,
                    0,
                    player_tile,
                    libtcod.white,
                    'Guardian',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component,
                    level=level_component,
                    equipment=equipment_component)
    entities = [player]

    equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=1)
    dagger = Entity(0,
                    0,
                    dagger_tile,
                    libtcod.white,
                    'Elemental Absorber + 1',
                    equippable=equippable_component)
    player.inventory.add_item(dagger)
    player.equipment.toggle_equip(dagger)

    equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                      max_hp_bonus=5,
                                      defense_bonus=0)
    shield = Entity(0,
                    0,
                    shield_tile,
                    libtcod.white,
                    'Elemental Deflector + 0',
                    equippable=equippable_component)
    player.inventory.add_item(shield)
    player.equipment.toggle_equip(shield)
    player.fighter.hp += shield.equippable.max_hp_bonus

    con = libtcod.console.Console(constants['screen_width'],
                                  constants['screen_height'])
    panel = libtcod.console.Console(constants['screen_width'],
                                    constants['panel_height'])

    game_map = GameMap(constants['map_width'], constants['map_height'])
    game_map.make_map(constants['max_rooms'], constants['room_min_size'],
                      constants['room_max_size'], constants['map_width'],
                      constants['map_height'], player, entities)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(constants['message_x'],
                             constants['message_width'],
                             constants['message_height'])

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN
    previous_game_state = game_state

    # Welcome the player
    message_log.add_message(
        Message(
            'Welcome, Guardian, to the elemental kingdom of Empyria! Aquire all the elements...or die trying! Fearsome foes await in the deepest depths of Empyria, where many Guardians have disappeared...',
            libtcod.white))

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, constants['fov_radius'],
                          constants['fov_light_walls'],
                          constants['fov_algorithm'])

        render_all(con, panel, entities, player, game_map, fov_map,
                   fov_recompute, message_log, constants['screen_width'],
                   constants['screen_height'], constants['bar_width'],
                   constants['panel_height'], constants['panel_y'], mouse,
                   constants['colors'], game_state)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key, game_state)

        move = action.get('move')
        pickup = action.get('pickup')
        show_inventory = action.get('show_inventory')
        drop_inventory = action.get('drop_inventory')
        inventory_index = action.get('inventory_index')
        take_stairs = action.get('take_stairs')
        level_up = action.get('level_up')
        show_character_screen = action.get('show_character_screen')
        wait = action.get('wait')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                    fov_recompute = True
                else:
                    player.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        elif pickup and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickup_results = player.inventory.add_item(entity)
                    player_turn_results.extend(pickup_results)

                    break

            else:
                message_log.add_message(
                    Message('There is nothing here to pick up.',
                            libtcod.yellow))

        if show_inventory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        if drop_inventory:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(
                player.inventory.items):
            item = player.inventory.items[inventory_index]

            if game_state == GameStates.SHOW_INVENTORY:
                player_turn_results.extend(player.inventory.use(item))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(player.inventory.drop_item(item))

        if take_stairs and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.stairs and entity.x == player.x and entity.y == player.y:
                    entities = game_map.next_floor(player, message_log,
                                                   constants)
                    fov_map = initialize_fov(game_map)
                    fov_recompute = True
                    con.clear()

                    break
            else:
                message_log.add_message(
                    Message(
                        'You search around, but the stairs are nowhere to be seen.',
                        libtcod.yellow))

        if level_up:
            if level_up == 'hp':
                player.fighter.base_max_hp += 30
                player.fighter.hp += 30
            elif level_up == 'str':
                player.fighter.base_power += 5
            elif level_up == 'def':
                player.fighter.base_defense += 1

            game_state = previous_game_state

        if show_character_screen:
            previous_game_state = game_state
            game_state = GameStates.CHARACTER_SCREEN

        if wait == True:
            game_state = GameStates.ENEMY_TURN
            fov_recompute = True

        if exit:
            if game_state in (GameStates.SHOW_INVENTORY,
                              GameStates.DROP_INVENTORY,
                              GameStates.CHARACTER_SCREEN):
                game_state = previous_game_state
            else:
                return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')
            item_consumed = player_turn_result.get('consumed')
            item_pick_gold = player_turn_result.get('got_gold')
            item_dropped = player_turn_result.get('item_dropped')
            equip = player_turn_result.get('equip')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    # Using xp to increase player's stats, "absorbing" the element
                    if dead_entity.fighter.name == 'Corrupted Guardian':
                        previous_game_state = game_state
                        game_state = GameStates.WIN
                        message_log.add_message(
                            Message(
                                'You have brought peace to Empyria and vanquished the Corrputed Guardian! Congratulations!',
                                libtcod.yellow))

                    if dead_entity.fighter.element == 'blank':
                        player.fighter.blank_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.blank_element > player.fighter.max_blank_element:
                            player.fighter.blank_element = player.fighter.max_blank_element
                    elif dead_entity.fighter.element == 'fire':
                        player.fighter.fire_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.fire_element > player.fighter.max_fire_element:
                            player.fighter.fire_element = player.fighter.max_fire_element
                    elif dead_entity.fighter.element == 'air':
                        player.fighter.air_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.air_element > player.fighter.max_air_element:
                            player.fighter.air_element = player.fighter.max_air_element
                    elif dead_entity.fighter.element == 'ice':
                        player.fighter.ice_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.ice_element > player.fighter.max_ice_element:
                            player.fighter.ice_element = player.fighter.max_ice_element
                    elif dead_entity.fighter.element == 'lightning':
                        player.fighter.lightning_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.lightning_element > player.fighter.max_lightning_element:
                            player.fighter.lightning_element = player.fighter.max_lightning_element
                    elif dead_entity.fighter.element == 'earth':
                        player.fighter.earth_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.earth_element > player.fighter.max_earth_element:
                            player.fighter.earth_element = player.fighter.max_earth_element
                    elif dead_entity.fighter.element == 'psychic':
                        player.fighter.psychic_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.psychic_element > player.fighter.max_psychic_element:
                            player.fighter.psychic_element = player.fighter.max_psychic_element
                    elif dead_entity.fighter.element == 'water':
                        player.fighter.water_element += dead_entity.fighter.xp
                        message = kill_monster(dead_entity)
                        if player.fighter.water_element > player.fighter.max_water_element:
                            player.fighter.water_element = player.fighter.max_water_element

                message_log.add_message(message)

            if item_added:
                entities.remove(item_added)

                game_state = GameStates.ENEMY_TURN

            if item_consumed:
                game_state = GameStates.ENEMY_TURN

            # if item_pick_gold:
            # entities.remove(item_gold)

            # game_state = GameStates.ENEMY_TURN

            if item_dropped:
                entities.append(item_dropped)

                game_state = GameStates.ENEMY_TURN

            if equip:
                equip_results = player.equipment.toggle_equip(equip)

                for equip_result in equip_results:
                    equipped = equip_result.get('equipped')
                    dequipped = equip_result.get('dequipped')

                    if equipped:
                        message_log.add_message(
                            Message('You equipped the {0}.'.format(
                                equipped.name)))

                    if dequipped:
                        message_log.add_message(
                            Message('You dequipped the {0}.'.format(
                                dequipped.name)))

                game_state = GameStates.ENEMY_TURN

            xp = player_turn_result.get('xp')

            if xp:
                # if not GameStates.WIN:
                leveled_up = player.level.add_xp(xp)
                message_log.add_message(
                    Message('You gained {0} exp!'.format(xp)))
                if (player.fighter.blank_element
                        == player.fighter.max_blank_element
                        and player.fighter.fire_element
                        == player.fighter.max_fire_element
                        and player.fighter.air_element
                        == player.fighter.max_air_element
                        and player.fighter.ice_element
                        == player.fighter.max_ice_element
                        and player.fighter.lightning_element
                        == player.fighter.max_lightning_element
                        and player.fighter.earth_element
                        == player.fighter.max_earth_element
                        and player.fighter.psychic_element
                        == player.fighter.max_psychic_element
                        and player.fighter.water_element
                        == player.fighter.max_water_element):
                    message_log.add_message(
                        Message(
                            'You have collected all of the elements and are now a true Elemental Guardian! You won! Or did you...?',
                            libtcod.yellow))

                if leveled_up:

                    # if player.level.current_level == 5:
                    # previous_game_state = game_state
                    # game_state = GameStates.WIN
                    # message_log.add_message(Message('You have collected 180 exp! You won!', libtcod.yellow))
                    # else:
                    message_log.add_message(
                        Message(
                            'Level up! You are now level {0}'.format(
                                player.level.current_level) + '!',
                            libtcod.yellow))
                    previous_game_state = game_state
                    game_state = GameStates.LEVEL_UP

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                    if game_state == GameStates.PLAYER_DEAD:
                        break

            else:
                game_state = GameStates.PLAYERS_TURN

            fov_recompute = True
Exemplo n.º 16
0
def get_item(name, x, y):
    if name == 'Healing Potion':
        item_comp = Item(use_function=heal, amount=4)

        return Entity('Healing Potion',
                      x,
                      y,
                      '!',
                      libtcod.violet,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      item=item_comp)

    if name == 'ZAP':
        item_comp = Item(use_function=auto_aim_zap, damage=4, max_range=5)

        return Entity('ZAP',
                      x,
                      y,
                      'z',
                      libtcod.yellow,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      item=item_comp)

    if name == 'Wrist-mounted rocket launcher':
        item_comp = Item(
            use_function=guided_rocket,
            targeting=True,
            targeting_message=Message(
                'Left-click a target to fire, right-click to cancel',
                libtcod.light_cyan),
            damage=20,
            damage_radius=2)

        return Entity('Wrist-mounted rocket launcher',
                      x,
                      y,
                      'w',
                      libtcod.orange,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      item=item_comp)

    if name == 'Teleporting bomb':
        item_comp = Item(
            use_function=teleporting_bomb,
            targeting=True,
            targeting_message=Message(
                'Left-click a target to fire, right-click to cancel',
                libtcod.light_cyan),
            damage=10,
            damage_radius=2)

        return Entity('Teleporting bomb',
                      x,
                      y,
                      't',
                      libtcod.light_blue,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      item=item_comp)

    if name == 'Confuser':
        item_comp = Item(use_function=confuse,
                         targeting=True,
                         targeting_message=Message(
                             'Left-click a target, right-click to cancel',
                             libtcod.light_cyan))

        return Entity('Confuser',
                      x,
                      y,
                      'c',
                      libtcod.violet,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      item=item_comp)

    if name == 'Hammer':
        equippable_comp = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=1)
        return Entity('Hammer',
                      x,
                      y,
                      'h',
                      libtcod.brass,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      equippable=equippable_comp)

    if name == 'Crowbar':
        equippable_comp = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=2)
        return Entity('Crowbar',
                      x,
                      y,
                      'f',
                      libtcod.red,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      equippable=equippable_comp)

    if name == 'Parabola':
        equippable_comp = Equippable(EquipmentSlots.OFF_HAND, defense_bonus=2)
        return Entity('Parabola',
                      x,
                      y,
                      'O',
                      libtcod.white,
                      blocks=False,
                      render_order=RenderOrder.ITEM,
                      equippable=equippable_comp)

    return None
Exemplo n.º 17
0
def place_entities(x, y, game_map, area_width, area_height,
                   max_monsters_per_area, max_items_per_area):
    number_of_monsters = randint(0, max_monsters_per_area)
    number_of_items = randint(0, max_items_per_area)

    for i in range(number_of_monsters):
        mx = randint(x + 1, x + area_width - 1)
        my = randint(y + 1, y + area_height - 1)

        if ((mx, my) not in game_map.entities
                or (mx, my) not in game_map.terrain):
            if randint(0, 100) < 80:
                fighter_component = Fighter(hp=10, defense=0, power=3)
                ai_component = BasicMonster()
                fov_component = Fov(game_map, radius=7)
                Entity(mx,
                       my,
                       'z',
                       'Zombie',
                       'green',
                       game_map.entities,
                       fighter=fighter_component,
                       ai=ai_component,
                       fov=fov_component)
            else:
                fighter_component = Fighter(hp=16, defense=1, power=4)
                ai_component = BasicMonster()
                fov_component = Fov(game_map, radius=9)
                Entity(mx,
                       my,
                       'r',
                       'Robot',
                       'red',
                       game_map.entities,
                       fighter=fighter_component,
                       ai=ai_component,
                       fov=fov_component)

    for i in range(number_of_items):
        mx = randint(x + 1, x + area_width - 1)
        my = randint(y + 1, y + area_height - 1)

        if ((mx, my) not in game_map.entities
                and (mx, my) not in game_map.terrain
                and (mx, my) not in game_map.items):
            item_chance = randint(0, 100)
            if item_chance < 5:
                item_component = Item(use_function=heal, amount=4)
                Entity(mx,
                       my,
                       '!',
                       'Healing potion',
                       'violet',
                       game_map.items,
                       item=item_component)
            elif item_chance < 10:
                item_component = Item(
                    use_function=cast_fireball,
                    targeting=True,
                    targeting_message=
                    '''Left-click a target tile for the fireball,
                                      or right-click to cancel.''',
                    damage=20,
                    radius=3)
                Entity(mx,
                       my,
                       '#',
                       'Fireball Scroll',
                       'red',
                       game_map.items,
                       item=item_component)

            elif item_chance < 20:
                equippable_component = Equippable(EquipmentSlots.RIGHT_HAND,
                                                  power_bonus=3)
                Entity(mx,
                       my,
                       '/',
                       'Sword',
                       'blue',
                       game_map.items,
                       equippable=equippable_component)

            elif item_chance < 30:
                equippable_component = Equippable(EquipmentSlots.LEFT_HAND,
                                                  defense_bonus=3)
                Entity(mx,
                       my,
                       '[',
                       'Shield',
                       'brown',
                       game_map.items,
                       equippable=equippable_component)

            elif item_chance < 95:
                item_component = Item(
                    use_function=cast_confuse,
                    targeting=True,
                    targeting_message=
                    '''Left-click a target tile for the fireball,
                                      or right-click to cancel.''')
                Entity(mx,
                       my,
                       '#',
                       'Confuse Scroll',
                       'pink',
                       game_map.items,
                       item=item_component)

            else:
                item_component = Item(use_function=cast_lightning,
                                      damage=20,
                                      maximum_range=5)
                Entity(mx,
                       my,
                       '#',
                       'Scroll',
                       'cyan',
                       game_map.items,
                       item=item_component)
Exemplo n.º 18
0
 def __init__(self):
     self.entity = Entity()
Exemplo n.º 19
0
def main():

    #----------------------------------------------------------------------------------
    fighterComponent = Fighter(hp=30, defense=2, power=5)
    inventoryComponent = Inventory(26)
    player = Entity(0,
                    0,
                    '@',
                    tcod.white,
                    'Player',
                    blocks=True,
                    rOrder=renderOrder.actor,
                    fighter=fighterComponent,
                    inventory=inventoryComponent)
    entities = [player]
    #----------------------------------------------------------------------------------

    tcod.console_set_custom_font(
        Config.FONT, tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
    tcod.console_init_root(Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT,
                           Config.TITLE, False)

    con = tcod.console_new(Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT)
    panel = tcod.console_new(Config.SCREEN_WIDTH, Config.PANEL_HEIGHT)

    map = gameMap(Config.MAP_WIDTH, Config.MAP_HEIGHT)
    map.makeMap(Config.MAX_ROOMS, Config.ROOM_MIN_SIZE, Config.ROOM_MAX_SIZE,
                Config.MAP_WIDTH, Config.MAP_HEIGHT, player, entities,
                Config.MAX_MONSTERS_PER_ROOM, Config.MAX_ITEMS_PER_ROOM)
    fovRecompute = True
    fovMap = initializeFOV(map)

    messageLog = MessageLog(Config.MESSAGE_X, Config.MESSAGE_WIDTH,
                            Config.MESSAGE_HEIGHT)

    key = tcod.Key()
    mouse = tcod.Mouse()

    gameState = gameStates.PLAYERS_TURN
    previousGameState = gameState

    #----------------------------------------------------------------------------------

    while not tcod.console_is_window_closed():

        tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key,
                                 mouse)

        if fovRecompute:
            recomputeFOV(fovMap, player.x, player.y, Config.FOV_RADIUS,
                         Config.FOV_LIGHT_WALLS, Config.FOV_ALGORITHM)

        renderAll(con, panel, entities, player, map, fovMap, fovRecompute,
                  messageLog, Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT,
                  Config.BAR_WIDTH, Config.PANEL_HEIGHT, Config.PANEL_Y, mouse,
                  Config.COLORS, gameState)

        fovRecompute = False

        tcod.console_flush()

        clearAll(con, entities)

        #----------------------------------------------------------------------------------

        action = handleKeys(key, gameState)

        move = action.get('move')
        pickup = action.get('pickup')
        showInventory = action.get('showInventory')
        inventoryIndex = action.get('inventoryIndex')

        EXIT = action.get('EXIT')
        FULLSCREEN = action.get('FULLSCREEN')

        playerTurnResults = []

        if move and gameState == gameStates.PLAYERS_TURN:
            dx, dy = move
            destinationX = player.x + dx
            destinationY = player.y + dy

            if not map.isBlocked(destinationX, destinationY):
                target = getBlockingEntities(entities, destinationX,
                                             destinationY)
                if target:
                    attackResults = player.fighter.attack(target)
                    playerTurnResults.extend(attackResults)
                else:
                    player.move(dx, dy)
                    fovRecompute = True
                gameState = gameStates.ENEMY_TURN

        elif pickup and gameState == gameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickupResults = player.inventory.addItem(entity)
                    playerTurnResults.extend(pickupResults)
                    break
            else:
                messageLog.addMessage(
                    Message('There is nothing to pickup', tcod.yellow))

        if showInventory:
            previousGameState = gameState
            gameState = gameStates.SHOW_INVENTORY

        if inventoryIndex is not None and previousGameState != gameStates.PLAYER_DEAD and \
           inventoryIndex < len(player.inventory.items):
            item = player.inventory.items[inventoryIndex]
            playerTurnResults.extend(player.inventory.use(item))

        #----------------------------------------------------------------------------------

        if EXIT:
            if gameState == gameStates.SHOW_INVENTORY:
                gameState = previousGameState
            else:
                return True

        if FULLSCREEN:
            tcod.console_set_fullscreen(not tcod.console_is_fullscreen())

        #----------------------------------------------------------------------------------

        for playerTurnResult in playerTurnResults:
            message = playerTurnResult.get('message')
            deadEntity = playerTurnResult.get('dead')
            itemAdded = playerTurnResult.get('itemAdded')
            itemConsumed = playerTurnResult.get('consumed')

            if message:
                messageLog.addMessage(message)
            if deadEntity:
                if deadEntity == player:
                    message, gameState = killPlayer(deadEntity)
                else:
                    message = killMonster(deadEntity)
                messageLog.addMessage(message)
            if itemAdded:
                entities.remove(itemAdded)
                gameState = gameStates.ENEMY_TURN
            if itemConsumed:
                gameState = gameStates.ENEMY_TURN
        #----------------------------------------------------------------------------------

        if gameState == gameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemyTurnResults = entity.ai.takeTurn(
                        player, fovMap, map, entities)

                    for enemyTurnResult in enemyTurnResults:
                        message = enemyTurnResult.get('message')
                        deadEntity = enemyTurnResult.get('dead')

                        if message:
                            messageLog.addMessage(message)
                        if deadEntity:
                            if deadEntity == player:
                                message, gameState = killPlayer(deadEntity)
                            else:
                                message = killMonster(deadEntity)
                            messageLog.addMessage(message)

                            if gameState == gameStates.PLAYER_DEAD:
                                break

                    if gameState == gameStates.PLAYER_DEAD:
                        break
            else:
                gameState = gameStates.PLAYERS_TURN
Exemplo n.º 20
0
def make_map(game_map, max_rooms, room_min_size, room_max_size, map_width,
             map_height, player, entities, colors):
    rooms = []
    num_rooms = 0

    center_of_last_room_x = None
    center_of_last_room_y = None

    for r in range(max_rooms):
        # random width and height
        w = randint(room_min_size, room_max_size)
        h = randint(room_min_size, room_max_size)
        # random position withut going outside bounds of the map
        x = randint(0, map_width - w - 1)
        y = randint(0, map_height - h - 1)

        # "Rect" class makes rectangles easier to work with
        new_room = Rect(x, y, w, h)

        # run through other rooms and see if intersection occurs
        for other_room in rooms:
            if new_room.intersect(other_room):
                break
        else:
            # no intersections

            # 'paint' to map's tiles
            create_room(game_map, new_room)

            # center coordinates of new room
            (new_x, new_y) = new_room.center()

            center_of_last_room_x = new_x
            center_of_last_room_y = new_y

            if num_rooms == 0:
                #this is the first room, where the player starts
                player.x = new_x
                player.y = new_y
            else:
                # all rooms after first
                # connect to previous room with tunnel

                # center coordinates of previous room
                (prev_x, prev_y) = rooms[num_rooms - 1].center()

                # flip a coin (random number that is either 0 or 1)
                if randint(0, 1) == 1:
                    # first move horizontally, then vertically
                    create_h_tunnel(game_map, prev_x, new_x, prev_y)
                    create_v_tunnel(game_map, prev_y, new_y, new_x)
                else:
                    # first move vertically, then horizontally
                    create_v_tunnel(game_map, prev_y, new_y, prev_x)
                    create_h_tunnel(game_map, prev_x, new_x, new_y)

            place_entities(new_room, entities, game_map.dungeon_level, colors)

            #finally, append new room to the list
            rooms.append(new_room)
            num_rooms += 1
    stairs_component = Stairs(game_map.dungeon_level + 1)
    down_stairs = Entity(center_of_last_room_x,
                         center_of_last_room_y,
                         '>', (255, 255, 255),
                         'Stairs',
                         render_order=RenderOrder.STAIRS,
                         stairs=stairs_component)
    entities.append(down_stairs)
Exemplo n.º 21
0
    def place_entities(self, room, entities, max_monsters_per_room,
                       max_items_per_room):
        # Get a random number of monsters
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)

        for i in range(number_of_items):
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                item_component = Item()

                item = Entity(x,
                              y,
                              '!',
                              libtcod.violet,
                              'Healing Potion',
                              render_order=RenderOrder.ITEM,
                              item=item_component)
                entities.append(item)

        for i in range(number_of_monsters):
            # Choose a random location in the room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            # Check if an entity is already in that location
            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                if randint(0, 100) < 80:
                    fighter_component = Fighter(hp=10, defense=0, power=3)
                    ai_component = BasicMonster()

                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.desaturated_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                else:
                    fighter_component = Fighter(hp=16, defense=1, power=4)
                    ai_component = BasicMonster()

                    monster = Entity(x,
                                     y,
                                     'T',
                                     libtcod.darker_green,
                                     'Troll',
                                     blocks=True,
                                     fighter=fighter_component,
                                     render_order=RenderOrder.ACTOR,
                                     ai=ai_component)

                entities.append(monster)
Exemplo n.º 22
0
def get_game_variables(constants):
    inventory_component = Inventory(20)
    starting_level = 5
    level_component = Level(current_level=starting_level)
    equipment_componet = Equipment()
    fighter_component = fighter(hp=starting_level * constants['hp_per_level'],
                                defense=0,
                                power=starting_level *
                                constants['power_per_level'])
    spellcaster_component = spellcaster(mp=starting_level *
                                        constants['mp_per_level'],
                                        casterl=starting_level)
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component,
                    level=level_component,
                    equipment=equipment_componet,
                    spellcaster=spellcaster_component)
    cursor = Entity(0,
                    0,
                    'X',
                    libtcod.yellow,
                    'Cursor',
                    blocks=False,
                    render_order=RenderOrder.CURSOR,
                    visible=False)
    entities = [player, cursor]
    equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=5)
    fsword = Entity(0,
                    0,
                    '/',
                    libtcod.red,
                    'Flaming Sword',
                    render_order=RenderOrder.ITEM,
                    equippable=equippable_component)
    equippable_component = Equippable(EquipmentSlots.OFF_HAND, defense_bonus=4)
    mshield = Entity(0,
                     0,
                     '[',
                     libtcod.white,
                     'Mirror Shield',
                     render_order=RenderOrder.ITEM,
                     equippable=equippable_component)
    equippable_component = Equippable(EquipmentSlots.ARMOR, defense_bonus=6)
    parmor = Entity(0,
                    0,
                    '[',
                    libtcod.light_gray,
                    'Plate Armor',
                    render_order=RenderOrder.ITEM,
                    equippable=equippable_component)

    player.inventory.add_item(fsword)
    player.equipment.toggle_equip(fsword)
    player.inventory.add_item(mshield)
    player.equipment.toggle_equip(mshield)
    player.inventory.add_item(parmor)
    player.equipment.toggle_equip(parmor)

    game_map = Map(constants['map_width'], constants['map_height'])
    game_map.make_map(constants['max_rooms'], constants['room_min_size'],
                      constants['room_max_size'], constants['map_width'],
                      constants['map_height'], player, entities,
                      constants['top_level'])
    game_state = GameStates.PLAYERS_TURN

    message_log = MessageLog(constants['message_x'],
                             constants['message_width'],
                             constants['message_height'])
    floor = 0
    highest_floor = 0
    levellist = {10000: [0, 0]}
    floorentities = {10000: [0, 0]}
    dstairxy = {10000: [0, 0]}
    ustairxy = {10000: [0, 0]}
    return player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor
Exemplo n.º 23
0
def main():
    print("Start")
    # blt.set("window: size=80x25, cellsize=auto;""input : filter={keyboard}")
    blt.color("white")
    fighter_component = Fighter(hp=30, defense=3, power=5)

    player = Entity(
        27,
        27,
        '[U+1090]',
        'white',
        'player',
        fighter=fighter_component)
    health_potion = Entity(
        25,
        25,
        '[U+7012]',
        'green',
        'healing')
    print("Generating map")
    start = time.time()
    entities = dict()
    items = dict()
    corpses = dict()

    game_map = GameMap(0, 0)

    chunk_size = 50

    max_monsters_per_chunk = 50
    max_items_per_chunk = 30
    cx = player.x // chunk_size * chunk_size
    cy = player.y // chunk_size * chunk_size
    add_new_chunks(cx, cy, chunk_size, game_map, entities, items,
                   max_monsters_per_chunk, max_items_per_chunk)

    # print(game_map.chunks)
    items[(health_potion.x, health_potion.y)] = health_potion
    entities[(player.x, player.y)] = player
    print(time.time() - start)
    print("BPS")
    # start = time.time()
    # make_bsp(game_map, 20, 5, player, entities, items, 3, 1)
    # blt.composition(True)
    camera = Camera(40, 20, 0, 0)
    blt.open()
    # print(time.time() - start)

    def is_unobstruct(x, y):
        if (x, y) in game_map.terrain:
            return False
        else:
            return True
    fov = rpas.FOVCalc()

    while True:
        mouse_x = blt.state(blt.TK_MOUSE_X)
        mouse_y = blt.state(blt.TK_MOUSE_Y)
        mouse = (mouse_x, mouse_y)
        blt.composition(True)
        # set_trace()
        blt.clear()
        # blt.bkcolor('green')
        # start = time.time()
        fov_cells = fov.calc_visible_cells_from(
            player.x, player.y, 20, is_unobstruct)
        # print(fov_cells)
        # recompute_fov(game_map, player.x, player.y, radius=5)
        # print(game_map.fov)
        render_all(game_map, camera, player, mouse,
                   entities, items, corpses,
                   fov_cells)
        # blt.put(2, 1, 0x2000)
        # blt.put(1, 1, 0x1000)
        # print(player.x)
        # print(player.y)
        blt.refresh()
        # print(time.time() - start)
        action = handle_keys()

        move = action.get('move')
        exit = action.get('exit')

        player_turn_results = []
        # print(len(game_map.terrain))
        # print(len(game_map.water))
        if move:
            dx, dy = move
            dest_x = player.x + dx
            dest_y = player.y + dy
            if (dest_x, dest_y) in game_map.terrain:
                continue
            if entities.get((dest_x, dest_y)):
                target = entities.get((dest_x, dest_y))
                attack_results = player.fighter.attack(target)
                player_turn_results.extend(attack_results)
            else:
                entities.pop((player.x, player.y))
                player.move(dx, dy)
                entities[(player.x, player.y)] = player

        if exit:
            return False
        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')

            if message:
                print(message.text)

            if dead_entity:
                if dead_entity == player:
                    message = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity, entities, corpses)
                print(message.text)
        print("Entites ", len(entities))
        i = 0
        entities_done = set()
        for entity in entities:
            # print(entities[entity])
            if (entities[entity] != player and
                    not (entity in entities_done) and
                    entity in fov_cells):
                enemy = entities.pop(entity)

                enemy.move_towards(player.x, player.y, game_map, entities)
                entities[(enemy.x, enemy.y)] = enemy
                entities_done.add((enemy.x, enemy.y))
                i += 1
        print(i)


        # print("input delay: %s" % (time.time() - start))
        cx = (player.x // chunk_size) * chunk_size
        cy = (player.y // chunk_size) * chunk_size

        add_new_chunks(cx, cy, chunk_size, game_map, entities, items,
                       max_monsters_per_chunk, max_items_per_chunk)
Exemplo n.º 24
0
 def test_EntityAttributeCompletely(self):
     # General functionality given.
     entity = Entity()
     entity.setObject(ComplexExample(), {}, False)
     ComplexExample().ToJSON(entity)
Exemplo n.º 25
0
def main():
    screen_width = 80
    screen_height = 50

    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    # Size of the map
    map_width = 80
    map_height = 43

    # Some variables for the rooms in the map
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3
    max_items_per_room = 2

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    inventory_component = Inventory(26)
    player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR, fighter=fighter_component, inventory=inventory_component)
    entities = [player]

    libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False)

    con = libtcod.console_new(screen_width, screen_height)
    panel = libtcod.console_new(screen_width, panel_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities,
                      max_monsters_per_room, max_items_per_room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN
    previous_game_state = game_state

    targeting_item = None

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm)

        render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, screen_width,
                   screen_height, bar_width, panel_height, panel_y, mouse, colors, game_state)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        # Acquire the dictionary returned by handle_keys() and handle_mouse()
        action = handle_keys(key, game_state)
        mouse_action = handle_mouse(mouse)

        # Extracts values from dictionaries by key
        move = action.get('move')
        exit = action.get('exit')
        pickup = action.get('pickup')
        show_inventory = action.get('show_inventory')
        drop_inventory = action.get('drop_inventory')
        inventory_index = action.get('inventory_index')
        fullscreen = action.get('fullscreen')

        left_click = mouse_action.get('left_click')
        right_click = mouse_action.get('right_click')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        elif pickup and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickup_results = player.inventory.add_item(entity)
                    player_turn_results.extend(pickup_results)

                    break
            else:
                message_log.add_message(Message('There is nothing to pick up here.', libtcod.yellow))

        if show_inventory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        if drop_inventory:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(player.inventory.items):
            item = player.inventory.items[inventory_index]

            if game_state == GameStates.SHOW_INVENTORY:
                player_turn_results.extend(player.inventory.use(item, entities=entities, fov_map=fov_map))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(player.inventory.drop_item(item))

        if game_state == GameStates.TARGETING:
            if left_click:
                target_x, target_y = left_click

                item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map,
                                                        target_x=target_x, target_y=target_y)
                player_turn_results.extend(item_use_results)
            elif right_click:
                player_turn_results.append({'targeting_cancelled': True})

        if exit:
            if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY):
                game_state = previous_game_state
            elif game_state == GameStates.TARGETING:
                player_turn_results.append({'targeting_cancelled': True})
            else:
                return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')
            item_consumed = player_turn_result.get('consumed')
            item_dropped = player_turn_result.get('item_dropped')
            targeting = player_turn_result.get('targeting')
            targeting_cancelled = player_turn_result.get('targeting_cancelled')

            if message:
                message_log.add_message(message)

            if targeting_cancelled:
                game_state = previous_game_state

                message_log.add_message(Message('Targeting cancelled'))

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                message_log.add_message(message)

            if item_consumed:
                game_state = GameStates.ENEMY_TURN

            if item_dropped:
                entities.append(item_dropped)

                game_state = GameStates.ENEMY_TURN

            if item_added:
                entities.remove(item_added)

                game_state = GameStates.ENEMY_TURN
            if targeting:
                previous_game_state = GameStates.PLAYERS_TURN
                game_state = GameStates.TARGETING
                targeting_item = targeting

                message_log.add_message(targeting_item.item.targeting_message)

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYERS_TURN
Exemplo n.º 26
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 'BASIC'
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3

    colors = {
        'dark_wall': (0, 0, 100),
        'dark_ground': (50, 50, 150),
        'light_wall': (130, 110, 50),
        'light_ground': (200, 180, 50),
        'desaturated_green': (63, 127, 63),
        'darker_green': (0, 127, 0)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    player = Entity(0,
                    0,
                    '@', (255, 255, 255),
                    'Player',
                    blocks=True,
                    fighter=fighter_component)
    entities = [player]

    tdl.set_font('arial10x10.png', greyscale=True, altLayout=True)

    root_console = tdl.init(screen_width,
                            screen_height,
                            title='Roguelike Tutorial Revised')
    con = tdl.Console(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    make_map(game_map, max_rooms, room_min_size, room_max_size, map_width,
             map_height, player, entities, max_monsters_per_room, colors)

    fov_recompute = True

    game_state = GameStates.PLAYERS_TURN

    while not tdl.event.is_window_closed():
        if fov_recompute:
            game_map.compute_fov(player.x,
                                 player.y,
                                 fov=fov_algorithm,
                                 radius=fov_radius,
                                 light_walls=fov_light_walls)

        render_all(con, entities, game_map, fov_recompute, root_console,
                   screen_width, screen_height, colors)
        tdl.flush()

        clear_all(con, entities)

        fov_recompute = False

        for event in tdl.event.get():
            if event.type == 'KEYDOWN':
                user_input = event
                break
        else:
            user_input = None

        if not user_input:
            continue

        action = handle_keys(user_input)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if game_map.walkable[destination_x, destination_y]:
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        if exit:
            return True

        if fullscreen:
            tdl.set_fullscreen(not tdl.get_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')

            if message:
                print(message)

            if dead_entity:
                pass  # We'll do something here momentarily

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            print(message)

                        if dead_entity:
                            pass
            else:
                game_state = GameStates.PLAYERS_TURN
Exemplo n.º 27
0
    def make_map(self, max_rooms, room_min_size, room_max_size, map_width,
                 map_height, player, entities, max_monsters_per_room,
                 max_items_per_room):
        # Create two rooms fore demonstration purposes
        rooms = []
        num_rooms = 0

        center_of_last_room_x = None
        center_of_last_room_y = None

        for r in range(max_rooms):
            # random width and height
            w = randint(room_min_size, room_max_size)
            h = randint(room_min_size, room_max_size)

            # random position without going out of the boundaries of the map
            x = randint(0, map_width - w - 1)
            y = randint(0, map_height - h - 1)

            # "Rect" class makes rectangles easier to work with
            new_room = Rect(x, y, w, h)

            # run through the other rooms and see if they intersect with this one
            for other_room in rooms:
                if new_room.intersect(other_room):
                    break
            else:
                # this means there are no intersections, so this room is valid

                # "paint" it to the map's tiles
                self.create_room(new_room)

                # center coordinates of new room, will be useful later
                (new_x, new_y) = new_room.center()

                center_of_last_room_x = new_x
                center_of_last_room_y = new_y

                if num_rooms == 0:
                    # this is the first room, where the player starts at
                    player.x = new_x
                    player.y = new_y
                else:
                    # all rooms after the first
                    # connect it to the previous room with a tunnel

                    # center coordinates of previous room
                    (prev_x, prev_y) = rooms[num_rooms - 1].center()

                    # flip a coin (random number that is either 0 or 1
                    if randint(0, 1) == 1:
                        # first move horizontally, then vertically
                        self.create_h_tunnel(prev_x, new_x, prev_y)
                        self.create_v_tunnel(prev_y, new_y, new_x)
                    else:
                        # first move vertically, then horizontally
                        self.create_v_tunnel(prev_y, new_y, prev_x)
                        self.create_h_tunnel(prev_x, new_x, new_y)

                # finally, append the new room to the list
                self.place_entities(new_room, entities, max_monsters_per_room,
                                    max_items_per_room)

                rooms.append(new_room)
                num_rooms += 1

        stairs_component = Stairs(self.dungeon_level + 1)
        down_stairs = Entity(center_of_last_room_x,
                             center_of_last_room_y,
                             '>',
                             libtcod.white,
                             'Stairs',
                             render_order=RenderOrder.STAIRS,
                             stairs=stairs_component)
        entities.append(down_stairs)
Exemplo n.º 28
0
from entity import Entity

from components import fighter, ai, sprite, location, item

player = lambda: Entity((fighter.Player(), sprite.Player()))

monsters = {
    'orc': lambda: Entity((fighter.Orc(), sprite.Orc(), ai.BasicMonster()))
}

items = {
    'healing_potiont':
    lambda: Entity((item.HealingPotiont(), sprite.HealingPotiont()))
}
Exemplo n.º 29
0
def main():

    tdl.set_font('arial10x10.png', greyscale=True, altLayout=True)

    # Setup playscreen with two consoles:
    #  - A place to draw the playscreen with the map and entities.
    #  - A console with the player's health bar, and a message log.
    root_console = tdl.init(SCREEN_WIDTH,
                            SCREEN_HEIGHT,
                            title='Rougelike Tutorial Game')
    map_console = tdl.Console(SCREEN_WIDTH, SCREEN_HEIGHT)
    panel_console = tdl.Console(SCREEN_WIDTH, PANEL_CONFIG['height'])
    message_log = MessageLog(MESSAGE_CONFIG)

    # This is you.  Kill some Orcs.
    player = Entity(0,
                    0,
                    '@',
                    COLORS['white'],
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    attacker=Attacker(power=5),
                    harmable=Harmable(hp=2000, defense=2),
                    inventory=Inventory(26))
    entities = [player]

    # Setup Initial Inventory, for testing.
    player.inventory.extend([HealthPotion.make(0, 0) for _ in range(5)])
    player.inventory.extend([MagicMissileScroll.make(0, 0) for _ in range(5)])
    player.inventory.extend([FireblastScroll.make(0, 0) for _ in range(5)])

    # Generate the map and place player, monsters, and items.
    game_map = GameMap(FLOOR_CONFIG['width'], FLOOR_CONFIG['height'])
    floor = make_floor(FLOOR_CONFIG, ROOM_CONFIG)
    floor.place_player(player)
    floor.write_to_game_map(game_map)
    spawn_entities(MONSTER_SCHEDULE, MONSTER_GROUPS, floor, entities)
    spawn_entities(ITEM_SCHEDULE, ITEM_GROUPS, floor, entities)

    # Initial values for game states
    game_state = GameStates.PLAYER_TURN
    previous_game_state = game_state
    # We only want to recompute the fov when needed.  For example, if the
    # player just used an item and has not moved, the fov will be the same.
    fov_recompute = True
    # Data needed to play an animation.
    animation_player = None
    # A list of recently dead enemies.  We need this to defer drawing thier
    # corpses until *after* any animations have finished.
    dead_entities = []

    #-------------------------------------------------------------------------
    # Main Game Loop.
    #-------------------------------------------------------------------------
    while not tdl.event.is_window_closed():

        #---------------------------------------------------------------------
        # If needed, recompute the player's field of view.
        #---------------------------------------------------------------------
        if fov_recompute:
            game_map.compute_fov(player.x,
                                 player.y,
                                 fov=FOV_CONFIG["algorithm"],
                                 radius=FOV_CONFIG["radius"],
                                 light_walls=FOV_CONFIG["light_walls"])

        #---------------------------------------------------------------------
        # Render and display the dungeon and its inhabitates.
        #---------------------------------------------------------------------
        render_all(map_console, entities, game_map, fov_recompute, COLORS)
        root_console.blit(map_console, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0)
        render_health_bars(panel_console, player, PANEL_CONFIG, COLORS)
        render_messages(panel_console, message_log)
        root_console.blit(panel_console, 0, PANEL_CONFIG['y'], SCREEN_WIDTH,
                          SCREEN_HEIGHT, 0, 0)

        #---------------------------------------------------------------------
        # Render any menus.
        #---------------------------------------------------------------------
        if game_state in (GameStates.SHOW_INVETORY, GameStates.DROP_INVENTORY):
            if game_state == GameStates.SHOW_INVETORY:
                invetory_message = "Press the letter next to the item to use it.\n"
            elif game_state == GameStates.DROP_INVENTORY:
                invetory_message = "Press the letter next to the item to drop it.\n"
            menu_console, menu_x, menu_y = invetory_menu(
                invetory_message, player.inventory, 50, SCREEN_WIDTH,
                SCREEN_HEIGHT)
            root_console.blit(menu_console, menu_x, menu_y, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0, 0)

        #---------------------------------------------------------------------
        # Advance the frame of any animations.
        #---------------------------------------------------------------------
        if game_state == GameStates.ANIMATION_PLAYING:
            # Now play the animatin
            animation_finished = animation_player.next_frame()
            sleep(0.15)
            if animation_finished:
                game_state, previous_game_state = previous_game_state, game_state

        tdl.flush()
        clear_all(map_console, entities)

        # Unless the player moves, we do not need to recompute the fov.
        fov_recompute = False

        #---------------------------------------------------------------------
        # Get key input from the player.
        #---------------------------------------------------------------------
        input_states = (GameStates.PLAYER_TURN, GameStates.SHOW_INVETORY,
                        GameStates.DROP_INVENTORY)
        for event in tdl.event.get():
            if event.type == 'KEYDOWN':
                user_input = event
                break
        else:
            user_input = None
        if game_state in input_states and not user_input:
            continue
        action = handle_keys(user_input, game_state)

        #----------------------------------------------------------------------
        # Handle player actions.
        #......................................................................
        # Here we process the consequences of input from the player that
        # affect the game state.  These consequences are added to a queue for
        # later processing.  This allows consequences to have further
        # consequences, which are then also added to the queue.  The messages
        # on the queue are constantly popped and dealt with until the queue is
        # empty, after which we pass the turn.
        #----------------------------------------------------------------------
        move = action.get('move')
        pickup = action.get('pickup')
        drop = action.get('drop')
        inventory_index = action.get('inventory_index')
        player_turn_results = []

        #----------------------------------------------------------------------
        # Player Move Action
        #......................................................................
        # The player has entered a move action.  Chack if the space in that
        # direction is movable, and if so put a move result on the queue.  If
        # if not, attack the blocking entity by putting an attack action on the
        # queue.
        #----------------------------------------------------------------------
        if move and game_state == GameStates.PLAYER_TURN:
            dx, dy = move
            destination_x, destination_y = player.x + dx, player.y + dy
            if game_map.walkable[destination_x, destination_y]:
                blocker = get_blocking_entity_at_location(
                    entities, destination_x, destination_y)
                # If you attempted to walk into a square occupied by an entity,
                # and that entity is not yourself.
                if blocker and blocker != player:
                    attack_results = player.attacker.attack(blocker)
                    player_turn_results.extend(attack_results)
                else:
                    player_turn_results.append({'move': (dx, dy)})
                game_state = GameStates.ENEMY_TURN

        #----------------------------------------------------------------------
        # Player Pickup
        #......................................................................
        # The player has attempted to pickup an item.  If there is an item in
        # the players space, put a pickup action on the queue.
        #----------------------------------------------------------------------
        elif pickup and game_state == GameStates.PLAYER_TURN:
            for entity in entities:
                if (entity.item and entity.x == player.x
                        and entity.y == player.y):
                    pickup_results = player.inventory.pickup(entity)
                    player_turn_results.extend(pickup_results)
                    break
            else:
                player_turn_results.append(
                    {'message': Message("There is nothing to pick up!")})
            game_state = GameStates.ENEMY_TURN

        #----------------------------------------------------------------------
        # Player Inventory use / drop
        #......................................................................
        # The player has attempted to use or drop an item from the inventory.
        # Check which state we are in (using or dropping) and put an
        # instruction on the queue.
        #----------------------------------------------------------------------
        elif (game_state
              in (GameStates.SHOW_INVETORY, GameStates.DROP_INVENTORY)
              and inventory_index is not None
              and inventory_index < len(player.inventory.items)
              and previous_game_state != GameStates.PLAYER_DEAD):
            entity = player.inventory.items[inventory_index]
            if game_state == GameStates.SHOW_INVETORY:
                if entity.item.targeting == ItemTargeting.PLAYER:
                    player_turn_results.extend(entity.item.use(player))
                if entity.item.targeting == ItemTargeting.CLOSEST_MONSTER:
                    player_turn_results.extend(
                        entity.item.use(player, entities))
                if entity.item.targeting == ItemTargeting.WITHIN_RADIUS:
                    player_turn_results.extend(
                        entity.item.use(player, entities))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(player.inventory.drop(entity))
            game_state, previous_game_state = previous_game_state, game_state

        #----------------------------------------------------------------------
        # Process the results queue
        #......................................................................
        # We are done processing player inputs, and may have some results on
        # the player turn queue.  Process the queue by popping off the top
        # result from the queue.  There are many different possible results,
        # so handle each with a dedicated handler.
        #
        # Note: Handling a result may result in other results being added to
        # the queue, so we continually process the results queue until it is
        # empty.
        #----------------------------------------------------------------------
        while player_turn_results != []:
            result = player_turn_results.pop()
            animation = result.get('animation')
            damage = result.get('damage')
            dead_entity = result.get('dead')
            death_message = result.get('death_message')
            heal = result.get('heal')
            item_added = result.get('item_added')
            item_consumed = result.get('item_consumed')
            item_dropped = result.get('item_dropped')
            message = result.get('message')
            move = result.get('move')
            # Handle movement.
            if move:
                player.move(*move)
                fov_recompute = True
            # Handle Messages
            if message:
                message_log.add_message(message)
            if item_added:
                player.inventory.add(item_added)
                entities.remove(item_added)
            # Handle damage dealt.
            if damage:
                target, amount = damage
                damage_result = target.harmable.take_damage(amount)
                player_turn_results.extend(damage_result)
            # Remove consumed items from inventory
            if item_consumed:
                consumed, item = item_consumed
                if consumed:
                    player.inventory.remove(item)
                    game_state, previous_game_state = (GameStates.ENEMY_TURN,
                                                       game_state)
            # Remove dropped items from inventory and place on the map
            if item_dropped:
                player.inventory.remove(item_dropped)
                item_dropped.x, item_dropped.y = player.x, player.y
                entities.append(item_dropped)
                game_state, previous_game_state = (GameStates.ENEMY_TURN,
                                                   game_state)
            # Heal an entity
            if heal:
                target, amount = heal
                target.harmable.hp += min(
                    amount, target.harmable.max_hp - target.harmable.hp)
            # Handle death
            if dead_entity == player:
                player_turn_results.extend(kill_player(player, COLORS))
                game_state = GameStates.PLAYER_DEAD
            elif dead_entity:
                player_turn_results.extend(kill_monster(dead_entity, COLORS))
                dead_entities.append(dead_entity)
            # Handle a death message.  Death messages are special in that
            # they immediately break out of the game loop.
            if death_message:
                message_log.add_message(death_message)
                #break
            # Play an animation.
            if animation:
                animation_type = animation[0]
                if animation_type == Animations.MAGIC_MISSILE:
                    animation_player = MagicMissileAnimation(
                        map_console, game_map, (player.x, player.y),
                        (animation[1].x, animation[1].y))
                elif animation_type == Animations.HEALTH_POTION:
                    animation_player = HealthPotionAnimation(
                        map_console, game_map, player)
                elif animation_type == Animations.FIREBLAST:
                    animation_player = FireblastAnimation(
                        map_console, game_map, player, animation[2])
                game_state, previous_game_state = (
                    GameStates.ANIMATION_PLAYING, game_state)

        #---------------------------------------------------------------------
        # Handle enemy actions
        #---------------------------------------------------------------------
        enemy_turn_results = []
        if game_state == GameStates.ENEMY_TURN:
            for entity in (x for x in entities if x.ai):
                enemy_turn_results.extend(entity.ai.take_turn(
                    player, game_map))
            game_state = GameStates.PLAYER_TURN
        # Process all result actions of enemy turns
        while enemy_turn_results != []:
            result = enemy_turn_results.pop()
            move_towards = result.get('move_towards')
            move_random_adjacent = result.get('move_random_adjacent')
            message = result.get('message')
            damage = result.get('damage')
            dead_entity = result.get('dead')
            death_message = result.get('death_message')
            # Handle a move towards action.  Move towards a target.
            if move_towards:
                monster, target_x, target_y = move_towards
                monster.move_towards(target_x, target_y, game_map, entities)
            # Handle a move random adjacent action.  Move to a random adjacent
            # square.
            if move_random_adjacent:
                monster = move_random_adjacent
                monster.move_to_random_adjacent(game_map, entities)
            # Handle a simple message.
            if message:
                message_log.add_message(message)
            # Handle damage dealt.
            if damage:
                target, amount = damage
                damage_result = target.harmable.take_damage(amount)
                enemy_turn_results.extend(damage_result)
            # Handle death.
            if dead_entity == player:
                enemy_turn_results.extend(kill_player(player, COLORS))
                game_state = GameStates.PLAYER_DEAD
            elif dead_entity:
                enemy_turn_results.extend(kill_monster(dead_entity, COLORS))
            # Handle a death message.  Death messages are special in that
            # they immediately break out of the game loop.
            if death_message:
                message_log.add_message(death_message)
                break

        #---------------------------------------------------------------------
        # Handle meta actions
        #---------------------------------------------------------------------
        show_invetory = action.get('show_invetory')
        if game_state == GameStates.PLAYER_TURN and show_invetory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVETORY

        drop = action.get('drop_inventory')
        if game_state == GameStates.PLAYER_TURN and drop:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        exit = action.get('exit')
        if exit:
            if game_state in (GameStates.SHOW_INVETORY,
                              GameStates.DROP_INVENTORY):
                game_state = previous_game_state
            else:
                # Hard exit the game.
                return True

        fullscreen = action.get('fullscreen')
        if fullscreen:
            tdl.set_fullscreen(not tdl.get_fullscreen())

        #---------------------------------------------------------------------
        # Once an animation is finished that results in a dead monster, draw it
        # as a corpse.
        #---------------------------------------------------------------------
        if not game_state == GameStates.ANIMATION_PLAYING:
            while dead_entities:
                dead_entity = dead_entities.pop()
                make_corpse(dead_entity, COLORS)

        #---------------------------------------------------------------------
        # If the player is dead, the game is over.
        #---------------------------------------------------------------------
        if game_state == GameStates.PLAYER_DEAD:
            continue
Exemplo n.º 30
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 43

    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30
    max_monsters_per_room = 3

    fov_algorithm = 'BASIC'
    fov_light_walls = True
    fov_radius = 10

    colors = {
        'dark_wall': (0, 0, 100),
        'dark_ground': (50, 50, 150),
        'light_wall': (130, 110, 50),
        'light_ground': (200, 180, 50),
        'desaturated_green': (63, 127, 63),
        'darker_green': (0, 127, 0),
        'dark_red': (191, 0, 0),
        'white': (255, 255, 255),
        'black': (0, 0, 0),
        'red': (255, 0, 0),
        'orange': (255, 127, 0),
        'light_red': (255, 114, 114),
        'darker_red': (127, 0, 0),
        'violet': (127, 0, 255),
        'yellow': (255, 255, 0),
        'blue': (0, 0, 255),
        'green': (0, 255, 0)
    }

    inventory_component = Inventory(26)
    fighter_component = Fighter(hp=30, defense=2, power=5)
    player = Entity(0,
                    0,
                    '@', (255, 255, 255),
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component)
    entities = [player]
    tdl.set_font('arial10x10.png', greyscale=True, altLayout=True)

    root_console = tdl.init(screen_width,
                            screen_height,
                            title='Roguelike 3000')
    con = tdl.Console(screen_width, screen_height)
    panel = tdl.Console(screen_width, panel_height)

    game_map = GameMap(map_width, map_height)
    make_map(game_map, max_rooms, room_min_size, room_max_size, map_width,
             map_height, player, entities, max_monsters_per_room, colors)
    fov_recompute = True
    message_log = MessageLog(message_x, message_width, message_height)
    game_state = GameStates.PLAYERS_TURN
    previous_game_state = game_state

    while not tdl.event.is_window_closed(
    ) and game_state != GameStates.PLAYER_DEAD:
        if fov_recompute:
            game_map.compute_fov(player.x,
                                 player.y,
                                 fov=fov_algorithm,
                                 radius=fov_radius,
                                 light_walls=fov_light_walls)

        render_all(con, panel, entities, player, game_map, fov_recompute,
                   root_console, message_log, screen_width, screen_height,
                   bar_width, panel_height, panel_y, colors, game_state)

        tdl.flush()
        clear_all(con, entities)
        fov_recompute = False

        for event in tdl.event.get():
            if event.type == 'KEYDOWN':
                user_input = event
                break
        else:
            user_input = None

        if not user_input:
            continue
        action = handle_keys(user_input, game_state)
        player_turn_results = []
        if game_state == GameStates.PLAYERS_TURN:
            if "move" in action:
                move = action["move"]
                destination_x = player.x + move[0]
                destination_y = player.y + move[1]

                if game_map.walkable[destination_x, destination_y]:
                    target = get_blocking_entities_at_location(
                        entities, destination_x, destination_y)
                    if target:
                        attack_results = player.fighter.attack(target)
                        player_turn_results.extend(attack_results)
                    else:
                        player.move(move[0], move[1])
                        fov_recompute = True
            elif "pickup" in action:
                for entity in entities:
                    if entity.item and entity.x == player.x and entity.y == player.y:
                        pickup_results = player.inventory.add_item(
                            entity, colors)
                        player_turn_results.extend(pickup_results)
                        break
                else:
                    message_log.add_message(
                        Message('There is nothing here to pick up.',
                                colors.get('yellow')))

            game_state = GameStates.ENEMY_TURN

        if "show_inventory" in action:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        if "index_inventory" in action and previous_game_state != GameStates.PLAYER_DEAD:
            index = action["index_inventory"]
            if index < len(player.inventory.items):
                item = player.inventory.items[index]
                player_turn_results.extend(item.item.use(player))
                player.inventory.remove(index)
                game_state = previous_game_state

        if "exit" in action:
            if game_state == GameStates.SHOW_INVENTORY:
                game_state = previous_game_state
            else:
                return True

        if "fullscreen" in action:
            tdl.set_fullscreen(not tdl.get_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity, colors)
                else:
                    message = kill_monster(dead_entity, colors)

                message_log.add_message(message)

            if item_added:
                entities.remove(item_added)

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, game_map, entities)
                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(
                                    dead_entity, colors)
                            else:
                                message = kill_monster(dead_entity, colors)

                            message_log.add_message(message)

                    if game_state == GameStates.PLAYER_DEAD:
                        break

            else:
                game_state = GameStates.PLAYERS_TURN