Example #1
0
def create_region_spawns():
	#Runners
	#spawns.generate_group('runner_scout', amount=random
	alife.factions.generate()
	
	return False

	#Step 3: Rookie village
	_spawn_chunks = random.choice([t['rooms'] for t in WORLD_INFO['refs']['villages'][0]])
	_rookie_village_members = spawns.generate_group('loner',
	                                                amount=random.randint(7, 9),
	                                                group_motive='survival',
	                                                spawn_chunks=_spawn_chunks)
	
	for member in _rookie_village_members:
		alife.planner.remove_goal(member, 'discover')
	
	_dirt_road_start_chunk = maps.get_chunk(WORLD_INFO['refs']['dirt_road'][0])
	_dirt_road_end_chunk =  maps.get_chunk(WORLD_INFO['refs']['dirt_road'][len(WORLD_INFO['refs']['dirt_road'])-1])
	
	for x in range(0, MAP_SIZE[0], WORLD_INFO['chunk_size']):
		for y in range(_dirt_road_end_chunk['pos'][1], _dirt_road_start_chunk['pos'][1], WORLD_INFO['chunk_size']):
			if x < _dirt_road_end_chunk['pos'][0]-(10*WORLD_INFO['chunk_size']) or x > _dirt_road_end_chunk['pos'][0]+(10*WORLD_INFO['chunk_size']):
				continue
			
			if random.randint(0, 125):
				continue
			
			_spawn_chunk = '%s,%s' % (x, y)
	
			for _alife in spawns.generate_group('feral dog', amount=random.randint(4, 6), spawn_chunks=[_spawn_chunk]):
				life.memory(_alife, 'focus_on_chunk', chunk_key=_spawn_chunk)
Example #2
0
def melee_combat(life, targets):
	_target = get_closest_target(life, targets)
	
	if not _target:
		logging.error('No target for melee combat.')
		return False
	
	if sight.can_see_position(life, _target['last_seen_at'], block_check=True, strict=True):
		_can_see = sight.can_see_position(life, _target['life']['pos'], get_path=True)
		
		if _can_see:
			if len(_can_see)>1:
				movement.find_target(life, _target['life']['id'], distance=1, follow=True)
			else:
				melee.fight(life, _target['life']['id'])
		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:
		return False
Example #3
0
def perform_moves(people):
	for life_id in people:
		_life = LIFE[life_id]
		if not _life['stance'] in _life['moves'] or not _life['next_stance']['towards']:
			continue
		
		if _life['next_stance']['towards']:
			_target = LIFE[_life['next_stance']['towards']]
			
			if _life['stance'] in _life['moves'] and _target['stance'] in _life['moves'][_life['stance']]['counters']:
				if 'player' in _target:
					gfx.message('You counter %s\'s %s.' % (' '.join(_life['name']), _target['stance']), style='player_combat_good')
				elif 'player' in _life:
					gfx.message('%s counters your %s.' % (' '.join(_target['name']), _life['stance']), style='player_combat_bad')
				
				print '%s counters %s\'s %s!' % (_target['name'], _life['name'], _life['stance'])
				
				#react_to_attack(_life, _target['id'], _target['stance'])
			else:
				lfe.memory(_life, 'shot', target=_target['id'])
				lfe.memory(_target, 'attacked', target=_life['id'])
				alife.judgement.judge_life(_target, _life['id'])
				
				if 'player' in _life:
					gfx.message('You %s %s.' % (_life['stance'], ' '.join(_target['name'])), style='player_combat_good')
				elif 'player' in _target:
					gfx.message('%s lands a %s.' % (' '.join(_life['name']), _life['stance']), style='player_combat_bad')
				
				print '%s\'s %s hits %s!' % (_life['name'], _life['stance'], _target['name'])
				react_to_attack(_target, _life['id'], _life['stance'])
			
			_life['next_stance']['towards'] = None
Example #4
0
def melee_combat(life, targets):
	_target = get_closest_target(life, targets)
	
	if not _target:
		logging.error('No target for melee combat.')
		return False
	
	if sight.can_see_position(life, _target['last_seen_at'], block_check=True, strict=True):
		_can_see = sight.can_see_position(life, _target['life']['pos'], get_path=True)
		
		if _can_see:
			if len(_can_see)>1:
				movement.find_target(life, _target['life']['id'], distance=1, follow=True)
			else:
				melee.fight(life, _target['life']['id'])
		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:
		return False
Example #5
0
def set_leader(life, group_id, life_id):
	_group = get_group(life, group_id)
	_group['leader'] = life_id
	
	set_motive(life, group_id, stats.get_group_motive(LIFE[life_id]))
	
	lfe.memory(LIFE[life_id], 'claimed to be the leader of group', group=group_id)
	logging.debug('%s claims to be the leader of group #%s' % (' '.join(LIFE[life_id]['name']), group_id))
Example #6
0
def _find_alife_and_say(life, target_id, say):
    _target = brain.knows_alife_by_id(life, target_id)

    if _find_alife(life, _target["life"]["id"]):
        speech.communicate(life, _say["gist"], matches=[_target["life"]["id"]], **say)
        lfe.memory(life, "told about founder", camp=_say["camp"], target=_target["life"]["id"])
        return True

    return False
Example #7
0
def set_focus_point(life, chunk_key):
    lfe.delete_memory(life, matches={'text': 'focus_on_chunk'})

    lfe.memory(life, 'focus_on_chunk', chunk_key=chunk_key)

    if 'player' in life:
        _center_chunk_pos = maps.get_chunk(chunk_key)['pos']
        _center_chunk_pos.append(2)

        logic.show_event('<Movement Order>', pos=_center_chunk_pos)
Example #8
0
def set_focus_point(life, chunk_key):
	lfe.delete_memory(life, matches={'text': 'focus_on_chunk'})
	
	lfe.memory(life, 'focus_on_chunk', chunk_key=chunk_key)
	
	if 'player' in life:
		_center_chunk_pos = maps.get_chunk(chunk_key)['pos']
		_center_chunk_pos.append(2)
		
		logic.show_event('<Movement Order>', pos=_center_chunk_pos)
Example #9
0
def set_focus_point(life, chunk_key):
    lfe.delete_memory(life, matches={"text": "focus_on_chunk"})

    lfe.memory(life, "focus_on_chunk", chunk_key=chunk_key)

    if "player" in life:
        _center_chunk_pos = maps.get_chunk(chunk_key)["pos"]
        _center_chunk_pos.append(2)

        logic.show_event("<Movement Order>", pos=_center_chunk_pos)
Example #10
0
def set_leader(life, group_id, life_id):
    _group = get_group(life, group_id)
    _group['leader'] = life_id

    set_motive(life, group_id, stats.get_group_motive(LIFE[life_id]))

    lfe.memory(LIFE[life_id],
               'claimed to be the leader of group',
               group=group_id)
    logging.debug('%s claims to be the leader of group #%s' %
                  (' '.join(LIFE[life_id]['name']), group_id))
Example #11
0
def _find_alife_and_say(life, target_id, say):
	_target = brain.knows_alife_by_id(life, target_id)
	
	if _find_alife(life, _target['life']['id']):
		speech.communicate(life, _say['gist'], matches=[_target['life']['id']], **say)
		lfe.memory(life,
			'told about founder',
			camp=_say['camp'],
			target=_target['life']['id'])
		return True
	
	return False
Example #12
0
def add_member(life, group_id, life_id):
    if is_member(life, group_id, life_id):
        raise Exception(
            '%s failed to add new member: %s is already a member of group: %s'
            % (' '.join(life['name']), ' '.join(
                LIFE[life_id]['name']), group_id))

    if not life['id'] == life_id:
        _target = brain.knows_alife_by_id(life, life_id)

        if _target:
            if _target['group'] == group_id:
                pass
            elif _target and _target['group']:
                lfe.memory(LIFE[life_id],
                           'left group for group',
                           left_group=_target['group'],
                           group=group_id)
                remove_member(life, _target['group'], life_id)

            _target['group'] = group_id
        else:
            _target = brain.meet_alife(life, LIFE[life_id])

        stats.establish_trust(life, life_id)
    elif life['id'] == life_id and life[
            'group'] and not life['group'] == group_id:
        remove_member(life, life['group'], life_id)

    _group = get_group(life, group_id)
    for member in _group['members']:
        brain.meet_alife(LIFE[member], LIFE[life_id])

    if _group['shelter']:
        LIFE[life_id]['shelter'] = _group['shelter']
        lfe.memory(LIFE[life_id],
                   'shelter founder',
                   shelter=_group['shelter'],
                   founder=_group['leader'])

    _group['members'].append(life_id)

    if _group['leader'] and 'player' in LIFE[_group['leader']]:
        _text = '%s has joined your group.' % ' '.join(LIFE[life_id]['name'])
        gfx.message(_text, style='good')

        if sight.can_see_target(LIFE[_group['leader']], life_id):
            logic.show_event(_text, life=LIFE[life_id], delay=1)

    logging.debug(
        '%s added %s to group \'%s\'' %
        (' '.join(life['name']), ' '.join(LIFE[life_id]['name']), group_id))
Example #13
0
def add_raid_targets(life):
	for raider in [LIFE[r] for r in raids.get_raiders(life['camp'])]:
		if raider['id'] == life['id']:
			continue
		
		if not alife.brain.knows_alife(life, raider):
			alife.brain.meet_alife(life, raider)

		if not lfe.get_memory(life, matches={'text': 'target_is_raiding', 'target': raider['id'], 'camp': life['camp']}):
			lfe.memory(life,
			           'target_is_raiding',
			           target=raider['id'],
			           camp=life['camp'])
Example #14
0
def manage_raid(life, group_id):
	if not get_stage(life, group_id) in [STAGE_RAIDING, STAGE_ATTACKING]:
		return False
	
	_raid_chunk_key = get_flag(life, group_id, 'raid_chunk')
	
	if get_flag(life, group_id, 'announced_raid_location') == _raid_chunk_key:
		return False
	
	announce(life, group_id, 'raid_location', chunk_key=_raid_chunk_key)
	flag(life, group_id, 'announced_raid_location', _raid_chunk_key)
	lfe.memory(life, 'focus_on_chunk', chunk_key=_raid_chunk_key)
	
	print 'RAID LOCATION SET' * 100
Example #15
0
def manage_raid(life, group_id):
    if not get_stage(life, group_id) in [STAGE_RAIDING, STAGE_ATTACKING]:
        return False

    _raid_chunk_key = get_flag(life, group_id, 'raid_chunk')

    if get_flag(life, group_id, 'announced_raid_location') == _raid_chunk_key:
        return False

    announce(life, group_id, 'raid_location', chunk_key=_raid_chunk_key)
    flag(life, group_id, 'announced_raid_location', _raid_chunk_key)
    lfe.memory(life, 'focus_on_chunk', chunk_key=_raid_chunk_key)

    print 'RAID LOCATION SET' * 100
Example #16
0
def _find_alife_and_say(life, target_id, say):
    _target = brain.knows_alife_by_id(life, target_id)

    if _find_alife(life, _target['life']['id']):
        speech.communicate(life,
                           _say['gist'],
                           matches=[_target['life']['id']],
                           **say)
        lfe.memory(life,
                   'told about founder',
                   camp=_say['camp'],
                   target=_target['life']['id'])
        return True

    return False
Example #17
0
def manage_jobs(life, group_id):
    _shelter = get_shelter(life, group_id)

    if not _shelter:
        return False

    if not get_stage(life, group_id) == STAGE_SETTLED:
        return False

    if get_flag(life, life['group'], 'guard_chunk_keys'):
        return False

    _guard_chunk_keys = []
    _potential_guard_chunk_keys = []
    _group_members = get_group(life, life['group'])['members']
    _shelter_chunks = references.get_reference(_shelter)[:]

    #TODO: This is horrible... like the worst possible way to do this
    for chunk_key in WORLD_INFO['chunk_map']:
        if chunk_key in _shelter_chunks:
            _shelter_chunks.remove(chunk_key)
            continue

        if bad_numbers.distance(life['pos'],
                                chunks.get_chunk(chunk_key)['pos']) > 50:
            continue

        _potential_guard_chunk_keys.append(chunk_key)

    if not _potential_guard_chunk_keys:
        return False

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

        _chunk_key = _potential_guard_chunk_keys.pop(
            random.randint(0,
                           len(_potential_guard_chunk_keys) - 1))
        _guard_chunk_keys.append(_chunk_key)
        lfe.memory(LIFE[member_id], 'focus_on_chunk', chunk_key=_chunk_key)

        if not _potential_guard_chunk_keys:
            break

    flag(life, life['group'], 'guard_chunk_keys', _guard_chunk_keys)
Example #18
0
def add_raid_targets(life):
    for raider in [LIFE[r] for r in raids.get_raiders(life['camp'])]:
        if raider['id'] == life['id']:
            continue

        if not alife.brain.knows_alife(life, raider):
            alife.brain.meet_alife(life, raider)

        if not lfe.get_memory(life,
                              matches={
                                  'text': 'target_is_raiding',
                                  'target': raider['id'],
                                  'camp': life['camp']
                              }):
            lfe.memory(life,
                       'target_is_raiding',
                       target=raider['id'],
                       camp=life['camp'])
Example #19
0
def perform_moves(people):
    for life_id in people:
        _life = LIFE[life_id]
        if not _life['stance'] in _life['moves'] or not _life['next_stance'][
                'towards']:
            continue

        if _life['next_stance']['towards']:
            _target = LIFE[_life['next_stance']['towards']]

            if _life['stance'] in _life['moves'] and _target[
                    'stance'] in _life['moves'][_life['stance']]['counters']:
                if 'player' in _target:
                    gfx.message('You counter %s\'s %s.' %
                                (' '.join(_life['name']), _target['stance']),
                                style='player_combat_good')
                elif 'player' in _life:
                    gfx.message('%s counters your %s.' %
                                (' '.join(_target['name']), _life['stance']),
                                style='player_combat_bad')

                print '%s counters %s\'s %s!' % (
                    _target['name'], _life['name'], _life['stance'])

                #react_to_attack(_life, _target['id'], _target['stance'])
            else:
                lfe.memory(_life, 'shot', target=_target['id'])
                lfe.memory(_target, 'attacked', target=_life['id'])
                alife.judgement.judge_life(_target, _life['id'])

                if 'player' in _life:
                    gfx.message('You %s %s.' %
                                (_life['stance'], ' '.join(_target['name'])),
                                style='player_combat_good')
                elif 'player' in _target:
                    gfx.message('%s lands a %s.' %
                                (' '.join(_life['name']), _life['stance']),
                                style='player_combat_bad')

                print '%s\'s %s hits %s!' % (_life['name'], _life['stance'],
                                             _target['name'])
                react_to_attack(_target, _life['id'], _life['stance'])

            _life['next_stance']['towards'] = None
Example #20
0
def manage_jobs(life, group_id):
	_shelter = get_shelter(life, group_id)
	
	if not _shelter:
		return False
	
	if not get_stage(life, group_id) == STAGE_SETTLED:
		return False
	
	if get_flag(life, life['group'], 'guard_chunk_keys'):
		return False
	
	_guard_chunk_keys = []
	_potential_guard_chunk_keys = []
	_group_members = get_group(life, life['group'])['members']
	_shelter_chunks = references.get_reference(_shelter)[:]
	
	#TODO: This is horrible... like the worst possible way to do this
	for chunk_key in WORLD_INFO['chunk_map']:
		if chunk_key in _shelter_chunks:
			_shelter_chunks.remove(chunk_key)
			continue
		
		if bad_numbers.distance(life['pos'], chunks.get_chunk(chunk_key)['pos'])>50:
			continue
		
		_potential_guard_chunk_keys.append(chunk_key)
	
	if not _potential_guard_chunk_keys:
		return False
	
	for member_id in _group_members:
		if member_id == life['id']:
			continue
		
		_chunk_key = _potential_guard_chunk_keys.pop(random.randint(0, len(_potential_guard_chunk_keys)-1))
		_guard_chunk_keys.append(_chunk_key)
		lfe.memory(LIFE[member_id], 'focus_on_chunk', chunk_key=_chunk_key)
		
		if not _potential_guard_chunk_keys:
			break
	
	flag(life, life['group'], 'guard_chunk_keys', _guard_chunk_keys)
Example #21
0
def create_region_spawns():
    #Runners
    #spawns.generate_group('runner_scout', amount=random
    alife.factions.generate()

    return False

    #Step 3: Rookie village
    _spawn_chunks = random.choice(
        [t['rooms'] for t in WORLD_INFO['refs']['villages'][0]])
    _rookie_village_members = spawns.generate_group('loner',
                                                    amount=random.randint(
                                                        7, 9),
                                                    group_motive='survival',
                                                    spawn_chunks=_spawn_chunks)

    for member in _rookie_village_members:
        alife.planner.remove_goal(member, 'discover')

    _dirt_road_start_chunk = maps.get_chunk(WORLD_INFO['refs']['dirt_road'][0])
    _dirt_road_end_chunk = maps.get_chunk(
        WORLD_INFO['refs']['dirt_road'][len(WORLD_INFO['refs']['dirt_road']) -
                                        1])

    for x in range(0, MAP_SIZE[0], WORLD_INFO['chunk_size']):
        for y in range(_dirt_road_end_chunk['pos'][1],
                       _dirt_road_start_chunk['pos'][1],
                       WORLD_INFO['chunk_size']):
            if x < _dirt_road_end_chunk['pos'][0] - (
                    10 * WORLD_INFO['chunk_size']) or x > _dirt_road_end_chunk[
                        'pos'][0] + (10 * WORLD_INFO['chunk_size']):
                continue

            if random.randint(0, 125):
                continue

            _spawn_chunk = '%s,%s' % (x, y)

            for _alife in spawns.generate_group('feral dog',
                                                amount=random.randint(4, 6),
                                                spawn_chunks=[_spawn_chunk]):
                life.memory(_alife, 'focus_on_chunk', chunk_key=_spawn_chunk)
Example #22
0
def add_member(life, group_id, life_id):
	if not group_id in LIFE[life_id]['known_groups']:
		raise Exception('DOES NOT KNOW')
	
	if is_member(life, group_id, life_id):
		raise Exception('%s failed to add new member: %s is already a member of group: %s' % (' '.join(life['name']), ' '.join(LIFE[life_id]['name']), group_id))
	
	if not life['id'] == life_id:
		_target = brain.knows_alife_by_id(life, life_id)
		
		if _target:
			if _target['group'] == group_id:
				pass
			elif _target and _target['group']:
				lfe.memory(LIFE[life_id], 'left group for group', left_group=_target['group'], group=group_id)
				remove_member(life, _target['group'], life_id)
			
			_target['group'] = group_id
		else:
			brain.meet_alife(life, LIFE[life_id])
	elif life['id'] == life_id and life['group'] and not life['group'] == group_id:
		remove_member(life, life['group'], life_id)
	
	_group = get_group(life, group_id)
	for member in _group['members']:
		brain.meet_alife(LIFE[member], LIFE[life_id])
	
	if _group['shelter']:
		LIFE[life_id]['shelter'] = _group['shelter']
		lfe.memory(LIFE[life_id], 'shelter founder', shelter=_group['shelter'], founder=_group['leader'])
	
	_group['members'].append(life_id)
	
	if _group['leader'] and 'player' in LIFE[_group['leader']]:
		_text = '%s has joined your group.' % ' '.join(LIFE[life_id]['name'])
		gfx.message(_text, style='good')
		
		if sight.can_see_target(LIFE[_group['leader']], life_id):
			logic.show_event(_text, life=LIFE[life_id], delay=1)
	
	logging.debug('%s added %s to group \'%s\'' % (' '.join(life['name']), ' '.join(LIFE[life_id]['name']), group_id))
Example #23
0
def ranged_combat(life, targets):
	_target = 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
	
	if not life['path'] or not numbers.distance(lfe.path_dest(life), _target['last_seen_at']) == 0:
		movement.position_to_attack(life, _target['life']['id'])
	
	if sight.can_see_position(life, _target['last_seen_at'], block_check=True, strict=True) and not sight.view_blocked_by_life(life, _target['last_seen_at'], allow=[_target['life']['id']]):
		if sight.can_see_position(life, _target['life']['pos']):
			if not len(lfe.find_action(life, matches=[{'action': 'shoot'}])):
				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'},
						5000,
						delay=int(round(life['recoil']-stats.get_recoil_recovery_rate(life))))
		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'], 'waiting...'
		return False
Example #24
0
def drop_cache(item_names):
	while 1:
		_chunk_key = random.choice(WORLD_INFO['chunk_map'].keys())
		_chunk = alife.chunks.get_chunk(_chunk_key)
		
		if _chunk['type'] == 'other':
			break
	
	for item in item_names:
		_pos = random.choice(_chunk['ground'])
		_item = ITEMS[items.create_item(item, position=[_pos[0], _pos[1], 2])]
		
		for life in LIFE.values():
			lfe.memory(life, 'cache_drop', chunk_key=_chunk_key)
			#alife.survival.add_needed_item(life,
			#                               {'pos': _item['pos'][:]},
			#                               satisfy_if=alife.action.make_small_script(function='always'),
			#                               satisfy_callback=alife.action.make_small_script(function='consume'))
			#alife.brain.remember_item(life, _item)
	
	gfx.message('You see something parachuting to the ground.')
	print _chunk['pos']
Example #25
0
def explode(item):
    if not item['type'] == 'explosive':
        return False

    logging.debug('The %s (item %s) explodes!' % (item['name'], item['uid']))

    #TODO: Don't breathe this!
    item['pos'] = get_pos(item['uid'])

    if item['damage']['force']:
        effects.create_explosion(item['pos'], item['damage']['force'])

    if SETTINGS['controlling'] and alife.sight.can_see_position(
            LIFE[SETTINGS['controlling']], item['pos']):
        gfx.message('%s explodes!' % get_name(item))
        logic.show_event('%s explodes!' % get_name(item), item=item, delay=0)

    #elif bad_numbers.distance(

    #TODO: Dirty hack
    for life_id in LIFE:
        _limbs = LIFE[life_id]['body'].keys()

        if not _limbs:
            continue

        _force = bad_numbers.clip(
            (item['damage']['force'] * 2) -
            bad_numbers.distance(LIFE[life_id]['pos'], item['pos']), 0, 100)

        if not _force:
            continue

        _known_item = alife.brain.remembers_item(LIFE[life_id], item)
        _direction = bad_numbers.direction_to(item['pos'],
                                              LIFE[life_id]['pos'])

        #TODO: Intelligent(?) limb groups?
        _distance = bad_numbers.distance(LIFE[life_id]['pos'], item['pos']) / 2

        for i in range(_force - _distance):
            _limb = random.choice(_limbs)

            for _attached_limb in life.get_all_attached_limbs(
                    LIFE[life_id], _limb):
                if _attached_limb in _limbs:
                    _limbs.remove(_attached_limb)

            #_limb = random.choice(LIFE[life_id]['body'].keys())

            if _known_item and _known_item[
                    'last_seen_time'] < 100 and _known_item['last_owned_by']:
                life.memory(LIFE[life_id],
                            'blown_up_by',
                            target=_known_item['last_owned_by'])

            #for _limb in _limbs:
            life.add_wound(LIFE[life_id],
                           _limb,
                           force_velocity=bad_numbers.velocity(
                               _direction, _force * 2))

            if not _limbs:
                break

        life.push(LIFE[life_id], _direction, _force)

        if 'player' in LIFE[life_id]:
            life.say(LIFE[life_id],
                     '@n are thrown by the explosion!',
                     action=True)
        else:
            life.say(LIFE[life_id],
                     '@n is thrown by the explosion!',
                     action=True)

    if 'fire' in item['damage']:
        _circle = drawing.draw_circle(item['pos'], item['radius'])
        _zone = zones.get_zone_at_coords(item['pos'])

        if _zone:
            for pos in zones.dijkstra_map(
                    item['pos'], [item['pos']], [_zone],
                    return_score_in_range=[0, item['damage']['fire']]):
                if not pos in _circle:
                    continue

                if not maps.position_is_in_map(pos):
                    continue

                for life_id in LIFE_MAP[pos[0]][pos[1]]:
                    for _visible_item in [
                            get_item_from_uid(i)
                            for i in life.get_all_visible_items(LIFE[life_id])
                    ]:
                        if not 'CAN_BURN' in _visible_item['flags']:
                            continue

                        burn(_visible_item, item['damage']['fire'])

                if not random.randint(0, 4):
                    effects.create_fire((pos[0], pos[1], item['pos'][2]),
                                        intensity=item['damage']['fire'] / 2)

                _dist = bad_numbers.distance(item['pos'], pos) / 2
                if not random.randint(0, _dist) or not _dist:
                    effects.create_ash(pos)

                if gfx.position_is_in_frame(pos):
                    _render_pos = gfx.get_render_position(pos)
                    gfx.refresh_view_position(_render_pos[0], _render_pos[1],
                                              'map')

    #if item['uid'] in ITEMS and ITEMS[item['uid']]['owner'] and item['uid'] in LIFE[ITEMS[item['uid']]['owner']]['inventory']:
    delete_item(item)
Example #26
0
def listen(life):
	for event in life['heard'][:]:
		if not event['from']['id'] in life['know']:
			pass
		
		if not brain.knows_alife(life, event['from']):
			brain.meet_alife(life, event['from'])
			
			logging.info('%s learned about %s via listen.' % (' '.join(life['name']), ' '.join(event['from']['name'])))
		
		if event['gist'] == 'looks_hostile':
			#speech.communicate(life, 'surrender', matches=[{'id': event['from']['id']}])
			pass
		
		elif event['gist'] == 'camp_raid':
			print '*' * 10
			print 'RAID IN EFFECT!!!!!!!!!!'
			print '*' * 10
			_knows = brain.knows_alife(life, event['from'])
			_raid = raids.defend_camp(event['camp']['id'], life['id'])
			
			if _knows and not judgement.is_target_dangerous(life, _knows['life']['id']):
				lfe.memory(life, 'heard about a camp raid', camp=event['camp']['id'])
				_raid_score = judgement.judge_raid(life, event['raiders'], event['camp']['id'])
				speech.announce(life, 'raid_score', raid_score=_raid_score)
		
		elif event['gist'] == 'raid_score':
			print life['name'],'Got friendly raid score:', event['raid_score'] 

		elif event['gist'] == 'share_item_info':
			if event['item'] in ITEMS:
				if not brain.has_remembered_item(life, event['item']):
					lfe.memory(life, 'heard about an item',
						item=event['item'],
						target=event['from']['id'])
					brain.remember_item(life, ITEMS[event['item']])
		
		elif event['gist'] == 'camp_founder':
			lfe.memory(life, 'heard about camp',
				camp=event['camp'],
				target=event['founder'],
				founder=event['founder'])
			
			print 'Thanks for the camp founder info!'
		
		elif event['gist'] == 'under_attack':
			_knows_attacker = True
			
			if life['id'] == event['attacker']:
				pass
			else:
				print life['name'], 'HEARD CALL FOR HELP FROM', event['from']['name']
				if not brain.knows_alife_by_id(life, event['attacker']):
					brain.meet_alife(life, LIFE[event['attacker']])
					_knows_attacker = False
				
				_target = brain.knows_alife_by_id(life, event['attacker'])
				_believes = judgement.believe_which_alife(life, [event['from']['id'], event['attacker']])
	
				#SITUATION 1: We believe it
				if _believes == event['from']['id']:
					lfe.memory(life, 'heard about attack',
						attacker=event['attacker'],
						target=event['from']['id'])
					lfe.memory(life, 'target attacked victim',
						target=event['attacker'],
						victim=event['from']['id'])
					
					if event['last_seen_at']:
						_target['last_seen_at'] = event['last_seen_at'][:]
					else:
						_target['last_seen_at'] = event['from']['pos'][:]
					
					judgement.judge_life(life, event['attacker'])
				else:
					lfe.memory(life, 'reject under_attack: attacker is trusted',
						attacker=event['attacker'],
						target=event['from']['id'])
		
		elif event['gist'] == 'bit':
			#React to attack... this needs to be a function in stats.py
			if event['target'] == life['id']:
				pass
			else:
				_trust_sender = judgement.can_trust(life, event['from']['id'])
				
				if brain.knows_alife_by_id(life, event['target']):
					_trust_target = judgement.can_trust(life, event['target'], low=5)
				else:
					brain.meet_alife(life, LIFE[event['target']])
					_trust_target = False
				
				if _trust_target and not _trust_sender and 1==4:
					lfe.memory(life, 'trusted target attacked by',
					           victim=event['target'],
					           target=event['from']['id'])

		elif event['gist'] == 'consume_item':
			lfe.memory(life, 'consume_item', target=event['from']['id'])
		
		elif event['gist'] == 'call':
			if judgement.can_trust(life, event['from']['id']):
				speech.start_dialog(life, event['from']['id'], 'call_accepted', remote=True)
		
		elif event['gist'] == 'order_attack':
			lfe.memory(life, 'ordered to attack',
			           target=event['target'])
		
		elif event['gist'] == 'threw_an_item':
			print 'CHECK THIS HERE' * 100
			pass
		
		elif event['gist'] == '_group_leader_state_change':
			life['think_rate'] = 0
		
		elif event['gist'] == 'dialog':
			if not 'player' in life and not event['dialog_id'] in life['dialogs']:
				life['dialogs'].append(event['dialog_id'])
		
		else:
			logging.warning('Unhandled ALife context: %s' % event['gist'])
		
		life['heard'].remove(event)
Example #27
0
def listen(life):
    for event in life['heard'][:]:
        if not event['from']['id'] in life['know']:
            pass

        if not brain.knows_alife(life, event['from']):
            brain.meet_alife(life, event['from'])

            logging.info(
                '%s learned about %s via listen.' %
                (' '.join(life['name']), ' '.join(event['from']['name'])))

        if event['gist'] == 'looks_hostile':
            #speech.communicate(life, 'surrender', matches=[{'id': event['from']['id']}])
            pass

        elif event['gist'] == 'camp_raid':
            print '*' * 10
            print 'RAID IN EFFECT!!!!!!!!!!'
            print '*' * 10
            _knows = brain.knows_alife(life, event['from'])
            _raid = raids.defend_camp(event['camp']['id'], life['id'])

            if _knows and not judgement.is_target_dangerous(
                    life, _knows['life']['id']):
                lfe.memory(life,
                           'heard about a camp raid',
                           camp=event['camp']['id'])
                _raid_score = judgement.judge_raid(life, event['raiders'],
                                                   event['camp']['id'])
                speech.announce(life, 'raid_score', raid_score=_raid_score)

        elif event['gist'] == 'raid_score':
            print life['name'], 'Got friendly raid score:', event['raid_score']

        elif event['gist'] == 'share_item_info':
            if event['item'] in ITEMS:
                if not brain.has_remembered_item(life, event['item']):
                    lfe.memory(life,
                               'heard about an item',
                               item=event['item'],
                               target=event['from']['id'])
                    brain.remember_item(life, ITEMS[event['item']])

        elif event['gist'] == 'camp_founder':
            lfe.memory(life,
                       'heard about camp',
                       camp=event['camp'],
                       target=event['founder'],
                       founder=event['founder'])

            print 'Thanks for the camp founder info!'

        elif event['gist'] == 'under_attack':
            _knows_attacker = True

            if life['id'] == event['attacker']:
                pass
            else:
                print life['name'], 'HEARD CALL FOR HELP FROM', event['from'][
                    'name']
                if not brain.knows_alife_by_id(life, event['attacker']):
                    brain.meet_alife(life, LIFE[event['attacker']])
                    _knows_attacker = False

                _target = brain.knows_alife_by_id(life, event['attacker'])
                _believes = judgement.believe_which_alife(
                    life, [event['from']['id'], event['attacker']])

                #SITUATION 1: We believe it
                if _believes == event['from']['id']:
                    lfe.memory(life,
                               'heard about attack',
                               attacker=event['attacker'],
                               target=event['from']['id'])
                    lfe.memory(life,
                               'target attacked victim',
                               target=event['attacker'],
                               victim=event['from']['id'])

                    if event['last_seen_at']:
                        _target['last_seen_at'] = event['last_seen_at'][:]
                    else:
                        _target['last_seen_at'] = event['from']['pos'][:]

                    judgement.judge_life(life, event['attacker'])
                else:
                    lfe.memory(life,
                               'reject under_attack: attacker is trusted',
                               attacker=event['attacker'],
                               target=event['from']['id'])

        elif event['gist'] == 'bit':
            #React to attack... this needs to be a function in stats.py
            if event['target'] == life['id']:
                pass
            else:
                _trust_sender = judgement.can_trust(life, event['from']['id'])

                if brain.knows_alife_by_id(life, event['target']):
                    _trust_target = judgement.can_trust(life,
                                                        event['target'],
                                                        low=5)
                else:
                    brain.meet_alife(life, LIFE[event['target']])
                    _trust_target = False

                if _trust_target and not _trust_sender and 1 == 4:
                    lfe.memory(life,
                               'trusted target attacked by',
                               victim=event['target'],
                               target=event['from']['id'])

        elif event['gist'] == 'consume_item':
            lfe.memory(life, 'consume_item', target=event['from']['id'])

        elif event['gist'] == 'call':
            if judgement.can_trust(life, event['from']['id']):
                speech.start_dialog(life,
                                    event['from']['id'],
                                    'call_accepted',
                                    remote=True)

        elif event['gist'] == 'order_attack':
            lfe.memory(life, 'ordered to attack', target=event['target'])

        elif event['gist'] == 'threw_an_item':
            print 'CHECK THIS HERE' * 100
            pass

        elif event['gist'] == '_group_leader_state_change':
            life['think_rate'] = 0

        elif event['gist'] == 'dialog':
            if not 'player' in life and not event['dialog_id'] in life[
                    'dialogs']:
                life['dialogs'].append(event['dialog_id'])

        else:
            logging.warning('Unhandled ALife context: %s' % event['gist'])

        life['heard'].remove(event)
Example #28
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})
Example #29
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 #30
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 #31
0
def explode(item):
	if not item['type'] == 'explosive':
		return False
	
	logging.debug('The %s (item %s) explodes!' % (item['name'], item['uid']))
	
	#TODO: Don't breathe this!
	item['pos'] = get_pos(item['uid'])
	
	if item['damage']['force']:
		effects.create_explosion(item['pos'], item['damage']['force'])
	
	if SETTINGS['controlling'] and alife.sight.can_see_position(LIFE[SETTINGS['controlling']], item['pos']):
		gfx.message('%s explodes!' % get_name(item))
		logic.show_event('%s explodes!' % get_name(item), item=item, delay=0)
		
	#elif bad_numbers.distance(
	
	#TODO: Dirty hack
	for life_id in LIFE:
		_limbs = LIFE[life_id]['body'].keys()
		
		if not _limbs:
			continue
		
		_force = bad_numbers.clip((item['damage']['force']*2)-bad_numbers.distance(LIFE[life_id]['pos'], item['pos']), 0, 100)
		
		if not _force:
			continue
		
		_known_item = alife.brain.remembers_item(LIFE[life_id], item)
		_direction = bad_numbers.direction_to(item['pos'], LIFE[life_id]['pos'])
		
		#TODO: Intelligent(?) limb groups?
		_distance = bad_numbers.distance(LIFE[life_id]['pos'], item['pos'])/2
		
		for i in range(_force-_distance):
			_limb = random.choice(_limbs)
			
			for _attached_limb in life.get_all_attached_limbs(LIFE[life_id], _limb):
				if _attached_limb in _limbs:
					_limbs.remove(_attached_limb)
			
			#_limb = random.choice(LIFE[life_id]['body'].keys())
			
			if _known_item and _known_item['last_seen_time'] < 100 and _known_item['last_owned_by']:
				life.memory(LIFE[life_id], 'blown_up_by', target=_known_item['last_owned_by'])
			
			#for _limb in _limbs:
			life.add_wound(LIFE[life_id], _limb, force_velocity=bad_numbers.velocity(_direction, _force*2))
			
			if not _limbs:
				break
		
		life.push(LIFE[life_id], _direction, _force)
		
		if 'player' in LIFE[life_id]:
			life.say(LIFE[life_id], '@n are thrown by the explosion!', action=True)
		else:
			life.say(LIFE[life_id], '@n is thrown by the explosion!', action=True)
	
	if 'fire' in item['damage']:
		_circle = drawing.draw_circle(item['pos'], item['radius'])
		_zone = zones.get_zone_at_coords(item['pos'])
		
		if _zone:	
			for pos in zones.dijkstra_map(item['pos'], [item['pos']], [_zone], return_score_in_range=[0, item['damage']['fire']]):
				if not pos in _circle:
					continue
				
				if not maps.position_is_in_map(pos):
					continue
				
				for life_id in LIFE_MAP[pos[0]][pos[1]]:
					for _visible_item in [get_item_from_uid(i) for i in life.get_all_visible_items(LIFE[life_id])]:
						if not 'CAN_BURN' in _visible_item['flags']:
							continue
						
						burn(_visible_item, item['damage']['fire'])
				
				if not random.randint(0, 4):
					effects.create_fire((pos[0], pos[1], item['pos'][2]),
					                    intensity=item['damage']['fire']/2)
			
				_dist = bad_numbers.distance(item['pos'], pos)/2
				if not random.randint(0, _dist) or not _dist:
					effects.create_ash(pos)
		
				if gfx.position_is_in_frame(pos):
					_render_pos = gfx.get_render_position(pos)
					gfx.refresh_view_position(_render_pos[0], _render_pos[1], 'map')
	
	#if item['uid'] in ITEMS and ITEMS[item['uid']]['owner'] and item['uid'] in LIFE[ITEMS[item['uid']]['owner']]['inventory']:
	delete_item(item)