Example #1
0
def explore_unknown_chunks(life):
    if life['path']:
        return True

    _chunk_key = references.path_along_reference(life, 'roads')

    if not _chunk_key:
        return False

    _walkable_area = chunks.get_walkable_areas(_chunk_key)
    if not _walkable_area:
        print 'no walkable area'
        return False

    _closest_pos = {'pos': None, 'distance': -1}
    for pos in _walkable_area:
        _distance = numbers.distance(life['pos'], pos)

        if _distance <= 1:
            _closest_pos['pos'] = pos
            break

        if not _closest_pos['pos'] or _distance < _closest_pos['distance']:
            _closest_pos['pos'] = pos
            _closest_pos['distance'] = _distance

    lfe.clear_actions(life)
    lfe.add_action(life, {'action': 'move', 'to': _closest_pos['pos']}, 200)

    return True
Example #2
0
def explore_known_chunks(life):
    # Our first order of business is to figure out exactly what we're looking for.
    # There's a big difference between exploring the map looking for a purpose and
    # exploring the map with a purpose. Both will use similar routines but I wager
    # it'll actually be a lot harder to do it without there being some kind of goal
    # to at least start us in the right direction.

    # This function will kick in only if the ALife is idling, so looting is handled
    # automatically.

    # Note: Determining whether this fuction should run at all needs to be done inside
    # the module itself.
    _chunk_key = brain.retrieve_from_memory(life, "explore_chunk")
    _chunk = maps.get_chunk(_chunk_key)

    if life["path"] and chunks.position_is_in_chunk(lfe.path_dest(life), _chunk_key):
        return True

    if chunks.is_in_chunk(life, "%s,%s" % (_chunk["pos"][0], _chunk["pos"][1])):
        life["known_chunks"][_chunk_key]["last_visited"] = WORLD_INFO["ticks"]
        return False

    if not _chunk["ground"]:
        return False

    _pos_in_chunk = random.choice(_chunk["ground"])
    lfe.clear_actions(life)
    lfe.add_action(life, {"action": "move", "to": _pos_in_chunk}, 200)
    return True
Example #3
0
def find_target(life, target, distance=5, follow=False, call=True):
	_target = brain.knows_alife_by_id(life, target)
	_dist = numbers.distance(life['pos'], _target['last_seen_at'])
	
	_can_see = sight.can_see_target(life, target)
	if _can_see and _dist<=distance:
		if follow:
			return True
		
		lfe.stop(life)
		
		return True
	
	if _target['escaped'] == 1:
		search_for_target(life, target)
		return False
	
	if not _can_see and sight.can_see_position(life, _target['last_seen_at']) and _dist<distance:
		if call:
			if not _target['escaped']:
				memory.create_question(life, target, 'GET_LOCATION')
				
			speech.communicate(life, 'call', matches=[target])
		
		_target['escaped'] = 1
		
		return False
	
	if not lfe.path_dest(life) == tuple(_target['last_seen_at'][:2]):
		lfe.clear_actions(life)
		lfe.add_action(life,
			          {'action': 'move','to': _target['last_seen_at'][:2]},
			          200)
	
	return False
Example #4
0
def explore_unknown_chunks(life):
	if life['path']:
		return True
	
	_chunk_key = references.path_along_reference(life, 'roads')
	
	if not _chunk_key:
		return False
	
	_walkable_area = chunks.get_walkable_areas(_chunk_key)
	if not _walkable_area:
		print 'no walkable area'
		return False
	
	_closest_pos = {'pos': None, 'distance': -1}
	for pos in _walkable_area:
		_distance = bad_numbers.distance(life['pos'], pos)
				
		if _distance <= 1:
			_closest_pos['pos'] = pos
			break
		
		if not _closest_pos['pos'] or _distance<_closest_pos['distance']:
			_closest_pos['pos'] = pos
			_closest_pos['distance'] = _distance
	
	lfe.clear_actions(life)
	lfe.add_action(life,{'action': 'move','to': _closest_pos['pos']},200)
	
	return True
Example #5
0
def understand(life):
	if SETTINGS['controlling']:
		_dist_to_player = numbers.distance(life['pos'], LIFE[SETTINGS['controlling']]['pos'])
		if _dist_to_player < 100:
			if life['think_rate_max']>=30:
				if _dist_to_player < 75:
					life['think_rate_max'] = 1
					life['online'] = True
					logging.debug('[Agent] %s brought online (Reason: Near viewer)' % ' '.join(life['name']))
				
			else:
				life['think_rate_max'] = 1
		else:
			if _dist_to_player >= OFFLINE_ALIFE_DISTANCE and life['online']:
				life['online'] = False
				logging.debug('[Agent] %s went offline (Reason: Away from viewer)' % ' '.join(life['name']))
			elif life['think_rate_max']<30:
				if _dist_to_player < OFFLINE_ALIFE_DISTANCE:
					life['online'] = True
				
				logging.debug('[Agent] %s went passive (Reason: Away from viewer)' % ' '.join(life['name']))
			
			life['think_rate_max'] = numbers.clip(15*(((_dist_to_player-100)+30)/30), 30, 60)
	else:
		life['think_rate_max'] = 5
	
	if not life['online'] or life['asleep']:
		return False
	
	if len(life['actions'])-len(lfe.find_action(life, matches=[{'action': 'move'}, {'action': 'dijkstra_move'}]))>0:
		lfe.clear_actions(life)
		life['path'] = []
		
		return False
	
	if life['think_rate']>0:
		life['think_rate'] -= 1
		
		return False
	
	for module in CONSTANT_MODULES:
		module.setup(life)
	
	life['think_rate'] = life['think_rate_max']
	
	#if life['name'][0].startswith('Tim'):
	#	_goal, _tier, _plan = planner.get_next_goal(life, debug='attack')
	#else:
	_goal, _tier, _plan = planner.get_next_goal(life)
	
	if _goal:
		lfe.change_goal(life, _goal, _tier, _plan)
	else:
		lfe.change_goal(life, 'idle', TIER_RELAXED, [])
		#logging.error('%s has no possible goal.' % ' '.join(life['name']))
		
		return False
	
	planner.think(life)
	
Example #6
0
def collect_nearby_wanted_items(life,
                                only_visible=True,
                                matches={'type': 'gun'}):
    _highest = {'item': None, 'score': -100000}
    _nearby = sight.find_known_items(life,
                                     matches=matches,
                                     only_visible=only_visible)

    for item in _nearby:
        _item = brain.get_remembered_item(life, item)
        _score = _item['score']
        _score -= bad_numbers.distance(life['pos'], ITEMS[item]['pos'])

        if not _highest['item'] or _score > _highest['score']:
            _highest['score'] = _score
            _highest['item'] = ITEMS[item]

    if not _highest['item']:
        return True

    _empty_hand = lfe.get_open_hands(life)

    if not _empty_hand:
        print 'No open hands, managing....'
        for item_uid in lfe.get_held_items(life):
            _container = lfe.can_put_item_in_storage(life, item_uid)

            lfe.add_action(life, {
                'action': 'storeitem',
                'item': item_uid,
                'container': _container
            },
                           200,
                           delay=lfe.get_item_access_time(life, item_uid))
        return False

    if life['pos'] == _highest['item']['pos']:
        lfe.clear_actions(life)

        for action in lfe.find_action(life,
                                      matches=[{
                                          'action': 'pickupholditem'
                                      }]):
            #print 'I was picking up something else...',_highest['item']['name']
            return False

        lfe.add_action(life, {
            'action': 'pickupholditem',
            'item': _highest['item']['uid'],
            'hand': random.choice(_empty_hand)
        },
                       200,
                       delay=lfe.get_item_access_time(life,
                                                      _highest['item']['uid']))
        lfe.lock_item(life, _highest['item']['uid'])
    else:
        lfe.walk_to(life, _highest['item']['pos'])

    return False
Example #7
0
def conditions(life, alife_seen, alife_not_seen, targets_seen, targets_not_seen, source_map):
	RETURN_VALUE = STATE_UNCHANGED
	
	if not lfe.execute_raw(life, 'state', 'hide'):
		if life['state'] == STATE:
			lfe.clear_actions(life)
			
		return False
	
	if not life['state'] == STATE:
		RETURN_VALUE = STATE_CHANGE
	
	return RETURN_VALUE
Example #8
0
def conditions(life, alife_seen, alife_not_seen, targets_seen,
               targets_not_seen, source_map):
    RETURN_VALUE = STATE_UNCHANGED

    if not lfe.execute_raw(life, 'state', 'guard'):
        if life['state'] == STATE:
            lfe.clear_actions(life)

        return False

    if not life['state'] == STATE:
        RETURN_VALUE = STATE_CHANGE

    return RETURN_VALUE
Example #9
0
def collect_nearby_wanted_items(life, only_visible=True, matches={"type": "gun"}):
    _highest = {"item": None, "score": -100000}
    _nearby = sight.find_known_items(life, matches=matches, only_visible=only_visible)

    for item in _nearby:
        _item = brain.get_remembered_item(life, item)
        _score = _item["score"]
        _score -= numbers.distance(life["pos"], ITEMS[item]["pos"])

        if not _highest["item"] or _score > _highest["score"]:
            _highest["score"] = _score
            _highest["item"] = ITEMS[item]

    if not _highest["item"]:
        return True

    _empty_hand = lfe.get_open_hands(life)

    if not _empty_hand:
        print "No open hands, managing...."
        for item_uid in lfe.get_held_items(life):
            _container = lfe.can_put_item_in_storage(life, item_uid)

            lfe.add_action(
                life,
                {"action": "storeitem", "item": item_uid, "container": _container},
                200,
                delay=lfe.get_item_access_time(life, item_uid),
            )
        return False

    if life["pos"] == _highest["item"]["pos"]:
        lfe.clear_actions(life)

        for action in lfe.find_action(life, matches=[{"action": "pickupholditem"}]):
            # print 'I was picking up something else...',_highest['item']['name']
            return False

        lfe.add_action(
            life,
            {"action": "pickupholditem", "item": _highest["item"]["uid"], "hand": random.choice(_empty_hand)},
            200,
            delay=lfe.get_item_access_time(life, _highest["item"]["uid"]),
        )
        lfe.lock_item(life, _highest["item"]["uid"])
    else:
        lfe.walk_to(life, _highest["item"]["pos"])

    return False
Example #10
0
def travel_to_position(life, pos, stop_on_sight=False):
	if stop_on_sight and sight.can_see_position(life, pos):
		return True
	
	if not numbers.distance(life['pos'], pos):
		return True
	
	_dest = lfe.path_dest(life)
	if _dest and tuple(_dest[:2]) == tuple(pos[:2]):
		return False
	
	lfe.clear_actions(life)
	lfe.add_action(life,{'action': 'move','to': (pos[0],pos[1])},200)
	
	return False
Example #11
0
def collect_nearby_wanted_items(life, only_visible=True, matches={'type': 'gun'}):
	_highest = {'item': None,'score': -100000}
	_nearby = sight.find_known_items(life, matches=matches, only_visible=only_visible)
	
	for item in _nearby:
		_item = brain.get_remembered_item(life, item)
		_score = _item['score']
		_score -= numbers.distance(life['pos'], ITEMS[item]['pos'])
		
		if not _highest['item'] or _score > _highest['score']:
			_highest['score'] = _score
			_highest['item'] = ITEMS[item]
	
	if not _highest['item']:
		return True
	
	_empty_hand = lfe.get_open_hands(life)
	
	if not _empty_hand:
		print 'No open hands, managing....'
		for item_uid in lfe.get_held_items(life):
			_container = lfe.can_put_item_in_storage(life, item_uid)
			
			lfe.add_action(life, {'action': 'storeitem',
				'item': item_uid,
			     'container': _container},
				200,
				delay=lfe.get_item_access_time(life, item_uid))
		return False
	
	if life['pos'] == _highest['item']['pos']:
		lfe.clear_actions(life)
		
		for action in lfe.find_action(life, matches=[{'action': 'pickupholditem'}]):
			#print 'I was picking up something else...',_highest['item']['name']
			return False
		
		lfe.add_action(life,{'action': 'pickupholditem',
			'item': _highest['item']['uid'],
			'hand': random.choice(_empty_hand)},
			200,
			delay=lfe.get_item_access_time(life, _highest['item']['uid']))
		lfe.lock_item(life, _highest['item']['uid'])
	else:
		lfe.clear_actions(life)
		lfe.add_action(life,{'action': 'move','to': _highest['item']['pos'][:2]},200)
	
	return False
Example #12
0
def explore_unknown_chunks(life):
    if life["path"]:
        return True

    _chunk_key = references.path_along_reference(life, "roads")

    if not _chunk_key:
        _best_reference = references._find_best_unknown_reference(life, "roads")["reference"]
        if not _best_reference:
            return False

        _chunk_key = references.find_nearest_key_in_reference(life, _best_reference, unknown=True, threshold=15)

    if not _chunk_key:
        return False

    _walkable_area = chunks.get_walkable_areas(_chunk_key)
    if not _walkable_area:
        print "no walkable area"
        return False

    _closest_pos = {"pos": None, "distance": -1}
    for pos in _walkable_area:
        _distance = numbers.distance(life["pos"], pos)

        if _distance <= 1:
            _closest_pos["pos"] = pos
            break

        if not _closest_pos["pos"] or _distance < _closest_pos["distance"]:
            _closest_pos["pos"] = pos
            _closest_pos["distance"] = _distance

    lfe.clear_actions(life)
    lfe.add_action(life, {"action": "move", "to": _closest_pos["pos"]}, 200)

    return True
Example #13
0
def ranged_combat(life, targets):
	_target = brain.knows_alife_by_id(life, get_closest_target(life, targets))
	
	#if not _target:
	#	for target_id in targets:
	#		if brain.knows_alife_by_id(life, target_id)['escaped']:
	#			continue
	#		
	#		brain.knows_alife_by_id(life, target_id)['escaped'] = 1
	#	
	#	logging.error('No target for ranged combat.')
	#	
	#	return False
	
	_engage_distance = get_engage_distance(life)
	_path_dest = lfe.path_dest(life)
	
	if not _path_dest:
		_path_dest = life['pos'][:]
	
	_target_distance = bad_numbers.distance(life['pos'], _target['last_seen_at'])
	
	#Get us near the target
	#if _target['last_seen_at']:
	movement.position_to_attack(life, _target['life']['id'], _engage_distance)
		
	if sight.can_see_position(life, _target['last_seen_at']):
		if _target_distance	<= _engage_distance:
			if sight.can_see_position(life, _target['life']['pos']):
				if not sight.view_blocked_by_life(life, _target['life']['pos'], allow=[_target['life']['id']]):
					lfe.clear_actions(life)
					
					if not len(lfe.find_action(life, matches=[{'action': 'shoot'}])) and _target['time_visible']>2:
						for i in range(weapons.get_rounds_to_fire(weapons.get_weapon_to_fire(life))):
							lfe.add_action(life, {'action': 'shoot',
							                      'target': _target['last_seen_at'],
							                      'target_id': _target['life']['id'],
							                      'limb': 'chest'},
							               300,
							               delay=int(round(life['recoil']-stats.get_recoil_recovery_rate(life))))
				else:
					_friendly_positions, _friendly_zones = get_target_positions_and_zones(life, judgement.get_trusted(life))
					_friendly_zones.append(zones.get_zone_at_coords(life['pos']))
					_friendly_positions.append(life['pos'][:])
					
					if not lfe.find_action(life, [{'action': 'dijkstra_move', 'orig_goals': [_target['life']['pos'][:]], 'avoid_positions': _friendly_positions}]):
						lfe.add_action(life, {'action': 'dijkstra_move',
						                      'rolldown': True,
						                      'zones': _friendly_zones,
						                      'goals': [_target['life']['pos'][:]],
						                      'orig_goals': [_target['life']['pos'][:]],
						                      'avoid_positions': _friendly_positions,
						                      'reason': 'combat_position'},
						               100)
			else:
				lfe.memory(life,'lost sight of %s' % (' '.join(_target['life']['name'])), target=_target['life']['id'])
				
				_target['escaped'] = 1
				
				for send_to in judgement.get_trusted(life):
					speech.communicate(life,
					                   'target_missing',
					                   target=_target['life']['id'],
					                   matches=[send_to])
		#else:
			#print life['name']
			#_friendly_positions, _friendly_zones = get_target_positions_and_zones(life, judgement.get_trusted(life))
			#_friendly_zones.append(zones.get_zone_at_coords(life['pos']))
			#_friendly_positions.append(life['pos'][:])
			
			#if not lfe.find_action(life, [{'action': 'dijkstra_move', 'orig_goals': [_target['life']['pos'][:]], 'avoid_positions': _friendly_positions}]):
			#	lfe.add_action(life, {'action': 'dijkstra_move',
			#		                'rolldown': True,
			#		                'zones': _friendly_zones,
			#		                'goals': [_target['life']['pos'][:]],
			#		                'orig_goals': [_target['life']['pos'][:]],
			#		                'avoid_positions': _friendly_positions,
			#		                'reason': 'combat_position'},
			#		         100)
			#	
			#	print '2'
		
	else:
		return False
Example #14
0
def ranged_combat(life, targets):
    _target = brain.knows_alife_by_id(life, get_closest_target(life, targets))

    #if not _target:
    #	for target_id in targets:
    #		if brain.knows_alife_by_id(life, target_id)['escaped']:
    #			continue
    #
    #		brain.knows_alife_by_id(life, target_id)['escaped'] = 1
    #
    #	logging.error('No target for ranged combat.')
    #
    #	return False

    _engage_distance = get_engage_distance(life)
    _path_dest = lfe.path_dest(life)

    if not _path_dest:
        _path_dest = life['pos'][:]

    _target_distance = bad_numbers.distance(life['pos'],
                                            _target['last_seen_at'])

    #Get us near the target
    #if _target['last_seen_at']:
    movement.position_to_attack(life, _target['life']['id'], _engage_distance)

    if sight.can_see_position(life, _target['last_seen_at']):
        if _target_distance <= _engage_distance:
            if sight.can_see_position(life, _target['life']['pos']):
                if not sight.view_blocked_by_life(
                        life,
                        _target['life']['pos'],
                        allow=[_target['life']['id']]):
                    lfe.clear_actions(life)

                    if not len(
                            lfe.find_action(
                                life, matches=[{
                                    'action': 'shoot'
                                }])) and _target['time_visible'] > 2:
                        for i in range(
                                weapons.get_rounds_to_fire(
                                    weapons.get_weapon_to_fire(life))):
                            lfe.add_action(
                                life, {
                                    'action': 'shoot',
                                    'target': _target['last_seen_at'],
                                    'target_id': _target['life']['id'],
                                    'limb': 'chest'
                                },
                                300,
                                delay=int(
                                    round(
                                        life['recoil'] -
                                        stats.get_recoil_recovery_rate(life))))
                else:
                    _friendly_positions, _friendly_zones = get_target_positions_and_zones(
                        life, judgement.get_trusted(life))
                    _friendly_zones.append(
                        zones.get_zone_at_coords(life['pos']))
                    _friendly_positions.append(life['pos'][:])

                    if not lfe.find_action(
                            life, [{
                                'action': 'dijkstra_move',
                                'orig_goals': [_target['life']['pos'][:]],
                                'avoid_positions': _friendly_positions
                            }]):
                        lfe.add_action(
                            life, {
                                'action': 'dijkstra_move',
                                'rolldown': True,
                                'zones': _friendly_zones,
                                'goals': [_target['life']['pos'][:]],
                                'orig_goals': [_target['life']['pos'][:]],
                                'avoid_positions': _friendly_positions,
                                'reason': 'combat_position'
                            }, 100)
            else:
                lfe.memory(life,
                           'lost sight of %s' %
                           (' '.join(_target['life']['name'])),
                           target=_target['life']['id'])

                _target['escaped'] = 1

                for send_to in judgement.get_trusted(life):
                    speech.communicate(life,
                                       'target_missing',
                                       target=_target['life']['id'],
                                       matches=[send_to])
        #else:
        #print life['name']
        #_friendly_positions, _friendly_zones = get_target_positions_and_zones(life, judgement.get_trusted(life))
        #_friendly_zones.append(zones.get_zone_at_coords(life['pos']))
        #_friendly_positions.append(life['pos'][:])

        #if not lfe.find_action(life, [{'action': 'dijkstra_move', 'orig_goals': [_target['life']['pos'][:]], 'avoid_positions': _friendly_positions}]):
        #	lfe.add_action(life, {'action': 'dijkstra_move',
        #		                'rolldown': True,
        #		                'zones': _friendly_zones,
        #		                'goals': [_target['life']['pos'][:]],
        #		                'orig_goals': [_target['life']['pos'][:]],
        #		                'avoid_positions': _friendly_positions,
        #		                'reason': 'combat_position'},
        #		         100)
        #
        #	print '2'

    else:
        return False
Example #15
0
def understand(life):
    if SETTINGS['controlling']:
        _dist_to_player = numbers.distance(
            life['pos'], LIFE[SETTINGS['controlling']]['pos'])
        if _dist_to_player < 100:
            if life['think_rate_max'] >= 30:
                if _dist_to_player < 75:
                    life['think_rate_max'] = 1
                    life['online'] = True
                    logging.debug(
                        '[Agent] %s brought online (Reason: Near viewer)' %
                        ' '.join(life['name']))

            else:
                life['think_rate_max'] = 1
        else:
            if _dist_to_player >= OFFLINE_ALIFE_DISTANCE and life['online']:
                life['online'] = False
                logging.debug(
                    '[Agent] %s went offline (Reason: Away from viewer)' %
                    ' '.join(life['name']))
            elif life['think_rate_max'] < 30:
                if _dist_to_player < OFFLINE_ALIFE_DISTANCE:
                    life['online'] = True

                logging.debug(
                    '[Agent] %s went passive (Reason: Away from viewer)' %
                    ' '.join(life['name']))

            life['think_rate_max'] = numbers.clip(
                15 * (((_dist_to_player - 100) + 30) / 30), 30, 60)
    else:
        life['think_rate_max'] = 5

    if not life['online'] or life['asleep']:
        return False

    if len(life['actions']) - len(
            lfe.find_action(life,
                            matches=[{
                                'action': 'move'
                            }, {
                                'action': 'dijkstra_move'
                            }])) > 0:
        lfe.clear_actions(life)
        life['path'] = []

        return False

    if life['think_rate'] > 0:
        life['think_rate'] -= 1

        return False

    for module in CONSTANT_MODULES:
        module.setup(life)

    life['think_rate'] = life['think_rate_max']

    #if life['name'][0].startswith('Tim'):
    #	_goal, _tier, _plan = planner.get_next_goal(life, debug='attack')
    #else:
    _goal, _tier, _plan = planner.get_next_goal(life)

    if _goal:
        lfe.change_goal(life, _goal, _tier, _plan)
    else:
        lfe.change_goal(life, 'idle', TIER_RELAXED, [])
        #logging.error('%s has no possible goal.' % ' '.join(life['name']))

        return False

    planner.think(life)