示例#1
0
def tick(life):
    if not lfe.execute_raw(life, 'discover', 'discover_type'):
        _lost_method = lfe.execute_raw(life, 'discover', 'when_lost')
        if _lost_method:
            if not life['path'] or not brain.retrieve_from_memory(
                    life, 'discovery_lock'):
                if not 'scanned_chunks' in life['state_flags']:
                    life['state_flags']['scanned_chunks'] = []

                sight.scan_surroundings(
                    life,
                    _chunks=brain.get_flag(life, 'visible_chunks'),
                    ignore_chunks=life['state_flags']['scanned_chunks'])

                _explore_chunk = chunks.find_best_chunk(
                    life,
                    ignore_starting=True,
                    ignore_time=True,
                    lost_method=_lost_method,
                    only_recent=True)
                brain.store_in_memory(life, 'discovery_lock', True)
                brain.store_in_memory(life, 'explore_chunk', _explore_chunk)

                if not _explore_chunk:
                    brain.flag(life, 'lost')
                    return False

                survival.explore_known_chunks(life)
        else:
            return False
示例#2
0
def conditions(life, alife_seen, alife_not_seen, targets_seen, targets_not_seen, source_map):
	RETURN_VALUE = STATE_UNCHANGED
	
	_mode = None
	if lfe.execute_raw(life, 'state', 'combat'):
		_mode = 'combat'
	
	if not _mode and lfe.execute_raw(life, 'state', 'hunt'):
		_mode = 'hunt'
	
	if not _mode:
		return False
	
	if not lfe.execute_raw(life, 'combat', 'ranged') and not lfe.execute_raw(life, 'combat', 'melee'):
		return False
	
	if not life['state'] == STATE:
		life['state_flags'] = {}
		stats.battle_cry(life)
		
		if gfx.position_is_in_frame(life['pos']) and SETTINGS['controlling']:
			_can_see = sight.can_see_position(life, LIFE[SETTINGS['controlling']]['pos'])
			
			if _can_see:
				_knows = brain.knows_alife_by_id(life, SETTINGS['controlling'])
				
				if _knows and judgement.can_trust(life, SETTINGS['controlling']):
					if lfe.ticker(life, 'enter_combat_message', 3, fire=True):
						logic.show_event('%s readies up.' % ' '.join(life['name']), life=life)
		
		RETURN_VALUE = STATE_CHANGE
	
	brain.flag(life, 'combat_mode', value=_mode)
	
	return RETURN_VALUE
示例#3
0
def track_target(life, target_id):
	_tracking = brain.get_flag(life, 'tracking_targets')
	
	if not _tracking:
		brain.flag(life, 'tracking_targets', [target_id])
		
		return None
	
	_tracking.append(target_id)
示例#4
0
def desires_job(life):
    #TODO: We recalculate this, but the answer is always the same.

    _wont = brain.get_flag(life, 'wont_work')
    if life['job'] or _wont:
        if _wont:
            _wont = brain.flag(life, 'wont_work', value=_wont - 1)

        return False

    if not life['stats']['lone_wolf']:
        return True

    brain.flag(life, 'wont_work', value=1000)
    return False
示例#5
0
文件: stats.py 项目: athros/Reactor-3
def desires_job(life):
	#TODO: We recalculate this, but the answer is always the same.
	
	_wont = brain.get_flag(life, 'wont_work')
	if life['job'] or _wont:
		if _wont:
			_wont = brain.flag(life, 'wont_work', value=_wont-1)
			
		return False
	
	if not life['stats']['lone_wolf']:
		return True
	
	brain.flag(life, 'wont_work', value=1000)
	return False
示例#6
0
def conditions(life, alife_seen, alife_not_seen, targets_seen,
               targets_not_seen, source_map):
    RETURN_VALUE = STATE_UNCHANGED

    _mode = None
    if lfe.execute_raw(life, 'state', 'combat'):
        _mode = 'combat'

    if not _mode and lfe.execute_raw(life, 'state', 'hunt'):
        _mode = 'hunt'

    if not _mode:
        return False

    if not lfe.execute_raw(life, 'combat', 'ranged') and not lfe.execute_raw(
            life, 'combat', 'melee'):
        return False

    if not life['state'] == STATE:
        life['state_flags'] = {}
        stats.battle_cry(life)

        if gfx.position_is_in_frame(life['pos']) and SETTINGS['controlling']:
            _can_see = sight.can_see_position(
                life, LIFE[SETTINGS['controlling']]['pos'])

            if _can_see:
                _knows = brain.knows_alife_by_id(life, SETTINGS['controlling'])

                if _knows and judgement.can_trust(life,
                                                  SETTINGS['controlling']):
                    if lfe.ticker(life, 'enter_combat_message', 3, fire=True):
                        logic.show_event('%s readies up.' %
                                         ' '.join(life['name']),
                                         life=life)

        RETURN_VALUE = STATE_CHANGE

    brain.flag(life, 'combat_mode', value=_mode)

    return RETURN_VALUE
示例#7
0
def tick(life):
	if not lfe.execute_raw(life, 'discover', 'discover_type'):
		_lost_method = lfe.execute_raw(life, 'discover', 'when_lost')
		if _lost_method:
			if not life['path'] or not brain.retrieve_from_memory(life, 'discovery_lock'):
				if not 'scanned_chunks' in life['state_flags']:
					life['state_flags']['scanned_chunks'] = []

				sight.scan_surroundings(life, _chunks=brain.get_flag(life, 'visible_chunks'), ignore_chunks=life['state_flags']['scanned_chunks'])
				
				_explore_chunk = chunks.find_best_chunk(life, ignore_starting=True, ignore_time=True, lost_method=_lost_method, only_recent=True)
				brain.store_in_memory(life, 'discovery_lock', True)
				brain.store_in_memory(life, 'explore_chunk', _explore_chunk)
				
				if not _explore_chunk:
					brain.flag(life, 'lost')
					return False
				
				survival.explore_known_chunks(life)
		else:
			return False
示例#8
0
def search_for_target(life, target_id):
    #TODO: Variable size instead of hardcoded
    _know = brain.knows_alife_by_id(life, target_id)
    _size = 30
    _timer = brain.get_flag(life, 'search_time')
    _chunk_path = alife.brain.get_flag(life, 'chunk_path')

    if _chunk_path:
        travel_to_position(life, _chunk_path['end'], force=True)

        return False

    if _timer > 0:
        brain.flag(life, 'search_time', _timer - 1)

        return False

    if brain.alife_has_flag(life, target_id, 'search_map'):
        _search_map = brain.get_alife_flag(life, target_id, 'search_map')
    else:
        _search_map = maps.create_search_map(life, _know['last_seen_at'],
                                             _size)
        brain.flag_alife(life, target_id, 'search_map', value=_search_map)

        lfe.walk_to(life, _know['last_seen_at'])
        brain.flag(life, 'search_time', 12)

        return False

    _lowest = {'score': -1, 'pos': None}
    _x_top_left = bad_numbers.clip(_know['last_seen_at'][0] - (_size / 2), 0,
                                   MAP_SIZE[0])
    _y_top_left = bad_numbers.clip(_know['last_seen_at'][1] - (_size / 2), 0,
                                   MAP_SIZE[1])

    for x in range(0, _size):
        _x = _x_top_left + x

        if _x >= MAP_SIZE[0] - 1:
            continue

        for y in range(0, _size):
            _y = _y_top_left + y

            if _y >= MAP_SIZE[1] - 1:
                continue

            if not _search_map[y, x]:
                continue

            if sight.can_see_position(life, (_x, _y, _know['last_seen_at'][2]),
                                      get_path=True) or not lfe.can_walk_to(
                                          life,
                                          (_x, _y, _know['last_seen_at'][2])):
                _search_map[y, x] = 0

            if _search_map[y, x] > 0 and (
                    not _lowest['pos']
                    or _search_map[y, x] < _lowest['score']):
                _lowest['score'] = _search_map[y, x]
                _lowest['pos'] = (_x, _y, x, y)

    if _lowest['pos']:
        x, y, _x, _y = _lowest['pos']

        if travel_to_position(life, (x, y, _know['last_seen_at'][2]),
                              stop_on_sight=False):
            _search_map[_y, _x] = 0

        brain.flag(
            life, 'search_time',
            bad_numbers.clip(
                bad_numbers.distance(life['pos'], (x, y)) * .75, 5, 16))
    else:
        _know['escaped'] = 2
示例#9
0
def create_function_map():
	FUNCTION_MAP.update({'is_family': stats.is_family,
		'name': lambda life: ' '.join(life['name']),
		'is_same_species': stats.is_same_species,
		'can_trust': judgement.can_trust,
		'is_dangerous': judgement.is_target_dangerous,
		'can_bite': stats.can_bite,
		'can_scratch': stats.can_scratch,
		'weapon_equipped_and_ready': combat.weapon_equipped_and_ready,
		'prepare_for_ranged': combat.prepare_for_ranged,
		'explore_unknown_chunks': survival.explore_unknown_chunks,
		'is_nervous': stats.is_nervous,
		'is_aggravated': stats.is_aggravated,
		'is_scared': judgement.is_scared,
		'is_safe': judgement.is_safe,
		'is_healthy': None,
		'is_intimidated': stats.is_intimidated,
		'is_intimidating': lambda life, life_id: stats.is_intimidated_by(LIFE[life_id], life['id']),
		'is_confident': stats.is_confident,
		'is_situation_tense': lambda life: judgement.get_tension(life)>=10,
		'is_combat_ready': lambda life, life_id: not LIFE[life_id]['state'] in ['hiding', 'hidden'],
		'is_surrendering': lambda life, life_id: LIFE[life_id]['state'] == 'surrender',
		'is_being_surrendered_to': lambda life: len(judgement.get_combat_targets(life, ignore_escaped=True, filter_func=lambda life, life_id: LIFE[life_id]['state'] == 'surrender'))>0,
		'closest': None,
		'kill': lambda life: lfe.kill(life, 'their own dumb self'),
		'has_attacked_trusted': stats.has_attacked_trusted,
		'has_attacked_self': stats.has_attacked_self,
		'distance_to_pos': stats.distance_from_pos_to_pos,
		'current_chunk_has_flag': lambda life, flag: chunks.get_flag(life, lfe.get_current_chunk_id(life), flag)>0,
		'is_idle': lambda life: life['state'] == 'idle',
		'is_relaxed': lambda life: life['state_tier'] == TIER_RELAXED,
		'is_child_of': stats.is_child_of,
		'is_parent_of': stats.is_parent_of,
		'has_parent': stats.has_parent,
		'has_child': stats.has_child,
		'is_night': logic.is_night,
		'is_born_leader': stats.is_born_leader,
		'is_psychotic': stats.is_psychotic,
		'is_safe_in_shelter': stats.is_safe_in_shelter,
		'is_incapacitated': stats.is_incapacitated,
		'is_target': lambda life, life_id: life_id in judgement.get_targets(life) or life_id in judgement.get_combat_targets(life),
		'seen_target_recently': lambda life, life_id: brain.knows_alife_by_id(life, life_id)['last_seen_time']<=150,
		'is_combat_target': lambda life, life_id: life_id in judgement.get_combat_targets(life),
		'is_traitor': lambda life, life_id: len(lfe.get_memory(life, matches={'text': 'traitor', 'target': life_id}))>0,
		'is_awake': judgement.is_target_awake,
		'is_dead': judgement.is_target_dead,
		'is_target_dead': judgement.is_target_dead,
		'is_raiding': lambda life: (life['group'] and groups.get_stage(life, life['group'])==STAGE_RAIDING)==True,
		'find_and_announce_shelter': groups.find_and_announce_shelter,
		'desires_shelter': stats.desires_shelter,
		'travel_to_position': movement.travel_to_position,
		'find_target': movement.find_target,
		'can_see_target': sight.can_see_target,
		'has_threats': lambda life: len(judgement.get_threats(life, ignore_escaped=1))>0,
		'has_visible_threat': lambda life: len(judgement.get_visible_threats(life))>0,
		'has_combat_targets': lambda life: len(judgement.get_combat_targets(life))>0,
		'has_lost_threat': lambda life: len(judgement.get_threats(life, escaped_only=True, ignore_escaped=2))>0,
		'has_ready_combat_targets': lambda life: len(judgement.get_ready_combat_targets(life, recent_only=True, limit_distance=sight.get_vision(life)+10))>0,
		'danger_close': stats.is_threat_too_close,
		'number_of_alife_in_chunk_matching': lambda life, chunk_key, matching, amount: len(chunks.get_alife_in_chunk_matching(chunk_key, matching))>amount,
		'number_of_alife_in_reference_matching': lambda life, reference_id, matching, amount: len(references.get_alife_in_reference_matching(reference_id, matching))>amount,
		'announce_to_group': groups.announce,
		'is_in_chunk': chunks.is_in_chunk,
		'is_in_shelter': lfe.is_in_shelter,
		'has_shelter': lambda life: len(judgement.get_known_shelters(life))>0,
		'has_completed_job': lambda life, job_id: job_id in life['completed_jobs'],
		'has_completed_task': lambda life, job_id: job_id in life['completed_jobs'],
		'retrieve_from_memory': brain.retrieve_from_memory,
		'pick_up_and_hold_item': lfe.pick_up_and_hold_item,
		'has_usable_weapon': lambda life: not combat.has_ready_weapon(life) == False,
		'has_potentially_usable_weapon': lambda life: combat.has_potentially_usable_weapon(life) == True,
		'target_is_combat_ready': judgement.target_is_combat_ready,
		'create_item_need': survival.add_needed_item,
		'group_needs_resources': lambda life, group_id: groups.needs_resources(group_id),
		'has_needs_to_meet': survival.has_needs_to_meet,
		'has_unmet_needs': survival.has_unmet_needs,
		'has_needs_to_satisfy': survival.has_needs_to_satisfy,
		'has_needs': lambda life: survival.has_needs_to_meet(life) or survival.has_unmet_needs(life) or survival.has_needs_to_satisfy(life),
		'has_number_of_items_matching': lambda life, matching, amount: len(lfe.get_all_inventory_items(life, matches=matching))>=amount,
		'flag_item_matching': lambda life, matching, flag: lfe.get_all_inventory_items(life, matches=[matching]) and brain.flag_item(life, lfe.get_all_inventory_items(life, matches=[matching])[0], flag)>0,
		'drop_item_matching': lambda life, matching: lfe.get_all_inventory_items(life, matches=[matching]) and lfe.drop_item(life, lfe.get_all_inventory_items(life, matches=[matching])[0]['uid'])>0,
		'has_target_to_follow': lambda life: judgement.get_target_to_follow(life)>0,
		'has_target_to_guard': lambda life: judgement.get_target_to_guard(life)>0,
		'get_recent_events': speech.get_recent_events,
		'get_target': lambda life, life_id: speech.get_target(life,
	                                                           lfe.has_dialog_with(life, life_id),
	                                                           dialog.get_flag(lfe.has_dialog_with(life, life_id),
	                                                                           'NEXT_GIST')),
		'get_needs': lambda life, life_id: speech.get_needs(life,
	                                                         lfe.has_dialog_with(life, life_id),
	                                                         dialog.get_flag(lfe.has_dialog_with(life, life_id),
	                                                                         'NEXT_GIST')),
		'get_location': lambda life: '%s, %s' % (life['pos'][0], life['pos'][1]),
		'join_group': lambda life, **kwargs: groups.join_group(life, kwargs['group_id']),
		'add_group_member': lambda life, life_id: groups.add_member(life, life['group'], life_id),
		'claim_to_be_group_leader': lambda life, life_id: groups.set_leader(life, life['group'], life['id']),
		'is_group_leader': lambda life: groups.is_leader_of_any_group(life)==True,
		'is_in_same_group': lambda life, life_id: (life['group'] and LIFE[life_id]['group'] == life['group'])>0,
		'is_target_group_leader': lambda life, life_id: (groups.is_leader_of_any_group(LIFE[life_id]))==True,
		'is_in_group': lambda life: life['group']>0,
		'is_target_hostile': lambda life, life_id: brain.knows_alife_by_id(life, life_id) and brain.knows_alife_by_id(life, life_id)['alignment'] == 'hostile',
		'is_target_in_group': lambda life, life_id, **kwargs: brain.knows_alife_by_id(life, life_id) and brain.knows_alife_by_id(life, life_id)['group']==kwargs['group'],
		'is_target_in_any_group': lambda life, life_id: brain.knows_alife_by_id(life, life_id) and brain.knows_alife_by_id(life, life_id)['group']>0,
		'is_target_group_friendly': lambda life, life_id: brain.knows_alife_by_id(life, life_id) and brain.knows_alife_by_id(life, life_id)['group'] and groups.get_group_memory(life, brain.knows_alife_by_id(life, life_id)['group'], 'alignment')=='trust',
		'is_target_group_hostile': groups.is_target_group_hostile,
		'is_target_group_neutral': lambda life, life_id: brain.knows_alife_by_id(life, life_id) and brain.knows_alife_by_id(life, life_id)['group'] and groups.get_group_memory(life, brain.knows_alife_by_id(life, life_id)['group'], 'alignment')=='neutral',
		'is_group_hostile': lambda life, **kwargs: groups.get_group_memory(life, kwargs['group_id'], 'alignment')=='hostile',
		'is_injured': lambda life: len(lfe.get_cut_limbs(life)) or len(lfe.get_bleeding_limbs(life)),
		'inform_of_group_members': speech.inform_of_group_members,
		'update_group_members': speech.update_group_members,
		'get_group_flag': groups.get_flag,
		'get_flag': brain.get_flag,
		'get_group': lambda life: life['group'],
		'discover_group': lambda life, **kwargs: groups.discover_group(life, kwargs['group_id']),
		'add_target_to_known_group': lambda life, life_id, **kwargs: groups.add_member(life, kwargs['group_id'], life_id),
		'knows_about_group': lambda life, **kwargs: groups.group_exists(life, kwargs['group_id']),
		'group_has_shelter': lambda life: groups.get_shelter(life, life['group'])>0,
		'declare_group_hostile': lambda life, **kwargs: stats.declare_group_hostile(life, kwargs['group_id']),
		'declare_group_trusted': lambda life, **kwargs: stats.declare_group_trusted(life, kwargs['group_id']),
		'declare_group_target': lambda life, life_id: stats.declare_group_target(life, life_id, 'hostile'),
		'get_group_shelter': lambda life: groups.get_shelter(life, life['group']),
		'set_group_shelter': lambda life, **kwargs: groups.set_shelter(life, kwargs['group_id'], kwargs['shelter']),
		'get_group_stage': lambda life: groups.get_stage(life, life['group']),
		'get_group_stage_message': speech.get_group_stage_message,
		'set_group_stage': lambda life, **kwargs: groups.set_stage(life, kwargs['group_id'], kwargs['stage']),
		'is_group_motivated_for_crime': lambda life: life['group'] and groups.get_motive(life, life['group']) == 'crime',
		'wants_to_leave_group_for_group': lambda life: stats.wants_to_abandon_group(life, life['group']),
		'knows_items_matching': lambda life, **kwargs: len(brain.get_multi_matching_remembered_items(life, kwargs['items'], no_owner=True))>0,
		'get_known_group': speech.get_known_group,
		'inform_of_group': speech.inform_of_group,
		'force_inform_of_group': speech.force_inform_of_group,
		'inform_of_items': lambda life, life_id, **kwargs: speech.inform_of_items(life, life_id, kwargs['items']),
		'update_location': lambda life, life_id: brain.update_known_life(life, life_id, 'last_seen_at', LIFE[life_id]['pos'][:]),
		'has_questions_for_target': lambda life, life_id: len(memory.get_questions_for_target(life, life_id))>0,
		'has_orders_for_target': lambda life, life_id: len(memory.get_orders_for_target(life, life_id))>0,
		'ask_target_question': memory.ask_target_question,
		'give_target_order_message': memory.give_target_order_message,
		'give_target_order': memory.give_target_order,
		'take_order': memory.take_order,
		'reject_order': memory.reject_order,
		'get_introduction_message': speech.get_introduction_message,
		'get_introduction_gist': speech.get_introduction_gist,
		'establish_trust': stats.establish_trust,
		'establish_feign_trust': stats.establish_feign_trust,
		'establish_aggressive': stats.establish_aggressive,
		'establish_hostile': stats.establish_hostile,
		'establish_scared': stats.establish_scared,
		'claim_hostile': lambda life, target, **kwargs: stats.establish_hostile(life, kwargs['target_id']),
		'describe_target': lambda life, life_id, **kwargs: speech.describe_target(life, kwargs['target']),
		'consume': lfe.consume,
		'explode': items.explode,
		'is_player': lambda life: 'player' in life,
		'is_neutral': lambda life, life_id: brain.knows_alife_by_id(life, life_id)['alignment'] == 'neutral',
		'reset_think_timer': lfe.reset_think_rate,
		'mark_target_as_combat_ready': lambda life, life_id: brain.flag_alife(life, life_id, 'combat_ready'),
		'mark_target_as_not_combat_ready': lambda life, life_id: brain.flag_alife(life, life_id, 'combat_ready', value=False),
		'saw_target_recently': lambda life, **kwargs: brain.knows_alife_by_id(life, kwargs['target_id']) and -1<brain.knows_alife_by_id(life, kwargs['target_id'])['last_seen_time']<6000,
		'update_location_of_target_from_target': speech.update_location_of_target_from_target,
		'ping': lambda life: logging.debug('%s: Ping!' % ' '.join(life['name'])),
		'wander': lambda life: alife_discover.tick(life),
		'pick_up_item': lambda life: alife_needs.tick(life),
		'take_shelter': lambda life: alife_shelter.tick(life),
		'has_non_relaxed_goal': lambda life: life['state_tier']>TIER_RELAXED,
		'needs_to_manage_inventory': lambda life: alife_manage_items.conditions(life) == True,
		'manage_inventory': lambda life: alife_manage_items.tick(life),
		'cover_exposed': lambda life: len(combat.get_exposed_positions(life))>0,
		'ranged_ready': lambda life: lfe.execute_raw(life, 'combat', 'ranged_ready'),
		'ranged_attack': lambda life: alife_combat.ranged_attack(life),
		'melee_ready': lambda life: lfe.execute_raw(life, 'combat', 'melee_ready'),
		'melee_attack': lambda life: alife_combat.melee_attack(life),
		'take_cover': lambda life: alife_cover.tick(life),
		'hide': lambda life: alife_escape.tick(life),
		'stop': lfe.stop,
		'search_for_threat': lambda life: alife_search.tick(life),
		'has_low_recoil': lambda life: life['recoil']>=.25,
		'has_medium_recoil': lambda life: life['recoil']>=.5,
		'has_high_recoil': lambda life: life['recoil']>=.75,
		'has_focus_point': lambda life: len(lfe.get_memory(life, matches={'text': 'focus_on_chunk'}))>0,
		'walk_to': lambda life: movement.travel_to_chunk(life, lfe.get_memory(life, matches={'text': 'focus_on_chunk'})[len(lfe.get_memory(life, matches={'text': 'focus_on_chunk'}))-1]['chunk_key']),
		'follow_target': alife_follow.tick,
		'guard_focus_point': lambda life: movement.guard_chunk(life, lfe.get_memory(life, matches={'text': 'focus_on_chunk'})[0]['chunk_key']),
		'disarm': lambda life, life_id: brain.flag_alife(life, life_id, 'disarm', value=WORLD_INFO['ticks']),
		'drop_weapon': lambda life: lfe.drop_item(life, lfe.get_held_items(life, matches={'type': 'gun'})[0]),
		'is_disarming': lambda life, life_id: brain.get_alife_flag(life, life_id, 'disarm')>0,
		'set_raid_location': lambda life, **kwargs: lfe.memory(life, 'focus_on_chunk', chunk_key=kwargs['chunk_key']),
		'move_to_chunk': lambda life, **kwargs:  movement.set_focus_point(life, kwargs['chunk_key']),
		'move_to_chunk_key': movement.set_focus_point,
		'recruiting': lambda life, life_id: speech.send(life, life_id, 'recruit'),
		'is_raiding': lambda life: life['group'] and groups.get_stage(life, life['group']) == STAGE_ATTACKING,
		'is_in_target_chunk': lambda life, target_id: lfe.get_current_chunk_id(life) == lfe.get_current_chunk_id(LIFE[target_id]),
		'get_chunk_key': lfe.get_current_chunk_id,
		'has_threat_in_combat_range': stats.has_threat_in_combat_range,
		'find_nearest_chunk_in_reference': references.find_nearest_chunk_key_in_reference_of_type,
		'has_item_type': lambda life, item_match: not lfe.get_inventory_item_matching(life, item_match) == None,
		'move_to_target': lambda life, target_id: movement.travel_to_position(life, LIFE[target_id]['pos']),
		'is_in_range_of_target': lambda life, target_id, distance: numbers.distance(life['pos'], LIFE[target_id]['pos'])<=int(distance),
		'track_target': lambda life, target_id: brain.meet_alife(life, LIFE[target_id]) and judgement.track_target(life, target_id),
		'untrack_target': judgement.untrack_target,
		'clear_tracking': lambda life: brain.flag(life, 'tracking_targets', []),
		'can_see_item': lambda life, item_uid: item_uid in life['seen_items'],
		'has_item': lambda life, item_uid: item_uid in life['inventory'],
		'pick_up_item': movement.pick_up_item,
		'create_mission': missions.create_mission_for_self,
		'give_mission': missions.create_mission_and_give,
		'do_mission': alife_work.tick,
		'has_mission': lambda life: len(life['missions'])>0,
		'drop_item': lfe.drop_item,
		'get_id': lambda life: life['id'],
		'always': lambda life: 1==1,
		'pass': lambda life, *a, **k: True,
		'never': lambda life: 1==2})
示例#10
0
def generate_needs(life):
    if not lfe.ticker(life, 'generate_needs', 90, fire=True):
        return False

    if stats.desires_weapon(life):
        brain.flag(life, 'no_weapon')
    else:
        brain.unflag(life, 'no_weapon')

    if combat.get_weapons(life):
        for weapon in combat.get_weapons(life):
            _weapon_uid = weapon['uid']

            #for _flag in ['ammo', 'feed']:
            if len(combat.get_all_ammo_for_weapon(life, _weapon_uid)) >= 5:
                _flag_name = '%s_needs_ammo' % _weapon_uid

                _need = brain.get_flag(life, _flag_name)

                if _need:
                    delete_needed_item(life, _need)
                    brain.unflag(life, _flag_name)

            if combat.get_feeds_for_weapon(life, _weapon_uid):
                _flag_name = '%s_needs_feed' % _weapon_uid

                _need = brain.get_flag(life, _flag_name)

                if _need:
                    delete_needed_item(life, _need)
                    brain.unflag(life, _flag_name)

        if not combat.has_potentially_usable_weapon(
                life) and not combat.has_ready_weapon(life):
            #_weapon_with_feed = None
            #for weapon in combat.get_weapons(life):
            #	if weapons.get_feed(weapon):
            #		_weapon_with_feed = weapon['uid']
            #		break

            #if _weapon_with_feed:
            #	_weapon_uid = weapon['uid']
            #	_flag_name = '%s_needs_ammo' % _weapon_uid
            #	_n = add_needed_item(life,
            #	                     {'type': 'bullet', 'owner': None, 'ammotype': weapon['ammotype']},
            #	                     satisfy_if=action.make_small_script(function='get_flag',
            #	                                                         args={'flag': _flag_name}),
            #	                     satisfy_callback=action.make_small_script(return_function='pick_up_and_hold_item'))
            #
            #	brain.flag(life, _flag_name, value=_n)

            for weapon in combat.get_weapons(life):
                _weapon_uid = weapon['uid']
                _flag_name = '%s_needs_feed' % _weapon_uid
                if combat.have_feed_and_ammo_for_weapon(life, _weapon_uid):
                    continue

                #print 'feeds?', combat.get_feeds_for_weapon(life, _weapon_uid), [ITEMS[i]['name'] for i in lfe.get_held_items(life)]

                if not combat.get_feeds_for_weapon(
                        life, _weapon_uid) and not brain.get_flag(
                            life, _flag_name):
                    _n = add_needed_item(
                        life, {
                            'type': weapon['feed'],
                            'owner': None,
                            'ammotype': weapon['ammotype']
                        },
                        satisfy_if=action.make_small_script(
                            function='get_flag', args={'flag': _flag_name}),
                        satisfy_callback=action.make_small_script(
                            return_function='pick_up_and_hold_item'))

                    brain.flag(life, _flag_name, value=_n)

                _flag_name = '%s_needs_ammo' % _weapon_uid

                if len(combat.get_all_ammo_for_weapon(
                        life, _weapon_uid)) < 5 and not brain.get_flag(
                            life, _flag_name):
                    _n = add_needed_item(
                        life, {
                            'type': 'bullet',
                            'owner': None,
                            'ammotype': weapon['ammotype']
                        },
                        satisfy_if=action.make_small_script(
                            function='get_flag', args={'flag': _flag_name}),
                        satisfy_callback=action.make_small_script(
                            return_function='pick_up_and_hold_item'))

                    brain.flag(life, _flag_name, value=_n)
示例#11
0
def generate_needs(life):
    if not lfe.ticker(life, "generate_needs", 90, fire=True):
        return False

    if stats.desires_weapon(life):
        brain.flag(life, "no_weapon")
    else:
        brain.unflag(life, "no_weapon")

    if combat.get_weapons(life):
        for weapon in combat.get_weapons(life):
            _weapon_uid = weapon["uid"]

            # for _flag in ['ammo', 'feed']:
            if len(combat.get_all_ammo_for_weapon(life, _weapon_uid)) >= 5:
                _flag_name = "%s_needs_ammo" % _weapon_uid

                _need = brain.get_flag(life, _flag_name)

                if _need:
                    delete_needed_item(life, _need)
                    brain.unflag(life, _flag_name)

            if combat.get_feeds_for_weapon(life, _weapon_uid):
                _flag_name = "%s_needs_feed" % _weapon_uid

                _need = brain.get_flag(life, _flag_name)

                if _need:
                    delete_needed_item(life, _need)
                    brain.unflag(life, _flag_name)

        if not combat.has_potentially_usable_weapon(life) and not combat.has_ready_weapon(life):
            # _weapon_with_feed = None
            # for weapon in combat.get_weapons(life):
            # 	if weapons.get_feed(weapon):
            # 		_weapon_with_feed = weapon['uid']
            # 		break

            # if _weapon_with_feed:
            # 	_weapon_uid = weapon['uid']
            # 	_flag_name = '%s_needs_ammo' % _weapon_uid
            # 	_n = add_needed_item(life,
            # 	                     {'type': 'bullet', 'owner': None, 'ammotype': weapon['ammotype']},
            # 	                     satisfy_if=action.make_small_script(function='get_flag',
            # 	                                                         args={'flag': _flag_name}),
            # 	                     satisfy_callback=action.make_small_script(return_function='pick_up_and_hold_item'))
            #
            # 	brain.flag(life, _flag_name, value=_n)

            for weapon in combat.get_weapons(life):
                _weapon_uid = weapon["uid"]
                _flag_name = "%s_needs_feed" % _weapon_uid
                if combat.have_feed_and_ammo_for_weapon(life, _weapon_uid):
                    continue

                    # print 'feeds?', combat.get_feeds_for_weapon(life, _weapon_uid), [ITEMS[i]['name'] for i in lfe.get_held_items(life)]

                if not combat.get_feeds_for_weapon(life, _weapon_uid) and not brain.get_flag(life, _flag_name):
                    _n = add_needed_item(
                        life,
                        {"type": weapon["feed"], "owner": None, "ammotype": weapon["ammotype"]},
                        satisfy_if=action.make_small_script(function="get_flag", args={"flag": _flag_name}),
                        satisfy_callback=action.make_small_script(return_function="pick_up_and_hold_item"),
                    )

                    brain.flag(life, _flag_name, value=_n)

                _flag_name = "%s_needs_ammo" % _weapon_uid

                if len(combat.get_all_ammo_for_weapon(life, _weapon_uid)) < 5 and not brain.get_flag(life, _flag_name):
                    _n = add_needed_item(
                        life,
                        {"type": "bullet", "owner": None, "ammotype": weapon["ammotype"]},
                        satisfy_if=action.make_small_script(function="get_flag", args={"flag": _flag_name}),
                        satisfy_callback=action.make_small_script(return_function="pick_up_and_hold_item"),
                    )

                    brain.flag(life, _flag_name, value=_n)
示例#12
0
def search_for_target(life, target_id):
	#TODO: Variable size instead of hardcoded
	_know = brain.knows_alife_by_id(life, target_id)
	_size = 30
	_timer = brain.get_flag(life, 'search_time')
	_chunk_path = alife.brain.get_flag(life, 'chunk_path')
	
	if _chunk_path:
		travel_to_position(life, _chunk_path['end'], force=True)
		
		return False
	
	if _timer>0:
		brain.flag(life, 'search_time', _timer-1)
		
		return False
	
	if brain.alife_has_flag(life, target_id, 'search_map'):
		_search_map = brain.get_alife_flag(life, target_id, 'search_map')
	else:
		_search_map = maps.create_search_map(life, _know['last_seen_at'], _size)
		brain.flag_alife(life, target_id, 'search_map', value=_search_map)
		
		lfe.walk_to(life, _know['last_seen_at'])
		brain.flag(life, 'search_time', 12)
		
		return False
	
	_lowest = {'score': -1, 'pos': None}
	_x_top_left = bad_numbers.clip(_know['last_seen_at'][0]-(_size/2), 0, MAP_SIZE[0])
	_y_top_left = bad_numbers.clip(_know['last_seen_at'][1]-(_size/2), 0, MAP_SIZE[1])
	
	for x in range(0, _size):
		_x = _x_top_left+x
		
		if _x >= MAP_SIZE[0]-1:
			continue
		
		for y in range(0, _size):
			_y = _y_top_left+y
			
			if _y >= MAP_SIZE[1]-1:
				continue
			
			if not _search_map[y, x]:
				continue
			
			if sight.can_see_position(life, (_x, _y, _know['last_seen_at'][2]), get_path=True) or not lfe.can_walk_to(life, (_x, _y, _know['last_seen_at'][2])):
				_search_map[y, x] = 0
			
			if _search_map[y, x]>0 and (not _lowest['pos'] or _search_map[y, x] < _lowest['score']):
				_lowest['score'] = _search_map[y, x]
				_lowest['pos'] = (_x, _y, x, y)

	if _lowest['pos']:
		x, y, _x, _y = _lowest['pos']
		
		if travel_to_position(life, (x, y, _know['last_seen_at'][2]), stop_on_sight=False):
			_search_map[_y, _x] = 0
		
		brain.flag(life, 'search_time', bad_numbers.clip(bad_numbers.distance(life['pos'], (x, y))*.75, 5, 16))
	else:
		_know['escaped'] = 2
示例#13
0
def search_for_target(life, target_id):
    # TODO: Variable size instead of hardcoded
    _know = brain.knows_alife_by_id(life, target_id)
    _size = 30
    _timer = brain.get_flag(life, "search_time")
    _chunk_path = alife.brain.get_flag(life, "chunk_path")

    if _chunk_path:
        travel_to_position(life, _chunk_path["end"], force=True)

        return False

    if _timer > 0:
        brain.flag(life, "search_time", _timer - 1)

        return False

    if brain.alife_has_flag(life, target_id, "search_map"):
        _search_map = brain.get_alife_flag(life, target_id, "search_map")
    else:
        _search_map = maps.create_search_map(life, _know["last_seen_at"], _size)
        brain.flag_alife(life, target_id, "search_map", value=_search_map)

        lfe.walk_to(life, _know["last_seen_at"])
        brain.flag(life, "search_time", 12)

        return False

    _lowest = {"score": -1, "pos": None}
    _x_top_left = numbers.clip(_know["last_seen_at"][0] - (_size / 2), 0, MAP_SIZE[0])
    _y_top_left = numbers.clip(_know["last_seen_at"][1] - (_size / 2), 0, MAP_SIZE[1])

    for x in range(0, _size):
        _x = _x_top_left + x

        if _x >= MAP_SIZE[0] - 1:
            continue

        for y in range(0, _size):
            _y = _y_top_left + y

            if _y >= MAP_SIZE[1] - 1:
                continue

            if not _search_map[y, x]:
                continue

            if sight.can_see_position(life, (_x, _y, _know["last_seen_at"][2]), get_path=True) or not lfe.can_walk_to(
                life, (_x, _y, _know["last_seen_at"][2])
            ):
                _search_map[y, x] = 0

            if _search_map[y, x] > 0 and (not _lowest["pos"] or _search_map[y, x] < _lowest["score"]):
                _lowest["score"] = _search_map[y, x]
                _lowest["pos"] = (_x, _y, x, y)

    if _lowest["pos"]:
        x, y, _x, _y = _lowest["pos"]

        if travel_to_position(life, (x, y, _know["last_seen_at"][2]), stop_on_sight=False):
            _search_map[_y, _x] = 0

        brain.flag(life, "search_time", numbers.clip(numbers.distance(life["pos"], (x, y)) * 0.75, 5, 16))
    else:
        _know["escaped"] = 2
示例#14
0
def manage_combat(life, group_id):
    if has_flag(life, group_id, 'confident'):
        _was_confident = get_flag(life, group_id, 'confident')

        if _was_confident == stats.is_confident(life) and not lfe.ticker(
                life, 'decision_wait', 16):
            return False

    flag(life, group_id, 'confident', stats.is_confident(life))

    _existing_friendlies = get_flag(life, group_id, 'friendlies')
    _existing_targets = get_flag(life, group_id, 'targets')
    _last_focal_point = get_flag(life, group_id, 'last_focal_point')

    if not _existing_friendlies:
        _existing_friendlies = {}

    if not _existing_targets:
        _existing_targets = {}

    for life_id in get_group(life, group_id)['members']:
        if not life_id in _existing_friendlies:
            _existing_friendlies[life_id] = {'updated': -900}

    flag(life, group_id, 'friendlies', _existing_friendlies)

    _checked_targets = []
    for target_id in judgement.get_threats(life):
        if target_id in _existing_targets:
            _existing_targets[target_id]['time'] = 0
        else:
            _existing_targets[target_id] = {
                'time': 0,
                'pos': brain.knows_alife_by_id(life,
                                               target_id)['last_seen_at'][:]
            }

        _checked_targets.append(target_id)

    _enemy_focal_pos = None

    for target_id in _existing_targets:
        if not _enemy_focal_pos:
            _enemy_focal_pos = _existing_targets[target_id]['pos'][:]
        else:
            _enemy_focal_pos = bad_numbers.lerp_velocity(
                _enemy_focal_pos, _existing_targets[target_id]['pos'], 0.5)

        if target_id in _checked_targets:
            continue

        _existing_targets[target_id]['time'] += 1

        if _existing_targets[target_id]['time'] > 100:
            del _existing_targets[target_id]

            continue

    _hostile_chunks = get_flag(life, group_id, 'hostile_chunks')
    _previous_visible_chunks = brain.get_flag(life, 'group_combat_vis_chunks')

    if _previous_visible_chunks and _previous_visible_chunks[
            'from_pos'] == life['pos']:
        _visible_chunks = _previous_visible_chunks['visible_chunks']
    else:
        _visible_chunks = chunks.get_visible_chunks_from(
            life['pos'], life['vision_max'] * .75)

        brain.flag(life,
                   'group_combat_vis_chunks',
                   value={
                       'from_pos': life['pos'][:],
                       'visible_chunks': _visible_chunks
                   })

    if _enemy_focal_pos:
        lfe.clear_ticker(life, 'group_command_reset')

        if not _last_focal_point or bad_numbers.distance(
                _enemy_focal_pos, _last_focal_point) > 30:
            _hostile_chunks = chunks.get_visible_chunks_from(
                (int(round(_enemy_focal_pos[0])),
                 int(round(_enemy_focal_pos[1])), 2), life['vision_max'] * 1.5)

            flag(life, group_id, 'hostile_chunks', _hostile_chunks)
            flag(life, group_id, 'visible_chunks', _visible_chunks)
            flag(life, group_id, 'last_focal_point', _enemy_focal_pos)

    else:
        _ticker = lfe.ticker(life, 'group_command_reset', 48)

        if get_stage(life, group_id) == STAGE_ATTACKING:
            if _ticker:
                set_stage(life, group_id, STAGE_FORMING)
                flag(life, group_id, 'friendlies', None)
                flag(life, group_id, 'strategy', None)
            else:
                manage_strategy(life, group_id)

        return False

    if not get_stage(life, group_id) == STAGE_ATTACKING:
        speech.announce_combat_to_group(life, group_id)
        set_stage(life, group_id, STAGE_ATTACKING)

    if not lfe.ticker(life, 'group_command_rate', 3):
        return False

    _orig_visible_chunks = _visible_chunks[:]

    #TODO: Check distance to threat
    for hostile_chunk_key in _hostile_chunks:
        if hostile_chunk_key in _visible_chunks:
            _visible_chunks.remove(hostile_chunk_key)

    #TODO: Additional stages: PLANNING, EXECUTING
    if _visible_chunks and stats.is_confident(life):
        for target_id in order_spread_out(
                life,
                group_id,
                _visible_chunks,
                filter_by=lambda life_id: WORLD_INFO[
                    'ticks'] - _existing_friendlies[life_id]['updated'] > 100):
            _existing_friendlies[target_id]['updated'] = WORLD_INFO['ticks']
    else:
        _distant_chunk = {'distance': -1, 'chunk_key': None}
        _unchecked_members = get_group(life, group_id)['members'][:]

        for chunk_key in _orig_visible_chunks:
            _distance = bad_numbers.distance(
                (int(round(
                    _enemy_focal_pos[0])), int(round(_enemy_focal_pos[1]))),
                chunks.get_chunk(chunk_key)['pos'])
            _distance *= bad_numbers.clip(
                bad_numbers.distance(life['pos'], _enemy_focal_pos), 1,
                35) / 35.0

            if chunk_key in _visible_chunks:
                _distance *= 2

            for member_id in _unchecked_members:
                if life['id'] == member_id:
                    continue

                _target = brain.knows_alife_by_id(life, member_id)

                if _target['last_seen_time'] <= 25 and chunks.get_chunk_key_at(
                        _target['last_seen_at']) == chunk_key:
                    _distance *= (2.5 * (1 - (bad_numbers.clip(
                        _target['last_seen_time'], 0, 25) / 25.0)))

            if _distance > _distant_chunk['distance']:
                _distant_chunk['distance'] = _distance
                _distant_chunk['chunk_key'] = chunk_key

        if _distant_chunk['chunk_key']:
            for target_id in order_move_to(
                    life,
                    group_id,
                    _distant_chunk['chunk_key'],
                    filter_by=lambda life_id: WORLD_INFO['ticks'] -
                    _existing_friendlies[life_id]['updated'] > 100):
                _existing_friendlies[target_id]['updated'] = WORLD_INFO[
                    'ticks']

        return False
示例#15
0
文件: groups.py 项目: flags/Reactor-3
def manage_combat(life, group_id):
	if has_flag(life, group_id, 'confident'):
		_was_confident = get_flag(life, group_id, 'confident')
		
		if _was_confident == stats.is_confident(life) and not lfe.ticker(life, 'decision_wait', 16):
			return False
	
	flag(life, group_id, 'confident', stats.is_confident(life))
	
	_existing_friendlies = get_flag(life, group_id, 'friendlies')
	_existing_targets = get_flag(life, group_id, 'targets')
	_last_focal_point = get_flag(life, group_id, 'last_focal_point')
	
	if not _existing_friendlies:
		_existing_friendlies = {}
	
	if not _existing_targets:
		_existing_targets = {}
	
	for life_id in get_group(life, group_id)['members']:
		if not life_id in _existing_friendlies:
			_existing_friendlies[life_id] = {'updated': -900}
	
	flag(life, group_id, 'friendlies', _existing_friendlies)
	
	_checked_targets = []
	for target_id in judgement.get_threats(life):
		if target_id in _existing_targets:
			_existing_targets[target_id]['time'] = 0
		else:
			_existing_targets[target_id] = {'time': 0, 'pos': brain.knows_alife_by_id(life, target_id)['last_seen_at'][:]}
		
		_checked_targets.append(target_id)

	_enemy_focal_pos = None

	for target_id in _existing_targets:
		if not _enemy_focal_pos:
			_enemy_focal_pos = _existing_targets[target_id]['pos'][:]
		else:
			_enemy_focal_pos = bad_numbers.lerp_velocity(_enemy_focal_pos, _existing_targets[target_id]['pos'], 0.5)
		
		if target_id in _checked_targets:
			continue
		
		_existing_targets[target_id]['time'] += 1
		
		if _existing_targets[target_id]['time']>100:
			del _existing_targets[target_id]
			
			continue
	
	_hostile_chunks = get_flag(life, group_id, 'hostile_chunks')
	_previous_visible_chunks = brain.get_flag(life, 'group_combat_vis_chunks')
	
	if _previous_visible_chunks and _previous_visible_chunks['from_pos'] == life['pos']:
		_visible_chunks = _previous_visible_chunks['visible_chunks']
	else:
		_visible_chunks = chunks.get_visible_chunks_from(life['pos'], life['vision_max']*.75)
		
		brain.flag(life, 'group_combat_vis_chunks', value={'from_pos': life['pos'][:],
		                                                   'visible_chunks': _visible_chunks})
	
	if _enemy_focal_pos:
		lfe.clear_ticker(life, 'group_command_reset')
		
		if not _last_focal_point or bad_numbers.distance(_enemy_focal_pos, _last_focal_point)>30:
			_hostile_chunks = chunks.get_visible_chunks_from((int(round(_enemy_focal_pos[0])), int(round(_enemy_focal_pos[1])), 2), life['vision_max']*1.5)
			
			flag(life, group_id, 'hostile_chunks', _hostile_chunks)
			flag(life, group_id, 'visible_chunks', _visible_chunks)
			flag(life, group_id, 'last_focal_point', _enemy_focal_pos)
			
	else:
		_ticker = lfe.ticker(life, 'group_command_reset', 48)
		
		if get_stage(life, group_id) == STAGE_ATTACKING:
			if _ticker:
				set_stage(life, group_id, STAGE_FORMING)
				flag(life, group_id, 'friendlies', None)
				flag(life, group_id, 'strategy', None)
			else:
				manage_strategy(life, group_id)
		
		return False
	
	if not get_stage(life, group_id) == STAGE_ATTACKING:
		speech.announce_combat_to_group(life, group_id)
		set_stage(life, group_id, STAGE_ATTACKING)
	
	if not lfe.ticker(life, 'group_command_rate', 3):
		return False
	
	_orig_visible_chunks = _visible_chunks[:]
	
	#TODO: Check distance to threat
	for hostile_chunk_key in _hostile_chunks:
		if hostile_chunk_key in _visible_chunks:
			_visible_chunks.remove(hostile_chunk_key)
		
	#TODO: Additional stages: PLANNING, EXECUTING
	if _visible_chunks and stats.is_confident(life):
		for target_id in order_spread_out(life, group_id, _visible_chunks, filter_by=lambda life_id: WORLD_INFO['ticks']-_existing_friendlies[life_id]['updated']>100):
			_existing_friendlies[target_id]['updated'] = WORLD_INFO['ticks']
	else:
		_distant_chunk = {'distance': -1, 'chunk_key': None}
		_unchecked_members = get_group(life, group_id)['members'][:]
		
		for chunk_key in _orig_visible_chunks:
			_distance = bad_numbers.distance((int(round(_enemy_focal_pos[0])), int(round(_enemy_focal_pos[1]))), chunks.get_chunk(chunk_key)['pos'])
			_distance *= bad_numbers.clip(bad_numbers.distance(life['pos'], _enemy_focal_pos), 1, 35)/35.0
			
			if chunk_key in _visible_chunks:
				_distance *= 2
			
			for member_id in _unchecked_members:
				if life['id'] == member_id:
					continue
				
				_target = brain.knows_alife_by_id(life, member_id)
				
				if _target['last_seen_time'] <= 25 and chunks.get_chunk_key_at(_target['last_seen_at']) == chunk_key:
					_distance *= (2.5*(1-(bad_numbers.clip(_target['last_seen_time'], 0, 25)/25.0)))
			
			if _distance>_distant_chunk['distance']:
				_distant_chunk['distance'] = _distance
				_distant_chunk['chunk_key'] = chunk_key
		
		if _distant_chunk['chunk_key']:
			for target_id in order_move_to(life, group_id, _distant_chunk['chunk_key'], filter_by=lambda life_id: WORLD_INFO['ticks']-_existing_friendlies[life_id]['updated']>100):
				_existing_friendlies[target_id]['updated'] = WORLD_INFO['ticks']
		
		return False
示例#16
0
def look(life):
    if not 'CAN_SEE' in life['life_flags']:
        return False

    for target_id in life['know']:
        if life['know'][target_id]['last_seen_time']:
            life['know'][target_id]['last_seen_time'] += 1
            life['know'][target_id]['time_visible'] = 0
        else:
            life['know'][target_id]['time_visible'] += 1

    if 'player' in life:
        if life['path'] or not brain.get_flag(life, 'visible_chunks'):
            if SETTINGS['smp']:
                _visible_chunks = post_scan_surroundings(life)
            else:
                _visible_chunks = scan_surroundings(life,
                                                    judge=False,
                                                    get_chunks=True,
                                                    ignore_chunks=0)

            _chunks = [maps.get_chunk(c) for c in _visible_chunks]
            brain.flag(life, 'visible_chunks', value=_visible_chunks)
        elif 'player' in life:
            _visible_chunks = brain.get_flag(life, 'visible_chunks')
            _chunks = [maps.get_chunk(c) for c in _visible_chunks]
        else:
            #This is for optimizing. Be careful if you mess with this...
            _nearby_alife = {}

            for alife in LIFE.values():
                if alife['id'] == life['id']:
                    continue

                if bad_numbers.distance(
                        life['pos'],
                        alife['pos']) <= get_vision(life) and can_see_position(
                            life, alife['pos']):
                    _nearby_alife[alife['id']] = {
                        'pos': alife['pos'][:],
                        'stance': alife['stance']
                    }

            _last_nearby_alife = brain.get_flag(life, '_nearby_alife')

            if not _last_nearby_alife == _nearby_alife:
                brain.flag(life, '_nearby_alife', value=_nearby_alife)
            else:
                for target_id in life['seen']:
                    if life['know'][target_id]['last_seen_time']:
                        life['know'][target_id]['last_seen_time'] = 0

                return False

            _chunks = [
                maps.get_chunk(c)
                for c in brain.get_flag(life, 'visible_chunks')
            ]

    life['seen'] = []
    life['seen_items'] = []

    for item_uid in life['know_items']:
        life['know_items'][item_uid]['last_seen_time'] += 1

    for target_id in life['know']:
        life['know'][target_id]['last_seen_time'] += 1

        if life['know'][target_id]['last_seen_time'] >= 10 and not life[
                'know'][target_id]['escaped']:
            life['know'][target_id]['escaped'] = 1

    if not 'player' in life:
        quick_look(life)

        return False

    for chunk in _chunks:
        judgement.judge_chunk_visually(
            life, '%s,%s' % (chunk['pos'][0], chunk['pos'][1]))
        judgement.judge_chunk_life(
            life, '%s,%s' % (chunk['pos'][0], chunk['pos'][1]))

        for ai in [LIFE[i] for i in chunk['life']]:
            if ai['id'] == life['id']:
                continue

            if not is_in_fov(life, ai['pos']):
                if ai['id'] in life['know']:
                    life['know'][ai['id']]['time_visible'] = 0

                continue

            if not ai['id'] in life['know']:
                brain.meet_alife(life, ai)

            _visibility = get_visiblity_of_position(life, ai['pos'])
            _stealth_coverage = get_stealth_coverage(ai)

            if _visibility < 1 - _stealth_coverage:
                continue

            life['seen'].append(ai['id'])

            if life['think_rate'] == life['think_rate_max']:
                lfe.create_and_update_self_snapshot(LIFE[ai['id']])
                judgement.judge_life(life, ai['id'])

            if ai['dead']:
                if 'player' in life and not life['know'][
                        ai['id']]['dead'] and life['know'][
                            ai['id']]['last_seen_time'] > 25:
                    logic.show_event('You discover the body of %s.' %
                                     ' '.join(ai['name']),
                                     life=ai)

                if life['know'][ai['id']]['group']:
                    groups.remove_member(life, life['know'][ai['id']]['group'],
                                         ai['id'])
                    life['know'][ai['id']]['group'] = None
                    core.record_loss(1)

                life['know'][ai['id']]['dead'] = True
            elif ai['asleep']:
                life['know'][ai['id']]['asleep'] = True
            elif not ai['asleep']:
                life['know'][ai['id']]['asleep'] = False

            life['know'][ai['id']]['last_seen_time'] = 0
            life['know'][ai['id']]['last_seen_at'] = ai['pos'][:]
            life['know'][ai['id']]['escaped'] = False
            life['know'][ai['id']]['state'] = ai['state']
            life['know'][ai['id']]['state_tier'] = ai['state_tier']

            if brain.alife_has_flag(life, ai['id'], 'search_map'):
                brain.unflag_alife(life, ai['id'], 'search_map')

            _chunk_id = lfe.get_current_chunk_id(ai)
            judgement.judge_chunk(life, _chunk_id, seen=True)

        for item in [ITEMS[i] for i in chunk['items'] if i in ITEMS]:
            if not is_in_fov(life, item['pos']):
                continue

            if not item['uid'] in life['know_items']:
                brain.remember_item(life, item)

            if items.is_item_owned(item['uid']):
                #TODO: This doesn't work because we are specifically checking chunks
                if item['owner'] and lfe.item_is_equipped(
                        LIFE[item['owner']], item['uid']):
                    life['know_items'][item['uid']]['last_seen_at'] = LIFE[
                        item['owner']]['pos']
                    life['know_items'][
                        item['uid']]['last_owned_by'] = item['owner']
                    life['know_items'][item['uid']]['last_seen_time'] = 0

                continue

            life['seen_items'].append(item['uid'])
            life['know_items'][item['uid']]['last_seen_at'] = item['pos'][:]
            life['know_items'][item['uid']]['last_seen_time'] = 0
            life['know_items'][item['uid']]['last_owned_by'] = None
            life['know_items'][item['uid']]['score'] = judgement.judge_item(
                life, item['uid'])
            life['know_items'][item['uid']]['lost'] = False
示例#17
0
文件: sight.py 项目: flags/Reactor-3
def look(life):
	if not 'CAN_SEE' in life['life_flags']:
		return False
	
	for target_id in life['know']:
		if life['know'][target_id]['last_seen_time']:
			life['know'][target_id]['last_seen_time'] += 1
			life['know'][target_id]['time_visible'] = 0
		else:
			life['know'][target_id]['time_visible'] += 1
	
	if 'player' in life:
		if life['path'] or not brain.get_flag(life, 'visible_chunks'):
			if SETTINGS['smp']:
				_visible_chunks = post_scan_surroundings(life)
			else:
				_visible_chunks = scan_surroundings(life, judge=False, get_chunks=True, ignore_chunks=0)
				
			_chunks = [maps.get_chunk(c) for c in _visible_chunks]
			brain.flag(life, 'visible_chunks', value=_visible_chunks)
		elif 'player' in life:
			_visible_chunks = brain.get_flag(life, 'visible_chunks')
			_chunks = [maps.get_chunk(c) for c in _visible_chunks]
		else:
			#This is for optimizing. Be careful if you mess with this...
			_nearby_alife = {}
			
			for alife in LIFE.values():
				if alife['id'] == life['id']:
					continue
				
				if bad_numbers.distance(life['pos'], alife['pos'])<=get_vision(life) and can_see_position(life, alife['pos']):
					_nearby_alife[alife['id']] = {'pos': alife['pos'][:], 'stance': alife['stance']}
			
			_last_nearby_alife = brain.get_flag(life, '_nearby_alife')
			
			if not _last_nearby_alife == _nearby_alife:
				brain.flag(life, '_nearby_alife', value=_nearby_alife)
			else:
				for target_id in life['seen']:
					if life['know'][target_id]['last_seen_time']:
						life['know'][target_id]['last_seen_time'] = 0
				
				return False
			
			_chunks = [maps.get_chunk(c) for c in brain.get_flag(life, 'visible_chunks')]
	
	life['seen'] = []
	life['seen_items'] = []
	
	for item_uid in life['know_items']:
		life['know_items'][item_uid]['last_seen_time'] += 1
	
	for target_id in life['know']:
		life['know'][target_id]['last_seen_time'] += 1
		
		if life['know'][target_id]['last_seen_time']>=10 and not life['know'][target_id]['escaped']:
			life['know'][target_id]['escaped'] = 1
	
	if not 'player' in life:
		quick_look(life)
		
		return False
	
	for chunk in _chunks:
		judgement.judge_chunk_visually(life, '%s,%s' % (chunk['pos'][0], chunk['pos'][1]))
		judgement.judge_chunk_life(life, '%s,%s' % (chunk['pos'][0], chunk['pos'][1]))
		
		for ai in [LIFE[i] for i in chunk['life']]:
			if ai['id'] == life['id']:
				continue
			
			if not is_in_fov(life, ai['pos']):
				if ai['id'] in life['know']:
					life['know'][ai['id']]['time_visible'] = 0
				
				continue
			
			if not ai['id'] in life['know']:
				brain.meet_alife(life, ai)
			
			_visibility = get_visiblity_of_position(life, ai['pos'])
			_stealth_coverage = get_stealth_coverage(ai)
			
			if _visibility < 1-_stealth_coverage:
				continue
			
			life['seen'].append(ai['id'])
			
			if life['think_rate'] == life['think_rate_max']:
				lfe.create_and_update_self_snapshot(LIFE[ai['id']])
				judgement.judge_life(life, ai['id'])
			
			if ai['dead']:
				if 'player' in life and not life['know'][ai['id']]['dead'] and life['know'][ai['id']]['last_seen_time']>25:
					logic.show_event('You discover the body of %s.' % ' '.join(ai['name']), life=ai)
				
				if life['know'][ai['id']]['group']:
					groups.remove_member(life, life['know'][ai['id']]['group'], ai['id'])
					life['know'][ai['id']]['group'] = None
					core.record_loss(1)
				
				life['know'][ai['id']]['dead'] = True
			elif ai['asleep']:
				life['know'][ai['id']]['asleep'] = True
			elif not ai['asleep']:
				life['know'][ai['id']]['asleep'] = False
			
			life['know'][ai['id']]['last_seen_time'] = 0
			life['know'][ai['id']]['last_seen_at'] = ai['pos'][:]
			life['know'][ai['id']]['escaped'] = False
			life['know'][ai['id']]['state'] = ai['state']
			life['know'][ai['id']]['state_tier'] = ai['state_tier']
			
			if brain.alife_has_flag(life, ai['id'], 'search_map'):
				brain.unflag_alife(life, ai['id'], 'search_map')
			
			_chunk_id = lfe.get_current_chunk_id(ai)
			judgement.judge_chunk(life, _chunk_id, seen=True)
	
		for item in [ITEMS[i] for i in chunk['items'] if i in ITEMS]:
			if not is_in_fov(life, item['pos']):
				continue
			
			if not item['uid'] in life['know_items']:
				brain.remember_item(life, item)

			if items.is_item_owned(item['uid']):
				#TODO: This doesn't work because we are specifically checking chunks
				if item['owner'] and lfe.item_is_equipped(LIFE[item['owner']], item['uid']):
					life['know_items'][item['uid']]['last_seen_at'] = LIFE[item['owner']]['pos']
					life['know_items'][item['uid']]['last_owned_by'] = item['owner']
					life['know_items'][item['uid']]['last_seen_time'] = 0
				
				continue
			
			life['seen_items'].append(item['uid'])
			life['know_items'][item['uid']]['last_seen_at'] = item['pos'][:]
			life['know_items'][item['uid']]['last_seen_time'] = 0
			life['know_items'][item['uid']]['last_owned_by'] = None
			life['know_items'][item['uid']]['score'] = judgement.judge_item(life, item['uid'])
			life['know_items'][item['uid']]['lost'] = False