Example #1
0
 def test_switch_weapon(self):
     new_entity = Entity("equipswitch", 100)
     axe = Weapon("skullsplitter", 10, 0.2)
     bow = Weapon("arrowless bow", 1, 1.0)   
     new_entity.equip_weapon(axe)
     new_entity.equip_weapon(bow)
     self.assertEqual(new_entity.weapon.name, bow.name)
Example #2
0
def main():
#----------------------------Initialize your storage------------------------------------#
	if len(sys.argv) < 2:
		print "Expected: "+str(sys.argv[0])+" <config>"
	conf = __import__(str(sys.argv[1]), fromlist=["*"])
	"""Initialize storage plugin"""
	st = Storage(conf.store_plugin_mod, conf.store_plugin_class)
	st.connect(conf.store_ip, conf.store_port)

	"""Create a service endpoint for up coming Data"""
	xeid_key = get_sha256_hash(str(conf.eid_uuid))
	xeid = EID(xeid_key, conf.app_proto, conf.transport)
	
	#-----------------------Create an entity and store it in registry----------------------#
	"""Create an entity"""
	xentity = Entity("WathsalaObject", "A bogus document inserted to demonstrate the software", "text/xml", "xyz", "D")
	"""Create an SID string for the entity"""
	uuid = "50aec6e5-1968-4243-a51c-ab1768a2c514"#uuid.uuid4()
	sid_str = get_sha256_hash(str(uuid))
	xentity.set_sid(sid_str)
	xjson = xentity.object2json()
	"""Store this entity in author registry"""
	st.put("wathsala", xjson)
	
	"""Store this entity's EID under sid_str"""
	st.put(sid_str, xeid.object2json())
Example #3
0
 def __init__(self, *args, **kwargs):
     Server.__init__(self, *args, **kwargs)
     self.id_inc = 0
     
     self.clients = []
     self.entities = []
     
     # Entities that can be hit.
     self.collided = []
     
     # Entites that hit.
     self.colliders = []
     
     # Static Objects in space.
     # Functions for the entities.
     self.functions = {
         'new_id': self.get_id,
         'add_entity': self.add_entity,
         'remove_entity': self.remove_entity,
         'system_size': SYSTEM_SIZE,
     }
     
     # A Planet to respawn at:
     planet = Entity(self.functions)
     planet.type = 'planet'
     self.entities.append(planet)
 def test_Entity_attack_with_weapon(self):
     my_weapon = Weapon("Axe", 31, 0.2)
     my_Entity = Entity("Ivan", 100)
     my_Entity.equip_weapon(my_weapon)
     attack = my_weapon.damage * (1 + my_weapon.critical_strike_percent)
     true_attack = my_Entity.attack()
     self.assertEqual(attack, true_attack)
Example #5
0
	def __init__(self, board):
		size = 15
		x = board.getWidth()/2 - size/2
		y = board.getHeight()/2 - size/2
		Entity.__init__(self, x, y, size)
		self.speed = 100
		self.dead = False
Example #6
0
	def update(self, timestep, target):
		displacementX = target[0]-self.position[0]
		displacementY = target[1]-self.position[1]
		distance = math.sqrt(displacementX**2 + displacementY**2)
		if distance == 0: distance = 1
		normalX = displacementX/distance
		normalY = displacementY/distance
		
		accelerationX = normalX*self.maxAcceleration
		accelerationY = normalY*self.maxAcceleration
		self.velocity = self.velocity[0]+accelerationX*timestep, self.velocity[1]+accelerationY*timestep
		
		angleTo = math.atan2(normalY, normalX)*180/math.pi+180
		angleDifference = angleTo - self.angle
		if angleDifference > 180: angleDifference -= 360
		
		angularAcceleration = angleDifference/180*self.maxAngularAcceleration
		
		self.angularVelocity += angularAcceleration*timestep
		
		relativeSpeed = self.speed()/self.topSpeed
		if relativeSpeed > 1:
			self.velocity = (self.velocity[0]/relativeSpeed, self.velocity[1]/relativeSpeed)
		
		if self.angularVelocity > self.topAngularSpeed:
			self.angularVelocity = self.topAngularSpeed
		elif self.angularVelocity < -self.topAngularSpeed:
			self.angularVelocity = -self.topAngularSpeed
		
		Entity.update(self, timestep)
Example #7
0
 def __init__(self,
     number:int=0,
     name:str='<Default Company Name>',
     address:list=list(['<Default Address, line %u>' %(n+1) for n in range(4)]),
     btwNumber:str='', # => don't show BTW number on factuur, do charge BTW
     reference:str='',
     paymentTerms:list=[
              "Betaling naar bankrekening (zie gegevens boven) binnen 30 dagen wordt op prijs gesteld.",
              "Bij betaling svp factuurnummer vermelden.",
     ],
     restitutionTerms:list=[
          "Het positieve van de hierbovengenoemde negatieve totaal wordt vandaag overgeboekt ",
          "volgens uw instructies.",
     ],
     companyLogo:str='',
     cars:list=[],
 ):
     Entity.__init__(self,
         number=number,
         name=name,
         address=address,
         btwNumber=btwNumber,
         reference=reference,
         paymentTerms=paymentTerms,
         restitutionTerms=restitutionTerms,
         companyLogo=companyLogo,
         cars=cars,
     )
 def __init__(self):
     Entity.__init__(self)
     
     self.collide_walls = True
     
     self.walk_speed = 100
     self._movement_vectors = []
     self._walking = {
         Character.Direction.UP : False, 
         Character.Direction.RIGHT : False, 
         Character.Direction.DOWN : False, 
         Character.Direction.LEFT : False
             }        
     
     self.max_hitpoints = self.current_hitpoints = 10
     self.hitbar_health_color = 0, 255, 0
     self.hitbar_damage_color = 255, 0, 0
     
     self.sprites = {
         Character.Direction.UP : 0, 
         Character.Direction.RIGHT : 0, 
         Character.Direction.DOWN : 0, 
         Character.Direction.LEFT : 0
             }
     self.facing = Character.Direction.DOWN
 def test_Entity_equip_weapon_no_weapon(self):
     my_weapon = Weapon("Axe", 31, 0.2)
     my_Entity = Entity("Ivan", 100)
     my_Entity.equip_weapon(my_weapon)
     self.assertEqual(my_Entity.weapon.type, "Axe")
     self.assertEqual(my_Entity.weapon.damage, 31)
     self.assertEqual(my_Entity.weapon.critical_strike_percent, 0.2)
Example #10
0
    def __init__(self, position):
        Entity.__init__(self)
        # Physics stuff
        self.position = position
        self.velocity = Vector2(0, 0)
        self.acceleration = Vector2(0, 0)

        # Image stuff
        self.animations = {}
        self.currentAnimation = None
        self.flipHorizontal = False
        self.offset = Vector2(0, 0)
        self.visible = True

        # z
        self.z = 0
        self.zVelocity = 0

        # self.shadow = content.images["shadow.png"]
        self.shadowSize = 14
        self.shadowOffset = Vector2(0, 0)
        self.shadowVisible = True

        # layering
        self.layerIndex = 0

        # rotation
        self.angle = 0
Example #11
0
    def __init__(self,
        text="<no text specified>",
        width=None,
        height=None,
        collision=Entity.BLOCK,
        draworder=10,
        rsize=None,
        halo_img="default",
        width_ofs=0,
        height_ofs=0,
        double=False,
        permute=True,
        dropshadow=False,
        dropshadow_color=sf.Color(30,30,30,150),
        colored_halo=True):

        self.colored_halo = colored_halo
        
        # Note: the 'constants' from defaults may change during startup, but 
        # this file may get parsed BEFORE this happens, so we can't
        # access defaults safely from default arguments which are 
        # stored at parse-time.
        height = height or Tile.AUTO
        width  = width  or Tile.AUTO
        rsize  = rsize  or defaults.letter_size[1]
        scale  =  rsize / defaults.letter_size[1] 
        
        self.permute = permute
            
        Entity.__init__(self)

        self.scale = scale
        self.rsize = rsize
        self.collision = collision
        self.text = text
        self.double = double
        self.dropshadow = dropshadow
        self.dropshadow_color = dropshadow_color

        self.optimized_text_elem = None
            
        self.draworder = draworder
        self.halo_img = halo_img
        
        # if either width and height are AUTO, compute the minimum bounding
        # rectangle for all glyph bounding rectangles.
        if width==Tile.AUTO or height==Tile.AUTO:
            self.dim,self.ofs = self._GuessRealBB(self.text)
            
        elif width==Tile.AUTO_QUICK or height==Tile.AUTO_QUICK:
            self.dim,self.ofs = self._GuessRealBB_Quick(self.text)
            
        else:
            self.dim = self._LetterToTileCoords(width,height)
            self.ofs = (width_ofs,height_ofs)
            
        
        if self.permute:
            self.text = self._Permute(self.text)
        self._Recache()
Example #12
0
    def __init__(self, name, **properties):
        self._account = None

        Entity.__init__(self, 'category', name, **properties)

        # Category id is it's name
        self._id = name
Example #13
0
 def update(self, dt):
     Entity.update(self, dt)
     self.z += self.zVelocity * dt
     self.velocity += self.acceleration * dt
     self.position += self.velocity * dt
     if self.currentAnimation:
         self.currentAnimation.update(dt)
Example #14
0
	def __init__(self, x, y, level, color = None):
		Entity.__init__(self)
		self.image = Surface((16, 16))
		if color: self.image.fill(color)
		self.image.convert()
		self.rect = Rect(x, y, 16, 16)
		self.level = level
Example #15
0
 def __init__(self, engine, color, axis_get_func):
     Entity.__init__(self, engine)
     self.color = color
     self.get_axis = axis_get_func
     self.pos = pos(0, 0) 
     self.velocity = pos(0, 0)
     self._speed = 1.0
Example #16
0
 def __init__(self, player):
     Entity.__init__(self, player.level, player.y, player.x)
     self.player = player
     self.num_ticks = NUM_TICKS
     self.curr_tick = NUM_TICKS
     self.radius = 3
     self.created_at = time.time()
Example #17
0
 def update( self, dt ):
     self.setPosition( self.host.standingAt )
     self.position[0] -= self.rect.w/2
     self.position[1] -= (self.rect.h - 1)
     self.rect.topleft = self.getPosition()
     
     Entity.update( self, dt )
Example #18
0
 def __init__(self, level):
     Entity.__init__(self)
     self._category = '_Environment'
     self._level = level
     self.animPath = ''
     self.graphics = ''
     self.physics = ''
Example #19
0
    def __init__(
            self,
            max_speed=1.0,
            average_turn=20.0,
            turn_std_dev=5.0,
            probability_positive_turn=0.5,
            x_pos=0.0,
            y_pos=0.0,
            parent=None):

        Entity.__init__(self, x_pos=x_pos, y_pos=y_pos, parent=parent)

        # basic attributes
        self.direction = 0.0
        self.max_speed = max_speed
        self.average_turn = average_turn
        self.turn_std_dev = turn_std_dev
        self.positive_turn = probability_positive_turn

        self.curr_x = x_pos
        self.curr_y = y_pos

        # Memory of movement
        self.X = []  # x position
        self.Y = []  # y position
        self.A = []  # angle turned
        self.X.append(self.curr_x)
        self.Y.append(self.curr_y)
        self.A.append(0.0)
Example #20
0
    def copyEntitiesFromInfiniteIter(self, sourceLevel, sourceBox, destinationPoint, entities):
        chunkCount = sourceBox.chunkCount
        i = 0
        copyOffset = map(lambda x, y: x - y, destinationPoint, sourceBox.origin)
        e = t = 0

        for (chunk, slices, point) in sourceLevel.getChunkSlices(sourceBox):
            yield (i, chunkCount)
            i += 1

            if entities:
                e += len(chunk.Entities)
                for entityTag in chunk.Entities:
                    x, y, z = Entity.pos(entityTag)
                    if (x, y, z) not in sourceBox:
                        continue

                    eTag = Entity.copyWithOffset(entityTag, copyOffset)

                    self.addEntity(eTag)

            t += len(chunk.TileEntities)
            for tileEntityTag in chunk.TileEntities:
                x, y, z = TileEntity.pos(tileEntityTag)
                if (x, y, z) not in sourceBox:
                    continue

                eTag = TileEntity.copyWithOffset(tileEntityTag, copyOffset)

                self.addTileEntity(eTag)

        info("Copied {0} entities, {1} tile entities".format(e, t))
 def __init__(self):
     Entity.__init__(self)
 
     self.slash_duration = 64
     self.damage_output = 1
     self._force = 640 #TODO: This is just a placeholder value.
 
     self.setVisible(False)
 
     #TODO: Put sprites into a spritesheet
     self.hold_sprites = {}
     self.hold_sprites[Character.Direction.UP] = loadImage('knifeb.bmp')
     self.hold_sprites[Character.Direction.RIGHT] = loadImage('knifer.bmp')
     self.hold_sprites[Character.Direction.DOWN] = loadImage('knifef.bmp')
     self.hold_sprites[Character.Direction.LEFT] = loadImage('knifel.bmp')
 
     #TODO: For dual-handed whatevers, these shouldn't be keyed to character directions after all. (If I ever do that.) 
     self.swing_sprites = {}
     self.swing_sprites[Character.Direction.UP] = loadImage('knifeslashne.bmp')
     self.swing_sprites[Character.Direction.RIGHT] = loadImage('knifeslashse.bmp')
     self.swing_sprites[Character.Direction.DOWN] = loadImage('knifeslashsw.bmp')
     self.swing_sprites[Character.Direction.LEFT] = loadImage('knifeslashnw.bmp')
 
     self.sprites = self.hold_sprites #Change self.sprites to the appropriate set...?
 
     self.facing = Character.Direction.DOWN
     self.attacker = None        
     self.attacking = False
     self.is_slash = False
     
     self._atk_origin = [0, 0]
     self.slash_timer = Timer(self.slash_duration, self.finishSlash)
     self.slash_timer.pause()
Example #22
0
    def __init__(
            self,
            length=100,
            width=100,
            n_patches=0):

        Entity.__init__(self, length=length, width=width)
        self.create_patches(n_patches)
Example #23
0
 def __init__(self, isEnnemy):
     Entity.__init__(self)
     self.isEnnemy = TimestampedValue('i', isEnnemy)
     self.champion = TimestampedValue('i', CHAMPION.UNKNOWN)
     self.skills = [Skill() for j in range(4)]
     self.range = TimestampedValue('i', -1) # 0 for melee champion ?
     self.mana = TimestampedValue('i', -1)
     self.speed = TimestampedValue('i', -1)
Example #24
0
File: hero.py Project: renton/0g
    def __init__(self):
        Entity.__init__(self, 200, 200, 40, 40, 0, 0)

        self.debug_color = (23,33,220)
        self.is_sticky = True
        self.speed = 6
        self.boost_multiplier = 2
        self.boost_ready = False
Example #25
0
    def __init__(self, pos_x, pos_y, surface, dt):
        Entity.__init__(self, pos_x, pos_y, surface, dt, self.VERTICES)

        self.angle = random.uniform(0.0, 360.0)
        self.spin = random.uniform(-1.0, 1.0)
        self.speed = 50.0
        # self.scale = Vector(5, 5)
        self.velocity = Vector(self.speed * random.uniform(-1.0, 1.0), self.speed * random.uniform(-1.0, 1.0))
Example #26
0
	def __init__(self, world):
		Entity.__init__(self, world)
		self.singular = 'a priest'

		self.ai.addAI(task.Fallback(self))
		self.ai.addAI(task.Cast(self))
		self.ai.addAI(task.Follow(self))
		self.ai.addAI(task.Wander(self))
Example #27
0
 def __init__(self, x=0, y=0, f=Action.South):
     Entity.__init__(x, y, f)
     self.nextAction = Action.Wait
     
     # store player statistics
     self.moves = 0
     
     if debug.active: print self
Example #28
0
 def __init__(self, x, y):
     Entity.__init__(self)
     self.xvel = x
     self.yvel = y
     self.onGround = False
     self.image = image.load(img_heror)
     (hauteur, largeur) = self.image.get_size()
     self.rect = Rect(x, y, hauteur, largeur)
Example #29
0
    def __init__( self, pos=[0,0], vel=[0,0], group=None, **kwargs ):
        Entity.__init__( self, pos, [0,0], None, group, pygame.Rect( 0, 0, self.width, self.height ), animated=False, **kwargs )
        self.visible = 0
        if EmptyPoint.instanceSpecificVars is None:
            attrList = list( self.__dict__.keys() )

        if EmptyPoint.instanceSpecificVars is None:
            EmptyPoint.instanceSpecificVars = dict( [ ( eachKey, eachVal ) for eachKey, eachVal in self.__dict__.items() if eachKey not in attrList ] )
Example #30
0
File: task.py Project: giann/clerk
    def __init__(self, name, **properties):
        self._due = None
        self._recurrence = None
        self._priority = "low"
        self._memo = None
        self._completed = None

        Entity.__init__(self, "task", name, **properties)
Example #31
0
def main():
    game_title = 'libtcod tutorial revised'

    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

    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)
    }
    #colors.get('dark_wall') yields the color val

    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, game_title, 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

    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)
        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')
        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)
                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 exit:
            if game_state in (GameStates.SHOW_INVENTORY,
                              GameStates.DROP_INVENTORY):
                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_dropped = player_turn_result.get('item_dropped')

            if message:
                print(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 item_added:
                entities.remove(item_added)

                game_state = GameStates.ENEMY_TURN

            if item_consumed:
                game_state = GameStates.ENEMY_TURN
            if item_dropped:
                entities.append(item_dropped)
                game_state = GameStates.ENEMY_TURN

        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:
                            print(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

            else:
                game_state = GameStates.PLAYERS_TURN
Example #32
0
    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 = {
            'goblin': 500,
            'orc': 350,
            'uruk': 100,
            'infirnimp': 49,
            'dragon': from_dungeon_level([100, 10], self.dungeon_level)
        }

        item_chances = {
            'healing_potion': 70,
            'lightning_scroll': 10,
            'fireball_scroll': 10,
            'confusion_scroll': 10
        }

        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 generation %
                if monster_choice == 'goblin':
                    fighter_component = Fighter(hp=10,
                                                sp=10,
                                                mp=1,
                                                defense=0,
                                                power=3,
                                                xp=30)
                    ai_component = BasicMonster()
                    #create an goblin at 50.0% chance
                    monster = Entity(x,
                                     y,
                                     'g',
                                     libtcod.light_green,
                                     'Goblin',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                elif monster_choice == 'orc':
                    fighter_component = Fighter(hp=20,
                                                sp=10,
                                                mp=1,
                                                defense=1,
                                                power=4,
                                                xp=50)
                    ai_component = BasicMonster()
                    #create an orc at 35.0% chance
                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.desaturated_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                elif monster_choice == 'uruk':
                    fighter_component = Fighter(hp=35,
                                                sp=20,
                                                mp=1,
                                                defense=1,
                                                power=5,
                                                xp=100)
                    ai_component = BasicMonster()
                    #create an uruk at 10.0% chance
                    monster = Entity(x,
                                     y,
                                     'u',
                                     libtcod.darkest_green,
                                     'uruk',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                elif monster_choice == 'infirnimp':
                    fighter_component = Fighter(hp=40,
                                                sp=30,
                                                mp=10,
                                                defense=3,
                                                power=6,
                                                xp=200)
                    ai_component = BasicMonster()
                    #create an infernimp at 4.9% chance
                    monster = Entity(x,
                                     y,
                                     'Infernimp',
                                     libtcod.amber,
                                     'Infernimp',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                else:
                    fighter_component = Fighter(hp=1000,
                                                sp=100,
                                                mp=1000,
                                                defense=30,
                                                power=60,
                                                xp=30000)
                    ai_component = BasicMonster()
                    #create a dragon at .1% chance
                    monster = Entity(x,
                                     y,
                                     'd',
                                     libtcod.darker_red,
                                     'Dragon',
                                     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':
                    #spawns healing potion at 70%
                    item_component = Item(use_function=heal, amount=4)
                    item = Entity(x,
                                  y,
                                  '!',
                                  libtcod.violet,
                                  'Healing Potion',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                elif item_choice == 'fireball_scroll':
                    #spawns fireball scroll at 10%
                    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',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                elif item_choice == 'confusion_scroll':
                    #spawns confuse scroll at 10%
                    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:
                    #spawns lightning scroll at 10%
                    item_component = Item(use_function=cast_lightning,
                                          damage=20,
                                          maximum_range=5)
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.yellow,
                                  'Lightning Scroll',
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                entities.append(item)
Example #33
0
    def make_map(self, max_rooms, room_max_size, room_min_size, map_width,
                 map_height, player, entities):

        rooms = []
        num_rooms = 0

        center_of_last_room_x = 0
        center_of_last_room_y = 0

        for r in range(max_rooms):
            # generates random room size
            w = randint(room_min_size, room_max_size)
            h = randint(room_min_size, room_max_size)

            # generates random room location in the map and not overlapping
            x = randint(0, map_width - w - 1)
            y = randint(0, map_height - h - 1)

            new_room = Rect(x, y, w, h)

            # checks for room intersections
            for other_room in rooms:
                if new_room.intersect(other_room):
                    break
            else:
                # if no intersections
                self.create_room(new_room)
                (new_x, new_y) = new_room.center()

                if num_rooms == 0:
                    # the first room contains the player in its center
                    player.x = new_x
                    player.y = new_y
                else:
                    # finds center of previous room
                    (prev_x, prev_y) = rooms[num_rooms - 1].center()

                    center_of_last_room_x = new_x
                    center_of_last_room_y = new_y

                    # flips a coin to find order of tunnel generation
                    if randint(0, 1) == 0:
                        # moves horizontally then vertically
                        self.create_horizontal_tunnel(prev_x, new_x, prev_y)
                        self.create_vertical_tunnel(prev_y, new_y, new_x)
                    else:
                        # moves vertically then horizontally
                        self.create_horizontal_tunnel(prev_x, new_x, new_y)
                        self.create_vertical_tunnel(prev_y, new_y, prev_x)

                self.place_entities(new_room, entities)
                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",
                             False,
                             render_order=RenderOrder.STAIRS,
                             stairs=stairs_component)
        entities.append(down_stairs)
Example #34
0
    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 = {
            'rat':
            from_dungeon_level([[80, 1], [40, 3], [15, 5]],
                               self.dungeon_level),
            'goblin':
            from_dungeon_level([[15, 1], [40, 3], [15, 5]],
                               self.dungeon_level),
            'orc':
            from_dungeon_level([[20, 2], [30, 4], [60, 6]],
                               self.dungeon_level),
            'troll':
            from_dungeon_level([[15, 3], [30, 5], [60, 7]], self.dungeon_level)
        }

        item_chances = {
            'torch': 10,
            'healing_potion': 35,
            'dagger': from_dungeon_level([[7, 1]], self.dungeon_level),
            'buckler': from_dungeon_level([[7, 2]], self.dungeon_level),
            'sword': from_dungeon_level([[35, 4]], self.dungeon_level),
            'shield': from_dungeon_level([[35, 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 == 'rat':
                    level_component = Level(current_level=1,
                                            current_xp=0,
                                            level_up_base=100,
                                            level_up_factor=100)
                    fighter_component = Fighter(hp=5,
                                                defense=0,
                                                power=1,
                                                body=monster_choice,
                                                xp=10,
                                                will_power=0)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'r',
                                     libtcod.dark_amber,
                                     'Rat',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                elif monster_choice == 'goblin':
                    level_component = Level(current_level=1,
                                            current_xp=0,
                                            level_up_base=40,
                                            level_up_factor=150)
                    fighter_component = Fighter(hp=10,
                                                defense=0,
                                                power=2,
                                                body=monster_choice,
                                                fov=7,
                                                xp=20,
                                                level=level_component,
                                                will_power=1)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'g',
                                     libtcod.dark_green,
                                     'Goblin',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component,
                                     inventory=Inventory(2),
                                     equipment=Equipment())
                elif monster_choice == 'orc':
                    fighter_component = Fighter(hp=20,
                                                defense=0,
                                                power=4,
                                                body=monster_choice,
                                                fov=4,
                                                xp=35,
                                                will_power=2)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.darker_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component,
                                     inventory=Inventory(10),
                                     equipment=Equipment())
                else:
                    fighter_component = Fighter(hp=30,
                                                defense=2,
                                                power=8,
                                                body=monster_choice,
                                                xp=100,
                                                will_power=3)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'T',
                                     libtcod.darkest_green,
                                     'Troll',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component,
                                     inventory=Inventory(15),
                                     equipment=Equipment())

                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 == 'torch':
                    equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                                      fov_bonus=5)
                    item = Entity(x,
                                  y,
                                  't',
                                  libtcod.yellow,
                                  'Torch',
                                  equippable=equippable_component)
                elif item_choice == 'sword':
                    equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                                      power_bonus=3)
                    item = Entity(x,
                                  y,
                                  '/',
                                  libtcod.sky,
                                  'Sword',
                                  equippable=equippable_component)
                elif item_choice == 'shield':
                    equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                                      defense_bonus=2)
                    item = Entity(x,
                                  y,
                                  '[',
                                  libtcod.darker_orange,
                                  'Shield',
                                  equippable=equippable_component)
                elif item_choice == 'dagger':
                    equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                                      power_bonus=1)
                    item = Entity(x,
                                  y,
                                  '/',
                                  libtcod.red,
                                  'Small Dagger',
                                  equippable=equippable_component)
                elif item_choice == 'buckler':
                    equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                                      defense_bonus=1)
                    item = Entity(x,
                                  y,
                                  '[',
                                  libtcod.red,
                                  'Rotten Buckler',
                                  equippable=equippable_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)
Example #35
0
 def __init__(self, workflow=None):
     Entity.__init__(self)
     self.id = None
     self.update(workflow)
Example #36
0
    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)
        max_equipment_items_per_room = from_dungeon_level([[2, 1]],
                                                          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),
            'Balrog':
            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([[25, 5]], self.dungeon_level),
            'confusion_spell':
            from_dungeon_level([[10, 2]], self.dungeon_level)
        }

        equipment_item_chances = {
            'equipment_health_potion':
            from_dungeon_level([[90, 1]], 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=10)
                    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=12,
                                                defense=0,
                                                power=4,
                                                magic=0,
                                                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)
                elif monster_choice == 'troll':
                    fighter_component = Fighter(hp=18,
                                                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=60,
                                                defense=5,
                                                power=16,
                                                magic=0,
                                                xp=200)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'B',
                                     libtcod.darker_red,
                                     'Balrog',
                                     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)
                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)
        '''
Example #37
0
 def __init__(self, x, r_y):
     Entity.__init__(self)
     self.r_y = r_y
     self.y = 0
     self.x = x
     self.color = BUOY_COLOUR
Example #38
0
def main():
    # Variables that define the screen size.
    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

    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)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    # Keeps track of the player's position at all times.
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component)
    entities = [player]

    # Tells libtcod which font to use.
    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    # Creates the screen with a title.
    libtcod.console_init_root(screen_width, screen_height,
                              'AngrealRL version T0.01', 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)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    # Variables that hold the keyboard and mouse inputs.
    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYER_TURN

    # Game loop that will only end if the screen is closed.
    while not libtcod.console_is_window_closed():
        # Captures new 'events' (user inputs).
        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)

        # Print the '@' symbol, set it to the position set by two parameters and set the backgroung to 'none'.
        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

        libtcod.console_flush()

        clear_all(con, entities)

        # Allow the game to be 'gracefully' closed by hitting the ESC key.
        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.PLAYER_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 = player.fighter.attack(target)
                else:
                    player.move(dx, dy)
                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        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')
                        # If the entity dies, changes the enemy status to 'dead'
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            print(message)

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

                            print(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYER_TURN
Example #39
0
    def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities,):
        """
        Create rooms for dungeon map
        """
        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 outside the boundaries of the map
            x = randint(0, map_width - w - 1)
            y = randint(0, map_height - h - 1)

            # 'Rect' class to make rooms
            new_room = Rect(x, y, w, h)

            # Run through other rooms to make sure it doesnt intersect
            for other_rooms in rooms:
                if new_room.intersect(other_rooms):
                    break
            else:
                # This will action if there are no intersections

                # unblock map tiles
                self.create_room(new_room)

                # center coordinates for 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:
                    # Upon creation of first room
                    player.x = new_x
                    player.y = new_y

                else:
                    """
                    for all rooms after the first one
                    connect the current room to the previous room
                    """
                    # Coordinates of the previous room
                    (prev_x, prev_y) = rooms[num_rooms - 1].center()
                    # Randomise the direction of the tunnel 1 == horizontal
                    if randint(0, 1) == 1:
                        # Move horizontal then vertical
                        self.create_h_tunnel(prev_x, new_x, prev_y)
                        self.create_v_tunnel(prev_y, new_y, new_x)
                    else:
                        # move vertical then horizontal
                        self.create_v_tunnel(prev_y, new_y, prev_x)
                        self.create_h_tunnel(prev_x, new_x, new_y)

                self.place_entities(new_room, entities, )

                # Finally add the new room to the room list
                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, '>', tcod.white, 'stairs',
                             render_order=RenderOrder.STAIRS, stairs=stairs_component)
        entities.append(down_stairs)
Example #40
0
from entity import Entity

player = Entity(charTile = "@", color = [255, 255, 255], name="Player", blocks_movement=True)

enemy = Entity(charTile = "E", color = [255, 255, 0], name="Enemy", blocks_movement=True)
Example #41
0
from entity import Entity, Point

a = Entity("object 1")

objects = [a, Entity("object 2"), Entity("object 3")]
for ob in objects:
    print ob
print 'selected: ', objects[1]

box = objects[1]

#remove
del objects[1]

for ob in objects:
    print ob

print 'in box: ', box
box.setName("new name!")
print box
Example #42
0
import tcod as libtcod
from random_utils import random_choice_from_dict, from_dungeon_level
from entity import Entity
from render_functions import RenderOrder
from components.fighter import Fighter
from components.ai import BasicMonster

monsters = {
    'orc':
    Entity([80],
           -1,
           -1,
           'o',
           libtcod.desaturated_green,
           'Orc',
           blocks=True,
           render_order=RenderOrder.ACTOR,
           fighter=Fighter(hp=20, defense=0, power=4, speed=150, xp=35),
           ai=BasicMonster()),
    'troll':
    Entity([[15, 3], [30, 5], [60, 7]],
           -1,
           -1,
           'T',
           libtcod.darker_green,
           'Troll',
           blocks=True,
           render_order=RenderOrder.ACTOR,
           fighter=Fighter(hp=30, defense=2, power=8, speed=200, xp=100),
           ai=BasicMonster()),
}
Example #43
0
 def __init__(self, row, col):
     Entity.__init__(self, row, col)
Example #44
0
    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 = {
            'quiz':
            80,
            'exam':
            from_dungeon_level([[15, 3], [30, 5], [60, 7]],
                               self.dungeon_level),
            'final':
            from_dungeon_level([[10, 3], [20, 5], [30, 7]], self.dungeon_level)
        }

        # Define chance for each type
        monster_type_chances = {
            'art': 25,
            'math': 25,
            'science': 25,
            'english': 25,
        }

        item_chances = {
            'healing_potion': 50,
            '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 == 'quiz':
                    if monster_type_choice == 'art':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=4,
                                                    name='Art Quiz',
                                                    xp=0,
                                                    subject='art')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         275,
                                         libtcod.white,
                                         'Art Quiz',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'math':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=4,
                                                    name='Math Quiz',
                                                    xp=0,
                                                    subject='math')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         278,
                                         libtcod.white,
                                         'Math Quiz',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'science':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=4,
                                                    name='Science Quiz',
                                                    xp=0,
                                                    subject='science')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         281,
                                         libtcod.white,
                                         'Science Quiz',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'english':

                        fighter_component = Fighter(hp=20,
                                                    defense=0,
                                                    power=4,
                                                    name='English Quiz',
                                                    xp=0,
                                                    subject='english')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         284,
                                         libtcod.white,
                                         'English Quiz',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                elif monster_choice == 'exam':
                    if monster_type_choice == 'art':

                        fighter_component = Fighter(hp=35,
                                                    defense=1,
                                                    power=6,
                                                    name='Art Exam',
                                                    xp=0,
                                                    subject='art')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         276,
                                         libtcod.white,
                                         'Art Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'math':

                        fighter_component = Fighter(hp=35,
                                                    defense=1,
                                                    power=6,
                                                    name='Math Exam',
                                                    xp=0,
                                                    subject='math')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         279,
                                         libtcod.white,
                                         'Math Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'science':

                        fighter_component = Fighter(hp=35,
                                                    defense=1,
                                                    power=6,
                                                    name='Science Exam',
                                                    xp=0,
                                                    subject='science')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         282,
                                         libtcod.white,
                                         'Science Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'english':

                        fighter_component = Fighter(hp=35,
                                                    defense=1,
                                                    power=6,
                                                    name='English Exam',
                                                    xp=0,
                                                    subject='english')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         285,
                                         libtcod.white,
                                         'English Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                elif monster_choice == 'final':
                    if monster_type_choice == 'art':

                        fighter_component = Fighter(hp=50,
                                                    defense=2,
                                                    power=8,
                                                    name='Art Final Exam',
                                                    xp=4,
                                                    subject='art')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         277,
                                         libtcod.white,
                                         'Art Final Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'math':

                        fighter_component = Fighter(hp=50,
                                                    defense=2,
                                                    power=8,
                                                    name='Math Final Exam',
                                                    xp=4,
                                                    subject='math')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         280,
                                         libtcod.white,
                                         'Math Final Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'science':

                        fighter_component = Fighter(hp=50,
                                                    defense=2,
                                                    power=8,
                                                    name='Science Final Exam',
                                                    xp=4,
                                                    subject='science')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         283,
                                         libtcod.white,
                                         'Science Final Exam',
                                         blocks=True,
                                         render_order=RenderOrder.ACTOR,
                                         fighter=fighter_component,
                                         ai=ai_component)

                    elif monster_type_choice == 'english':

                        fighter_component = Fighter(hp=50,
                                                    defense=2,
                                                    power=8,
                                                    name='English Final Exam',
                                                    xp=4,
                                                    subject='english')
                        ai_component = BasicMonster()
                        monster = Entity(x,
                                         y,
                                         286,
                                         libtcod.white,
                                         'English Final Exam',
                                         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,
                                  262,
                                  libtcod.white,
                                  'Relaxing Tea',
                                  render_order=RenderOrder.ITEM,
                                  item=item_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)
Example #45
0
 def __init__(self, name):
     self.name = name
     self.init_stats()
     Entity.__init__(self)
Example #46
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, 'Player', blocks=True)
    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
            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:
                    print('You kick the ' + target.name + ' in the shins, much to its annoyance!')
                else:
                    player.move(dx, dy)
                    fov_recompute = True

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
Example #47
0
    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 = {
            'sword': from_dungeon_level([[5, 4]], self.dungeon_level),
            'shield': from_dungeon_level([[15, 8]], self.dungeon_level),
            'healing_potion': 35,
            '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, 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=40)
                    item = Entity(x, y, '!', libtcod.violet, 'Healing Potion', render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_choice == 'sword':
                    equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=3)
                    item = Entity(x, y, '/', libtcod.sky, 'Sword', equippable=equippable_component)
                elif item_choice == 'shield':
                    equippable_component = Equippable(EquipmentSlots.OFF_HAND, defense_bonus=1)
                    item = Entity(x, y, '[', libtcod.darker_orange, 'Shield', equippable=equippable_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)
Example #48
0
    def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities):
        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)

            if r == 0 and self.dungeon_level != 1:
                up_stairs_component = Stairs(self.dungeon_level - 1)
                up_stairs = Entity(x + int(round(w / 2)), y + int(round(h / 2)), '<', libtcod.white, 'Stairs',
                                   render_order=RenderOrder.STAIRS, stairs=up_stairs_component)
                entities.append(up_stairs)

            # 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)

                rooms.append(new_room)
                num_rooms += 1

        down_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=down_stairs_component)
        entities.append(down_stairs)
Example #49
0
    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)

        # gets 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),
            "dragon":
            from_dungeon_level([[10, 7], [20, 10], [30, 14]],
                               self.dungeon_level)
        }
        item_chances = {
            "health_potion": 35,
            "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),
            "betrayal_scroll": from_dungeon_level([[10, 5]],
                                                  self.dungeon_level),
            "iron_sword": from_dungeon_level([[5, 4]], self.dungeon_level),
            "wooden_shield": from_dungeon_level([[15, 8]], 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 == "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)
                elif monster_choice == "troll":
                    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)
                elif monster_choice == "dragon":
                    fighter_component = Fighter(hp=40,
                                                defense=2,
                                                power=12,
                                                xp=500)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     "D",
                                     libtcod.dark_red,
                                     "Dragon",
                                     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 == "health_potion":
                    item_component = Item(use_function=heal, amount=40)
                    item = Entity(x,
                                  y,
                                  "!",
                                  libtcod.violet,
                                  "Health Potion",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_choice == "fireball_scroll":
                    item_component = Item(
                        use_function=cast_fireball,
                        targeting=True,
                        targeting_message=Message(
                            "Left-click a tile to target, or right-click to cancel.",
                            libtcod.light_cyan),
                        damage=25,
                        radius=3)
                    item = Entity(x,
                                  y,
                                  "#",
                                  libtcod.red,
                                  "Fireball Scroll",
                                  False,
                                  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 a tile to target, or right-click to cancel",
                            libtcod.light_cyan))
                    item = Entity(x,
                                  y,
                                  "#",
                                  libtcod.light_pink,
                                  "Confusion Scroll",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)

                elif item_choice == "betrayal_scroll":
                    item_component = Item(
                        use_function=cast_betrayal,
                        targeting=True,
                        targeting_message=Message(
                            "Left-click a tile to target, or right-click to cancel",
                            libtcod.light_cyan))
                    item = Entity(x,
                                  y,
                                  '#',
                                  libtcod.black,
                                  "Betrayal Scroll",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_choice == "lightning_scroll":
                    item_component = Item(use_function=cast_lightning,
                                          damage=40,
                                          maximum_range=5)
                    item = Entity(x,
                                  y,
                                  "#",
                                  libtcod.yellow,
                                  "Lightning Scroll",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_choice == "iron_sword":
                    equippable_component = Equippable(EquipmentSlots.MAIN_HAND,
                                                      power_bonus=3)
                    item = Entity(x,
                                  y,
                                  "/",
                                  libtcod.silver,
                                  "Iron Sword",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  equippable=equippable_component)
                elif item_choice == "wooden_shield":
                    equippable_component = Equippable(EquipmentSlots.OFF_HAND,
                                                      defense_bonus=1)
                    item = Entity(x,
                                  y,
                                  "[",
                                  libtcod.darker_orange,
                                  "Wooden Shield",
                                  False,
                                  render_order=RenderOrder.ITEM,
                                  equippable=equippable_component)
                entities.append(item)
Example #50
0
def main():

    # Screen settings
    screen_width = 80
    screen_height = 45

    # Map creation settings
    map_width = 80
    map_height = 45

    # Room creation settings
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    # FOV settings - passed to libtcod library
    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    # Color Dictionary for entities
    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 player entity and entities list - monsters appended at map creation
    max_monsters_per_room = 3

    player = Entity(0, 0, '@', libtcod.white, 'my dude', blocks=True)
    entities = [player]

    # Console settings and initialisation
    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_TCOD)
    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    # Set up the console
    con = libtcod.console_new(screen_width, screen_height)

    # Create the map object and trigger dungeon creation
    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)

    # Controller mappings
    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN

    # Main Loop
    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)

        # TODO - wouldn't it make more sense to move this under recompute_fov() call?
        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 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:
                    print('You kick the ' + target.name +
                          ' squarely in the nards, much to its dismay')

                else:
                    player.move(dx, dy)
                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        if exit:
            return True

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

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity != player:
                    print('The ' + entity.name +
                          ' scratches itself in an unpleasant fashion.')

            game_state = GameStates.PLAYERS_TURN
Example #51
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):
        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 boundaries
            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 check if they interact with new_room
            for other_room in rooms:
                if new_room.intersect(other_room):
                    break

            else:
                #if loop did not break, i.e. there were no intersections
                #paint it to the map's tiles
                self.create_room(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 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 (0, 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)

                self.place_entities(new_room, entities, max_monsters_per_room,
                                    max_items_per_room)

                #finally, append the new room to the list
                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)
Example #52
0
    def return_potions(self, x, y):
        item_chances = {
            'a': 10,
            'b': from_dungeon_level([[2, 4]], self.dungeon_level),
            'c': from_dungeon_level([[3, 4]], self.dungeon_level),
            'd': from_dungeon_level([[4, 4]], self.dungeon_level),
            'e': from_dungeon_level([[5, 4]], self.dungeon_level),
            'f': from_dungeon_level([[6, 4]], self.dungeon_level),
            'g': from_dungeon_level([[6, 4]], self.dungeon_level),
            'h': from_dungeon_level([[2, 4]], self.dungeon_level),
            'i': from_dungeon_level([[2, 4]], self.dungeon_level),
            'j': from_dungeon_level([[3, 4]], self.dungeon_level),
            'k': from_dungeon_level([[3, 4]], self.dungeon_level)
        }

        item_choice = random_choice_from_dict(item_chances)

        if item_choice == 'a':
            item_component = Item(use_function=heal, amount=20)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Lesser Healing Potion',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'b':
            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 == 'c':
            item_component = Item(use_function=heal, amount=60)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Large Healing Potion',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'd':
            item_component = Item(use_function=flood, amount=20)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Lesser Blud Potion',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'e':
            item_component = Item(use_function=seal, amount=20)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Lesser Bottle of Blud Storage',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'f':
            item_component = Item(use_function=flood, amount=40)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Blud Potion',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'g':
            item_component = Item(use_function=seal, amount=40)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Bottle of Blud Storage',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'h':
            item_component = Item(use_function=flood, amount=60)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Large Blud Potion',
                          render_order=RenderOrder.ITEM,
                          item=item_component)
        elif item_choice == 'i':
            item_component = Item(use_function=seal, amount=60)
            item = Entity(x,
                          y,
                          '!',
                          libtcod.violet,
                          'Large Bottle of Blud Storage',
                          render_order=RenderOrder.ITEM,
                          item=item_component)

        # Return the glass material so we get broken shards out of use
        item.material = 'glass'

        return item
Example #53
0
    def place_entities_at_nook(self, entities, min_monsters, max_monsters,
                               max_items):
        # 벽 지도 생성
        wall_map = np.zeros((self.height, self.width), dtype='uint8')
        for y in range(self.height):
            for x in range(self.width):
                wall_map[y, x] = 1 if self.tiles[y, x].blocked else 0

        # 구석 개수 설정
        nooks = find_nook(wall_map)
        monster_num = randint(min_monsters, max_monsters)

        # 몬스터 배치
        monster_chance = {'CI': 80, 'GS': 20, "FA": 10}
        for j in range(monster_num):
            ai_comp = BasicAi()
            choice = random_choice_from_dict(monster_chance)

            if j < len(nooks):
                mx = nooks[j][1]
                my = nooks[j][0]
            else:
                # 구석진 곳이 모자르면 지도에서 무작위로 좌표를 뽑아옴
                my, mx = self.np_find_empty_cell(entities, wall_map)

            if choice == 'CI':
                f_comp = Fighter(hp=10, defense=0, power=3)
                monster = self.create_monster(mx, my, '~', tcod.flame,
                                              '기어다니는 내장', f_comp, ai_comp)
            elif choice == 'GS':
                f_comp = Fighter(hp=16, defense=1, power=4)
                monster = self.create_monster(mx, my, 'S', tcod.dark_green,
                                              '거대 거미', f_comp, ai_comp)
            elif choice == 'FA':
                f_comp = Fighter(hp=20, defense=0, power=7)
                monster = self.create_monster(mx, my, '@',
                                              tcod.Color(128, 5, 5),
                                              '사람을 닮은 무언가', f_comp, ai_comp)
            entities.append(monster)
            self.monsters += 1  #계산용

        # 아이템 배치, 아직 임시
        shuffle(nooks)
        #item_chance = {'FB':5}
        item_chance = {
            'FJ': 60,
            'REG': 30,
            'FB': 10,
            "SC": 10,
            'FLW': 10,
            'SCF': 5,
            'SWD': 5,
            'SLD': 5,
            'AM': 1
        }  #'BK': 20 # #

        for i in range(len(nooks)):
            kinds = random_choice_from_dict(item_chance)

            if j < len(nooks):
                ix = nooks[i][1]
                iy = nooks[i][0]
            else:
                # 구석진 곳이 모자르면 지도에서 무작위로 좌표를 뽑아옴
                ix, iy = self.np_find_empty_cell(entities, wall_map)

            if kinds == 'REG':
                i_comp = Item(use_function=heal, amount=10)
                item = self.create_item(ix,
                                        iy,
                                        '!',
                                        tcod.violet,
                                        '재생 물약',
                                        item=i_comp)
            elif kinds == 'FJ':
                i_comp = Item(use_function=heal, amount=15, which='sanity')
                item = self.create_item(ix,
                                        iy,
                                        '!',
                                        tcod.orange,
                                        '과일 주스',
                                        item=i_comp)
            elif kinds == 'SC':
                i_comp = Item(use_function=cast_spell,
                              damage=(1, 30),
                              maximum_range=8)
                item = self.create_item(ix,
                                        iy,
                                        '?',
                                        tcod.green,
                                        '마법 불꽃의 주문서',
                                        item=i_comp)
            elif kinds == 'FB':
                i_comp = Item(use_function=cast_fireball,
                              targeting=True,
                              targeting_message=Message(
                                  SYS_LOG['target_message'], tcod.light_cyan),
                              damage=(3, 8, 5),
                              radius=3)
                item = self.create_item(ix,
                                        iy,
                                        '?',
                                        tcod.red,
                                        '화염 폭발의 주문서',
                                        item=i_comp)
            elif kinds == 'SCF':
                scarfs_list = {
                    '보라': tcod.violet,
                    '빨강': tcod.dark_red,
                    '초록': tcod.green,
                    '파랑': tcod.blue
                }
                from random import sample
                pick = sample(list(scarfs_list), 1)[0]
                if pick == '초록':
                    resist = 60
                else:
                    resist = 50
                e_comp = Equippable(EquipmentSlots.SCARF,
                                    sanity_resistance=resist)
                item = Entity(ix,
                              iy,
                              '>',
                              scarfs_list[pick],
                              f"{pick}색 목도리",
                              _Equippable=e_comp)
            elif kinds == 'SWD':
                e_comp = Equippable(EquipmentSlots.WIELD, attack_power=5)
                item = Entity(ix, iy, '/', tcod.gray, "검", _Equippable=e_comp)
            elif kinds == 'SLD':
                e_comp = Equippable(EquipmentSlots.OUTFIT, defense_power=5)
                item = Entity(ix,
                              iy,
                              '}',
                              tcod.lighter_gray,
                              "방패",
                              _Equippable=e_comp)
            elif kinds == 'FLW':
                e_comp = Equippable(EquipmentSlots.JEWELLERY,
                                    sanity_resistance=20)
                item = Entity(ix,
                              iy,
                              '*',
                              tcod.white,
                              "국화꽃 팔찌",
                              _Equippable=e_comp)
            elif kinds == "AM":
                e_comp = Equippable(EquipmentSlots.JEWELLERY,
                                    sanity_resistance=-80,
                                    attack_power=10)
                item = Entity(ix,
                              iy,
                              '&',
                              tcod.white,
                              "어딘가 잘못된 목걸이",
                              _Equippable=e_comp)
            entities.append(item)
        """
Example #54
0
    def tick(self, walls, projectiles, debug=False, **kwargs):

        # if debug: self._printinfo()

        for p in projectiles:
            if self.isCollidingWith(p):
                self.dead = True
                p.dead = True

        # For left and right:
        # If pushed and was not previously pushed:
        # 	Add movementModifier in appropriate direction
        # 	Note as currently pushed
        # 	Change facing direction
        # If not pushed:
        # 	if both directions are held:
        #		take away movement modifier

        if self.buttons["left"]:
            if not self.held["left"]:
                if debug: print("left down")
                self.velocity[0] -= self._movementModifier
                self.held["left"] = True
                self.facing = "left"
        else:
            if self.held["left"] and self.held["right"]:
                self.velocity[0] += self._movementModifier
            elif self.held["left"]:
                self.velocity[0] = 0
            self.held["left"] = False

        if self.buttons["right"]:
            if not self.held["right"]:
                if debug: print("right down")
                self.velocity[0] += self._movementModifier
                self.held["right"] = True
                self.facing = "right"
        else:
            if self.held["right"] and self.held["left"]:
                self.velocity[0] -= self._movementModifier
            elif self.held["right"]:
                self.velocity[0] = 0
            self.held["right"] = False

        if self.buttons["jump"]:
            if not self.held["jump"] and self.onGround:
                if debug: print("jump down")
                self.velocity[1] -= self._jumpModifier
                self.held["jump"] = True
                self.onGround = False
        else:
            self.held["jump"] = False

        if self.buttons["down"]:
            if not self.held["down"]:
                if debug: print("down down")
                self.held["down"] = True
        else:
            self.held["down"] = False

        if self.buttons["attack"]:
            if not self.held["attack"]:
                self.held["attack"] = True
                self.shot = True
        else:
            self.held["attack"] = False

        if self.buttons["interact"]:
            if not self.held["interact"]:
                pass
                self.held["interact"] = True
        else:
            self.held["interact"] = False

        collisions = Entity.tick(self, walls, debug=debug)

        if collisions["right"] and self.held["right"]:
            self.held["right"] = False
        if collisions["left"] and self.held["left"]:
            self.held["left"] = False

        self.setMod()
Example #55
0
 def get_state(self):
     return {"wall_state": self.state, **Entity.get_state(self)}
Example #56
0
 def update(self, dt):
     Entity.update(self, dt)
Example #57
0
 def __init__(self, position, mailbox):
     Entity.__init__(self, position, mailbox)
Example #58
0
def main():
    # Screen size
    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 size
    map_width = 80
    map_height = 43
    # Map Rooms
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    # Visiblity
    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)
    }

    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]

    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 reviesed', False,
                              libtcod.RENDERER_SDL2, 'C', True)

    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)

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

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

    game_state = GameStates.PLAYERS_TURN

    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)

        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')

        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

        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
Example #59
0
 def setUp(self):
     self.entity = Entity("Monster", 100)
Example #60
0
import curses
import time
from entity import Entity

screen = curses.initscr()
curses.noecho()  #turn off echoing input
curses.cbreak()  #don't wait for enter key

height, width = screen.getmaxyx()
win = curses.newwin(height, width, 0, 0)

win.keypad(1)
curses.curs_set(0)  #Hide the blinking cursor

player = Entity(10, 10, ord('@'))
mob = [20, 20]

colors = {'dark_wall': curses.COLOR_MAGENTA}

key = curses.KEY_RIGHT

while True:
    win.border(0)
    win.timeout(100)

    key = win.getch()

    if key == ord('q'):
        curses.nocbreak()
        screen.keypad(False)
        curses.echo()