Exemple #1
0
def update_targets_around_noise(life, noise):
	_most_likely_target = {'target': None, 'last_seen_time': 0}
	
	if 'target' in noise and not life['id'] == noise['target']:
		_visiblity = numbers.clip(sight.get_stealth_coverage(LIFE[noise['target']]), 0.0, 1.0)
		_visiblity = numbers.clip(_visiblity+(numbers.distance(life['pos'], LIFE[noise['target']]['pos']))/(sight.get_vision(life)/2), 0, 1.0)
		
		if _visiblity >= sight.get_visiblity_of_position(life, LIFE[noise['target']]['pos']):
			brain.meet_alife(life, LIFE[noise['target']])
			
			life['know'][noise['target']]['escaped'] = 1
			life['know'][noise['target']]['last_seen_at'] = noise['pos'][:]
			life['know'][noise['target']]['last_seen_time'] = 0
	
	for target in life['know'].values():
		if not target['escaped'] or not target['last_seen_at'] or target['dead']:
			continue
		
		if numbers.distance(target['last_seen_at'], noise['pos']) > noise['volume']:
			continue
		
		if judgement.is_target_threat(life, target['life']['id']):
			if not _most_likely_target['target'] or target['last_seen_time'] < _most_likely_target['last_seen_time']:
				_most_likely_target['last_seen_time'] = target['last_seen_time']
				_most_likely_target['target'] = target
	
	if _most_likely_target['target']:
		_most_likely_target['target']['escaped'] = 1
		_most_likely_target['target']['last_seen_at'] = noise['pos'][:]
		_most_likely_target['target']['last_seen_time'] = 1
		
		logging.debug('%s heard a noise, attributing it to %s.' % (' '.join(life['name']), ' '.join(_most_likely_target['target']['life']['name'])))
Exemple #2
0
    def check_chunks(self, force=False):
        if not force and WORLD_INFO["ticks"] - self.last_checked < self.check_every:
            return False

        self.last_checked = WORLD_INFO["ticks"]

        for life in [l for l in LIFE.values() if l["online"]]:
            _x_min = numbers.clip(life["pos"][0] - MAP_WINDOW_SIZE[0], 0, MAP_SIZE[0] - 1 - MAP_WINDOW_SIZE[0])
            _y_min = numbers.clip(life["pos"][1] - MAP_WINDOW_SIZE[1], 0, MAP_SIZE[1] - 1 - MAP_WINDOW_SIZE[1])
            _x_max = numbers.clip(life["pos"][0] + MAP_WINDOW_SIZE[0], 0, MAP_SIZE[0] - 1)
            _y_max = numbers.clip(life["pos"][1] + MAP_WINDOW_SIZE[1], 0, MAP_SIZE[1] - 1)
            _refresh = False

            for y in range(_y_min, _y_max, WORLD_INFO["chunk_size"]):
                for x in range(_x_min, _x_max, WORLD_INFO["chunk_size"]):
                    maps.load_cluster_at_position_if_needed((x, y))

                    SETTINGS["loading"] = True

                    if "player" in life:
                        _refresh = True

            if _refresh:
                gfx.refresh_view("map")

        SETTINGS["loading"] = False
Exemple #3
0
def get_overwatch_hardship(no_mod=True):
	_stats = WORLD_INFO['overwatch']
	_situation = get_player_situation()
	
	if not _situation:
		return 0
	
	if no_mod:
		_mod = 1
	else:
		if len(_situation['online_alife']) == len(_situation['trusted_online_alife']):
			_mod = _stats['last_updated']/float(WORLD_INFO['ticks'])
		else:
			_mod = numbers.clip((_stats['last_updated']*1.5)/float(WORLD_INFO['ticks']), 0, 1.0)
			
			#TODO: Decay
			#_stats['loss_experienced'] *= _dec
			#_stats['danger_experienced'] *= _dec
			#_stats['injury'] *= _dec
			#_stats['human_encounters'] *= _dec
	
	_hardship = _stats['loss_experienced']
	_hardship += _stats['danger_experienced']
	_hardship += _stats['injury']
	_hardship += _stats['human_encounters']*4
	_hardship *= _mod
	
	return numbers.clip(float(_hardship), 0.0, 10.0)
Exemple #4
0
def get_stealth_coverage(life):
    _coverage = 1.0

    if life['stance'] == 'standing':
        _stealth_mod = 1.0
    elif life['stance'] == 'crouching':
        _stealth_mod = 0.75
    else:
        _stealth_mod = 0.55

    _visible_chunk_keys = brain.get_flag(life, 'visible_chunks')

    if _visible_chunk_keys:
        _visible_chunks = len(_visible_chunk_keys)
    else:
        _visible_chunks = 100

    _stealth_mod *= numbers.clip(_visible_chunks / 100.0, 0, 1.0)

    for z in range(1, 6):
        if WORLD_INFO['map'][life['pos'][0]][life['pos'][1]][life['pos'][2] +
                                                             z]:
            _coverage *= _stealth_mod

    return numbers.clip(_coverage, 0.0, 1.0)
Exemple #5
0
    def check_chunks(self, force=False):
        if not force and WORLD_INFO[
                'ticks'] - self.last_checked < self.check_every:
            return False

        self.last_checked = WORLD_INFO['ticks']

        for life in [l for l in LIFE.values() if l['online']]:
            _x_min = numbers.clip(life['pos'][0] - MAP_WINDOW_SIZE[0], 0,
                                  MAP_SIZE[0] - 1 - MAP_WINDOW_SIZE[0])
            _y_min = numbers.clip(life['pos'][1] - MAP_WINDOW_SIZE[1], 0,
                                  MAP_SIZE[1] - 1 - MAP_WINDOW_SIZE[1])
            _x_max = numbers.clip(life['pos'][0] + MAP_WINDOW_SIZE[0], 0,
                                  MAP_SIZE[0] - 1)
            _y_max = numbers.clip(life['pos'][1] + MAP_WINDOW_SIZE[1], 0,
                                  MAP_SIZE[1] - 1)
            _refresh = False

            for y in range(_y_min, _y_max, WORLD_INFO['chunk_size']):
                for x in range(_x_min, _x_max, WORLD_INFO['chunk_size']):
                    maps.load_cluster_at_position_if_needed((x, y))

                    SETTINGS['loading'] = True

                    if 'player' in life:
                        _refresh = True

            if _refresh:
                gfx.refresh_view('map')

        SETTINGS['loading'] = False
Exemple #6
0
def generate_los(life,
                 target,
                 at,
                 source_map,
                 score_callback,
                 invert=False,
                 ignore_starting=False):
    _stime = time.time()
    _cover = {'pos': None, 'score': 9000}

    _x = numbers.clip(at[0] - (SETTINGS['los'] / 2), 0,
                      MAP_SIZE[0] - (SETTINGS['los'] / 2))
    _y = numbers.clip(at[1] - (SETTINGS['los'] / 2), 0,
                      MAP_SIZE[1] - (SETTINGS['los'] / 2))
    _top_left = (_x, _y, at[2])

    target_los = render_fast_los.render_fast_los(at, SETTINGS['los'],
                                                 source_map)

    for pos in render_los.draw_circle(life['pos'][0], life['pos'][1], 30):
        x = pos[0] - _top_left[0]
        y = pos[1] - _top_left[1]

        if pos[0] < 0 or pos[1] < 0 or pos[0] >= MAP_SIZE[0] or pos[
                1] >= MAP_SIZE[0]:
            continue

        if x < 0 or y < 0 or x >= target_los.shape[1] or y >= target_los.shape[
                0]:
            continue

        if life['pos'][0] - _top_left[0] >= target_los.shape[
                1] or life['pos'][1] - _top_left[1] >= target_los.shape[0]:
            continue

        if target_los[life['pos'][1] - _top_left[1], life['pos'][0] -
                      _top_left[0]] == invert and not ignore_starting:
            _cover['pos'] = life['pos'][:]
            return False

        if source_map[pos[0]][pos[1]][at[2] +
                                      1] or source_map[pos[0]][pos[1]][at[2] +
                                                                       2]:
            continue

        if target_los[y, x] == invert:
            #TODO: Additional scores, like distance from target
            _score = score_callback(life, target, pos)

            if _score < _cover['score']:
                _cover['score'] = _score
                _cover['pos'] = list(pos)

    #print time.time()-_stime
    if not _cover['pos']:
        print 'Nowhere to hide', target['life']['name'], _top_left

        return False

    return _cover
Exemple #7
0
def is_confident(life):
	_friendly_confidence = 0
	_threat_confidence = 0
	
	for target_id in judgement.get_trusted(life, visible=False):
		_knows = brain.knows_alife_by_id(life, target_id)
		
		if _knows['dead'] or _knows['asleep']:
			continue
		
		_recent_mod = numbers.clip(_knows['last_seen_time'], 0, 300)/300.0
		
		if _knows['last_seen_time']:
			_friendly_confidence += _recent_mod
		else:
			_friendly_confidence += judgement.get_ranged_combat_rating_of_target(life, target_id)*_recent_mod
	
	for target_id in judgement.get_threats(life, ignore_escaped=True):
		_knows = brain.knows_alife_by_id(life, target_id)
		
		if _knows['dead'] or _knows['asleep']:
			continue
		
		_recent_mod = numbers.clip(_knows['last_seen_time'], 0, 300)/300.0
		
		if _knows['last_seen_time']:
			_threat_confidence += 2*_recent_mod
		else:
			_threat_confidence += judgement.get_ranged_combat_rating_of_target(life, target_id)*_recent_mod
	
	return _friendly_confidence > _threat_confidence
Exemple #8
0
def draw_chunk_map(life=None, show_faction_ownership=False):
	_x_min = numbers.clip(CAMERA_POS[0]/WORLD_INFO['chunk_size'], 0, MAP_SIZE[0]/WORLD_INFO['chunk_size'])
	_y_min = numbers.clip(CAMERA_POS[1]/WORLD_INFO['chunk_size'], 0, MAP_SIZE[1]/WORLD_INFO['chunk_size'])
	_x_max = numbers.clip(_x_min+WINDOW_SIZE[0], 0, MAP_SIZE[0]/WORLD_INFO['chunk_size'])
	_y_max = numbers.clip(_y_min+WINDOW_SIZE[1], 0, MAP_SIZE[1]/WORLD_INFO['chunk_size'])
	
	_life_chunk_key = None
	
	if life:
		_life_chunk_key = lfe.get_current_chunk_id(life)
	
	for x in range(_x_min, _x_max):
		_d_x = x-(CAMERA_POS[0]/WORLD_INFO['chunk_size'])
		
		if 0>_d_x >= WINDOW_SIZE[0]:
			continue
		
		for y in range(_y_min, _y_max):
			_d_y = y-(CAMERA_POS[1]/WORLD_INFO['chunk_size'])
			_draw = True
			_fore_color = tcod.darker_gray
			_back_color = tcod.darkest_gray
			
			if 0>_d_y >= WINDOW_SIZE[1]:
				continue
			
			_chunk_key = '%s,%s' % (x*WORLD_INFO['chunk_size'], y*WORLD_INFO['chunk_size'])
			
			if life:
				if not _chunk_key in life['known_chunks']:
					_draw = False
			
			if _draw:
				_type = WORLD_INFO['chunk_map'][_chunk_key]['type']
				_char = 'x'
				
				if _type in ['building', 'town']:
					_fore_color = tcod.light_gray
					_char = 'B'
				elif _type in ['outpost', 'factory']:
					_fore_color = tcod.desaturated_green
					_back_color = tcod.desaturated_han
					_char = 'M'
				elif _type == 'field':
					_fore_color = tcod.yellow
				elif _type == 'forest':
					_fore_color = tcod.dark_green
				elif _type in ['road', 'driveway']:
					_fore_color = tcod.white
					_back_color = tcod.black
					_char = '.'
				
				if _chunk_key == _life_chunk_key and time.time()%1>=.5:
					_fore_color = tcod.white
					_char = 'X'
				
				gfx.blit_char_to_view(_d_x, _d_y, _char, (_fore_color, _back_color), 'chunk_map')
			else:
				gfx.blit_char_to_view(_d_x, _d_y, 'x', (tcod.darker_gray, tcod.darkest_gray), 'chunk_map')
Exemple #9
0
def death():
    FADE_TO_WHITE[0] += 0.5

    _time_since_death = FADE_TO_WHITE[0]
    _time_alive = numbers.clip(
        (LIFE[SETTINGS["controlling"]]["time_of_death"] - LIFE[SETTINGS["controlling"]]["created"])
        / float(WORLD_INFO["length_of_day"]),
        0.1,
        9999,
    )
    _string = "You die."
    _sub_string = LIFE[SETTINGS["controlling"]]["cause_of_death"]
    _col = int(round(255 * numbers.clip((_time_since_death / 100.0) - random.uniform(0, 0.15), 0, 1)))

    if _time_alive == 1:
        _sub_sub_string = "Lived 1 day"
    else:
        _sub_sub_string = "Lived %s days" % (_time_alive)

    gfx.fade_to_black(1)

    gfx.blit_string(
        (MAP_WINDOW_SIZE[0] / 2) - len(_string) / 2,
        MAP_WINDOW_SIZE[1] / 2,
        _string,
        "map",
        fore_color=tcod.Color(_col, 0, 0),
        back_color=tcod.Color(0, 0, 0),
    )

    gfx.blit_string(
        (MAP_WINDOW_SIZE[0] / 2) - len(_sub_string) / 2,
        (MAP_WINDOW_SIZE[1] / 2) + 2,
        _sub_string,
        "map",
        fore_color=tcod.Color(int(round(_col * 0.75)), int(round(_col * 0.75)), int(round(_col * 0.75))),
        back_color=tcod.Color(0, 0, 0),
    )

    gfx.blit_string(
        (MAP_WINDOW_SIZE[0] / 2) - len(_sub_sub_string) / 2,
        (MAP_WINDOW_SIZE[1] / 2) + 4,
        _sub_sub_string,
        "map",
        fore_color=tcod.Color(int(round(_col * 0.75)), int(round(_col * 0.75)), int(round(_col * 0.75))),
        back_color=tcod.Color(0, 0, 0),
    )

    if _time_since_death >= 350:
        worldgen.save_world()
        worldgen.reset_world()

        gfx.clear_scene()

        SETTINGS["running"] = 1
        return False

    return True
Exemple #10
0
def draw_message_box():
	_view = get_view_by_name('message_box')
	
	if not _is_view_dirty(_view):
		return False
	
	_set_view_clean(_view)
	
	#blit_string(1, 0, 'Messages', 'message_box', fore_color=tcod.white)
	
	_y_mod = 1
	_lower = numbers.clip(0,len(MESSAGE_LOG)-MESSAGE_LOG_MAX_LINES,100000)
	_i = -1
	for msg in MESSAGE_LOG[_lower:len(MESSAGE_LOG)]:
		if msg['count']:
			_text = '%s (x%s)' % (msg['msg'], msg['count']+1)
		else:		
			_text = msg['msg']
		
		if msg['style'] == 'damage':
			_fore_color = tcod.red
		elif msg['style'] == 'speech':
			_fore_color = tcod.gray
		elif msg['style'] == 'action':
			_fore_color = tcod.lighter_crimson
		elif msg['style'] == 'important':
			_fore_color = tcod.Color(150,150,255)
		elif msg['style'] == 'radio':
			_fore_color = tcod.Color(225,245,169)
		elif msg['style'] == 'good':
			_fore_color = tcod.light_green
		elif msg['style'] == 'player_combat_good':
			_fore_color = tcod.green
		elif msg['style'] == 'player_combat_bad':
			_fore_color = tcod.crimson
		else:
			_fore_color = tcod.white
		
		_c = 9*((_i>0)+1)
		_back_color = tcod.Color(_c, _c, _c)
		
		_i = -_i
		
		while _text:
			_print_text = _text[:_view['draw_size'][0]-2]
			_padding = ' '*numbers.clip(_view['draw_size'][0], 0, _view['draw_size'][0]-len(_print_text)-2)
			blit_string(1, _y_mod, _print_text+_padding, 'message_box', fore_color=_fore_color, back_color=_back_color)
			_y_mod += 1
			_text = _text[_view['draw_size'][0]-2:]
			
			if _y_mod > MESSAGE_LOG_MAX_LINES:
				break
			
			if not _text.startswith(' ') and _text:
				_text = ' '+_text
		
		if _y_mod > MESSAGE_LOG_MAX_LINES:
			break
Exemple #11
0
def _generate_los(life,
                  target,
                  at,
                  source_map,
                  score_callback,
                  invert=False,
                  ignore_starting=False):
    #Step 1: Locate cover
    _cover = {'pos': None, 'score': 9000}

    #TODO: Unchecked Cython flag
    _x = numbers.clip(at[0] - (MAP_WINDOW_SIZE[0] / 2), 0, MAP_SIZE[0])
    _y = numbers.clip(at[1] - (MAP_WINDOW_SIZE[1] / 2), 0, MAP_SIZE[1])
    _top_left = (_x, _y, at[2])
    target_los = render_los.render_los(source_map,
                                       at,
                                       top_left=_top_left,
                                       no_edge=False)

    for pos in render_los.draw_circle(life['pos'][0], life['pos'][1], 30):
        x = pos[0] - _top_left[0]
        y = pos[1] - _top_left[1]

        if pos[0] < 0 or pos[1] < 0 or pos[0] >= MAP_SIZE[0] or pos[
                1] >= MAP_SIZE[0]:
            continue

        if x < 0 or y < 0 or x >= target_los.shape[1] or y >= target_los.shape[
                0]:
            continue

        if life['pos'][0] - _top_left[0] >= target_los.shape[
                0] or life['pos'][1] - _top_left[1] >= target_los.shape[1]:
            continue

        if target_los[life['pos'][1] - _top_left[1], life['pos'][0] -
                      _top_left[0]] == invert and not ignore_starting:
            _cover['pos'] = life['pos'][:]
            return False

        if source_map[pos[0]][pos[1]][at[2] +
                                      1] or source_map[pos[0]][pos[1]][at[2] +
                                                                       2]:
            continue

        if target_los[y, x] == invert:
            #TODO: Additional scores, like distance from target
            _score = score_callback(life, target['life'], pos)

            if _score < _cover['score']:
                _cover['score'] = _score
                _cover['pos'] = list(pos)

    if not _cover['pos']:
        print 'Nowhere to hide'
        return False

    return _cover
Exemple #12
0
def is_confident(life):
    if 'player' in life:
        return False

    _friendly_confidence = judgement.get_ranged_combat_rating_of_target(
        life, life['id'])
    _threat_confidence = 0

    for target_id in judgement.get_trusted(life, visible=False):
        _knows = brain.knows_alife_by_id(life, target_id)

        if _knows['dead'] or _knows['asleep']:
            continue

        if _knows['last_seen_time'] > 30:
            if brain.get_alife_flag(life, target_id, 'threat_score'):
                _recent_mod = 1 - (
                    numbers.clip(_knows['last_seen_time'], 0, 300) / 300.0)
                _score = brain.get_alife_flag(life, target_id, 'threat_score')
                _friendly_confidence += _score * _recent_mod
            else:
                _friendly_confidence += 1
        else:
            _score = judgement.get_ranged_combat_rating_of_target(
                life, target_id)

            brain.flag_alife(life, target_id, 'threat_score', value=_score)

            _friendly_confidence += _score

    for target_id in judgement.get_threats(life, ignore_escaped=False):
        _knows = brain.knows_alife_by_id(life, target_id)

        if _knows['dead'] or _knows['asleep']:
            continue

        if _knows['last_seen_time']:
            if brain.get_alife_flag(life, target_id, 'threat_score'):
                if _knows['last_seen_time'] > 50:
                    _recent_mod = 1 - (
                        numbers.clip(_knows['last_seen_time'], 0, 600) / 600.0)
                else:
                    _recent_mod = 1

                _score = brain.get_alife_flag(life, target_id, 'threat_score')
                _threat_confidence += _score * _recent_mod
            else:
                _threat_confidence += 1
        else:
            _score = judgement.get_ranged_combat_rating_of_target(
                life, target_id, inventory_check=False)

            brain.flag_alife(life, target_id, 'threat_score', value=_score)

            _threat_confidence += _score

    return _friendly_confidence - _threat_confidence >= -2
Exemple #13
0
def draw_intro():
	_stime = time.time()
	_title_time = time.time()
	_warning_time = None
	_warning_message = VERSION
	_sub_mod = 0
	_sub_time = 0
	_shadow = 50
	_burn = 8.0
	_char_alpha = {c: random.uniform(.15, .7) for c in SUB_LINE}
	
	#Why did I base this on time.time()?
	while time.time()-_stime<=5:
		_text = INTRO
		
		if time.time()-_stime<=1:
			_text = list(_text)
			random.shuffle(_text)
			_text = ''.join(_text)
		else:
			if not _sub_time:
				_sub_time = time.time()
			
			if 4.0>time.time()-_stime:
				_burn *= 1.005
			elif time.time()-_stime>=4.0 and _burn>255:
				_burn = 255
			
			_text = INTRO
		
		_mod = int(round(255*numbers.clip(time.time()-_title_time, 0, 1)))
		
		console_set_default_foreground(0, Color(_mod, _mod, _mod))
		console_print(0, (WINDOW_SIZE[0]/2)-len(_text)/2, (WINDOW_SIZE[1]/2)-2, _text)
		
		if time.time()-_stime>=1:
			if not _warning_time:
				_warning_time = time.time()
			
			_mod = int(round(255*numbers.clip(time.time()-_warning_time, 0, 1)))
		
			console_set_default_foreground(0, Color(_mod/2, _mod/2, _mod/2))
			console_print(0, 0, WINDOW_SIZE[1]-1, _warning_message)
		
		if time.time()-_stime>=1.2:
			_i = 0
			for c in SUB_LINE:
				_c_mod = _char_alpha[c]
				_mod = numbers.clip(time.time()-_warning_time, 0, 1)
				console_set_default_foreground(0, Color(int(round((200*_mod)*_c_mod)), 0, 0))
				console_print(0, _i+(WINDOW_SIZE[0]/2)-len(SUB_LINE)/2, (WINDOW_SIZE[1]/2), c)
				_char_alpha[c] = numbers.clip(_char_alpha[c]*1.015, 0, 1)
				_i += 1
		
		console_flush()
	
	SETTINGS['running'] = 1
Exemple #14
0
def calculate_fire(fire):
	_neighbor_intensity = 0
	_neighbor_lit = False
	
	for x in range(-1, 2):
		_x = fire['pos'][0]+x
		
		if _x<0 or _x>=MAP_SIZE[0]:
			continue
		
		for y in range(-1, 2):
			if not x and not y:
				continue
			
			_y = fire['pos'][1]+y
			
			if _y<0 or _y>=MAP_SIZE[1]:
				continue
			
			_effects = [EFFECTS[eid] for eid in EFFECT_MAP[_x][_y] if EFFECTS[eid]['type'] == 'fire']
			for effect in _effects:
				_neighbor_intensity += effect['intensity']
				
				if 'light' in effect:
					_neighbor_lit = True
			
			if not _effects:
				_tile = WORLD_INFO['map'][_x][_y][fire['pos'][2]]
				_raw_tile = tiles.get_raw_tile(_tile)
				
				_heat = tiles.get_flag(WORLD_INFO['map'][_x][_y][fire['pos'][2]], 'heat')
				_current_burn = int(round(fire['intensity']))
				_max_burn = int(round(_current_burn*.23))
				
				if tiles.flag(_tile, 'heat', numbers.clip(_heat+(fire['intensity']*.01), 0, 8))>=_raw_tile['burnable']:
					if _raw_tile['burnable'] and _max_burn:
						create_fire((_x, _y, fire['pos'][2]), intensity=random.randint(1, numbers.clip(1+_max_burn, 2, 8)))
	
	_intensity = ((64-_neighbor_intensity)/64.0)*random.uniform(0, SETTINGS['fire burn rate'])
	fire['intensity'] -= _intensity
	
	for life in [LIFE[life_id] for life_id in LIFE_MAP[fire['pos'][0]][fire['pos'][1]]]:
		lfe.burn(life, fire['intensity'])
	
	for item in items.get_items_at(fire['pos']):
		items.burn(item, fire['intensity'])
	
	update_effect(fire)
	
	if fire['intensity'] <= 0.25:
		unregister_effect(fire)
	
	if 'light' in fire:
		fire['light']['brightness'] -= numbers.clip(_intensity*.015, 0, 5)
	elif not _neighbor_lit:
		fire['light'] = create_light(fire['pos'], (255, 69, 0), 17*(fire['intensity']/8.0), 0.25)
Exemple #15
0
def move_camera(pos, scroll=False):
	_orig_pos = CAMERA_POS[:]
	CAMERA_POS[0] = numbers.clip(pos[0]-(WINDOW_SIZE[0]/2),0,MAP_SIZE[0]-WINDOW_SIZE[0])
	CAMERA_POS[1] = numbers.clip(pos[1]-(WINDOW_SIZE[1]/2),0,MAP_SIZE[1]-WINDOW_SIZE[1])
	CAMERA_POS[2] = pos[2]
	
	if not _orig_pos == CAMERA_POS:
		gfx.refresh_view('map')
	elif SETTINGS['controlling'] and not alife.brain.get_flag(LIFE[SETTINGS['controlling']], 'redraw') == pos:
		gfx.refresh_view('map')
Exemple #16
0
def death():
	_player = LIFE[SETTINGS['controlling']]
	
	maps.reset_lights()
	FADE_TO_WHITE[0] += .5
	
	_time_since_death = FADE_TO_WHITE[0]
	_time_alive = round(numbers.clip((_player['time_of_death']-_player['created'])/float(WORLD_INFO['length_of_day']), 0.1, 9999), 2)
	_string = 'You die.'
	_sub_string = _player['cause_of_death']
	_col = int(round(255*numbers.clip((_time_since_death/100.0)-random.uniform(0, 0.15), 0, 1)))
	
	
	if _time_alive == 1:
		_sub_sub_string = 'Lived 1 day'
	else:
		if _time_alive < 1:
			_sub_sub_string = 'Lived less than a day'
		else:
			_sub_sub_string = 'Lived %0.1f days' % (_time_alive)
	
	gfx.fade_to_black(1)	
	
	gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_string)/2,
	                MAP_WINDOW_SIZE[1]/2,
	                _string,
	                'map',
	                fore_color=tcod.Color(_col, 0, 0),
	                back_color=tcod.Color(0, 0, 0))
	
	gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_sub_string)/2,
	                (MAP_WINDOW_SIZE[1]/2)+2,
	                _sub_string,
	                'map',
	                fore_color=tcod.Color(int(round(_col*.75)), int(round(_col*.75)), int(round(_col*.75))),
	                back_color=tcod.Color(0, 0, 0))
	
	gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_sub_sub_string)/2,
	                (MAP_WINDOW_SIZE[1]/2)+4,
	                _sub_sub_string,
	                'map',
	                fore_color=tcod.Color(int(round(_col*.75)), int(round(_col*.75)), int(round(_col*.75))),
	                back_color=tcod.Color(0, 0, 0))
	
	if _time_since_death>=350:
		worldgen.save_world()
		worldgen.reset_world()

		gfx.clear_scene()
		
		SETTINGS['running'] = 1
		return False
	
	return True
Exemple #17
0
def position_is_in_frame(pos):
	_view = get_active_view()
	
	if not _view:
		return False
	
	if pos[0] >= CAMERA_POS[0] and pos[0] < numbers.clip(CAMERA_POS[0]+_view['view_size'][0]-1, 0, MAP_SIZE[0]) and \
	   pos[1] >= CAMERA_POS[1] and pos[1] < numbers.clip(CAMERA_POS[1]+_view['view_size'][1]-1, 0, MAP_SIZE[1]):
		return True
	
	return False
Exemple #18
0
def position_is_in_frame(pos):
    _view = get_active_view()

    if not _view:
        return False

    if pos[0] >= CAMERA_POS[0] and pos[0] < numbers.clip(CAMERA_POS[0]+_view['view_size'][0]-1, 0, MAP_SIZE[0]) and \
       pos[1] >= CAMERA_POS[1] and pos[1] < numbers.clip(CAMERA_POS[1]+_view['view_size'][1]-1, 0, MAP_SIZE[1]):
        return True

    return False
Exemple #19
0
def is_confident(life):
	if 'player' in life:
		return False
	
	_friendly_confidence = judgement.get_ranged_combat_rating_of_target(life, life['id'])
	_threat_confidence = 0
	
	for target_id in judgement.get_trusted(life, visible=False):
		_knows = brain.knows_alife_by_id(life, target_id)
		
		if _knows['dead'] or _knows['asleep']:
			continue
		
		if _knows['last_seen_time']>30:
			if brain.get_alife_flag(life, target_id, 'threat_score'):
				_recent_mod = 1-(numbers.clip(_knows['last_seen_time'], 0, 300)/300.0)
				_score = brain.get_alife_flag(life, target_id, 'threat_score')
				_friendly_confidence += _score*_recent_mod
			else:
				_friendly_confidence += 1
		else:
			_score = judgement.get_ranged_combat_rating_of_target(life, target_id)
			
			brain.flag_alife(life, target_id, 'threat_score', value=_score)
			
			_friendly_confidence += _score
	
	for target_id in judgement.get_threats(life, ignore_escaped=False):
		_knows = brain.knows_alife_by_id(life, target_id)
		
		if _knows['dead'] or _knows['asleep']:
			continue
		
		if _knows['last_seen_time']:
			if brain.get_alife_flag(life, target_id, 'threat_score'):
				if _knows['last_seen_time']>50:
					_recent_mod = 1-(numbers.clip(_knows['last_seen_time'], 0, 600)/600.0)
				else:
					_recent_mod = 1
				
				_score = brain.get_alife_flag(life, target_id, 'threat_score')
				_threat_confidence += _score*_recent_mod
			else:
				_threat_confidence += 1
		else:
			_score = judgement.get_ranged_combat_rating_of_target(life, target_id, inventory_check=False)
			
			brain.flag_alife(life, target_id, 'threat_score', value=_score)
			
			_threat_confidence += _score
	
	return _friendly_confidence-_threat_confidence>=-2
Exemple #20
0
def get_vision(life):
	if not 'CAN_SEE' in life['life_flags']:
		return 0
	
	if 'player' in life:
		_fov_mod = 1
	else:
		_fov_mod = numbers.clip(1-(life['think_rate']/float(life['think_rate_max'])), 0.5, 1)
	
	_world_light = tcod.white-weather.get_lighting()
	_light_percentage = numbers.clip(((_world_light.r+_world_light.g+_world_light.b)*.30)/200.0, 0, 1)
	
	return int(round((life['vision_max']*_light_percentage)*_fov_mod))
Exemple #21
0
def move_camera(pos, scroll=False):
    _orig_pos = CAMERA_POS[:]
    CAMERA_POS[0] = numbers.clip(pos[0] - (MAP_WINDOW_SIZE[0] / 2), 0, MAP_SIZE[0] - MAP_WINDOW_SIZE[0])
    CAMERA_POS[1] = numbers.clip(pos[1] - (MAP_WINDOW_SIZE[1] / 2), 0, MAP_SIZE[1] - MAP_WINDOW_SIZE[1])
    CAMERA_POS[2] = pos[2]

    if not _orig_pos == CAMERA_POS:
        gfx.refresh_view("map")
    elif SETTINGS["controlling"] and not alife.brain.get_flag(LIFE[SETTINGS["controlling"]], "redraw") == pos:
        gfx.refresh_view("map")

    if SETTINGS["controlling"]:
        alife.brain.flag(LIFE[SETTINGS["controlling"]], "redraw", value=pos[:])
Exemple #22
0
def move_camera(pos, scroll=False):
    _orig_pos = CAMERA_POS[:]
    CAMERA_POS[0] = numbers.clip(pos[0] - (WINDOW_SIZE[0] / 2), 0,
                                 MAP_SIZE[0] - WINDOW_SIZE[0])
    CAMERA_POS[1] = numbers.clip(pos[1] - (WINDOW_SIZE[1] / 2), 0,
                                 MAP_SIZE[1] - WINDOW_SIZE[1])
    CAMERA_POS[2] = pos[2]

    if not _orig_pos == CAMERA_POS:
        gfx.refresh_view('map')
    elif SETTINGS['controlling'] and not alife.brain.get_flag(
            LIFE[SETTINGS['controlling']], 'redraw') == pos:
        gfx.refresh_view('map')
Exemple #23
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
	
	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.stop(life)
		lfe.walk_to(life, _know['last_seen_at'][:2])
	
	if life['path'] or lfe.find_action(life, matches=[{'action': 'move'}]):
		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)):
				_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=True):
			_search_map[_y, _x] = 0
	else:
		_know['escaped'] = 2
Exemple #24
0
def handle_camera(entity_id, min_zoom=3.5, max_zoom=14.5, max_enemy_distance=2400, center_distance=600.0):
	if not entity_id in entities.ENTITIES:
		display.CAMERA['zoom_speed'] = .005
		display.CAMERA['next_zoom'] = 4.5
		
		return False
	
	if not clock.is_ticking():
		return False
	
	_player = entities.get_entity(entity_id)
	_center_pos = _player['position'].copy()
	_median_distance = []
	
	if 'in_space' in _player and _player['in_space']:
		_distance_to_center = numbers.distance(_player['position'], (worlds.get_size()[0]/2, worlds.get_size()[1]/2))
		
		_min_zoom = 2.0
		_max_zoom = max_zoom
		display.CAMERA['next_zoom'] = numbers.clip(_max_zoom*((_distance_to_center/3000.0)-1), _min_zoom, _max_zoom)
	
	elif _player['death_timer'] == -1:
		for enemy_id in entities.get_sprite_groups(['enemies', 'hazards']):
			_enemy = entities.get_entity(enemy_id)
			
			if 'player' in _enemy:
				continue
			
			_dist = numbers.distance(_player['position'], _enemy['position'])
			if _dist>=max_enemy_distance:
				continue
			
			_median_distance.append(_dist)
			_center_pos = numbers.interp_velocity(_center_pos, _enemy['position'], 0.5)
		
		if not _median_distance:
			_median_distance = [0]
		
		_distance_to_nearest_enemy = sum(_median_distance)/len(_median_distance)
		_min_zoom = min_zoom
		_max_zoom = max_zoom
		display.CAMERA['next_zoom'] = numbers.clip(_max_zoom*(_distance_to_nearest_enemy/float(center_distance)), _min_zoom, _max_zoom)
	else:
		display.CAMERA['zoom_speed'] = .05
		display.CAMERA['next_zoom'] = 1.5
	
	if display.CAMERA['next_zoom'] < 5:
		display.CAMERA['next_center_on'] = _center_pos
	else:
		display.CAMERA['next_center_on'] = _player['position'].copy()
Exemple #25
0
def loop():
	_remove_labels = []
	
	for label in LABELS.values():
		if time.time()-label.time_created > label.show_for and not label.show_for == -1:
			if label.color[3]>0:
				label.color = (label.color[0], label.color[1], label.color[2], numbers.clip(label.color[3]-label.fade_out_speed, 0, 255))
			else:
				_remove_labels.append(label)
		else:
			if label.color[3] < 255:
				label.color = (label.color[0], label.color[1], label.color[2], numbers.clip(label.color[3]+label.fade_in_speed, 0, 255))
	
	for label in _remove_labels:
		del LABELS[label._id]
Exemple #26
0
def hit_laser(bullet, target_id):
	for i in range(random.randint(2, 3)):
		_effect = effects.create_particle(bullet['position'][0]+random.randint(-6, 6),
		                                  bullet['position'][1]+random.randint(-6, 6),
		                                  'explosion.png',
		                                  background=False,
		                                  scale=random.uniform(.4, .8),
		                                  flashes=random.randint(15, 25),
		                                  flash_chance=0.7)
		
		_effect['velocity'] = numbers.interp_velocity(bullet['velocity'], entities.get_entity(target_id)['velocity'], .1)
		_effect['velocity'][0] = numbers.clip(_effect['velocity'][0], -6, 6)
		_effect['velocity'][1] = numbers.clip(_effect['velocity'][1], -6, 6)
	
	entities.trigger_event(entities.get_entity(target_id), 'accelerate', velocity=numbers.interp_velocity(entities.get_entity(target_id)['velocity'], bullet['velocity'], .4))
Exemple #27
0
def reload_slices():
	for _slice in WORLD_INFO['slices'].values():
		#logging.debug('Loading slice: %s' % _slice['id'])
		
		_size = [_slice['bot_right'][0]-_slice['top_left'][0], _slice['bot_right'][1]-_slice['top_left'][1]]		
		_size[0] = numbers.clip(_size[0], 1, MAP_SIZE[0])
		_size[1] = numbers.clip(_size[1], 1, MAP_SIZE[1])
			
		_slice['_map'] = zones.create_map_array(size=_size)
		
		for pos in _slice['map']:
			_xx = _slice['top_left'][0]+1
			_yy = _slice['top_left'][1]+1
			
			_slice['_map'][pos[0]-_xx][pos[1]-_yy] = 1
Exemple #28
0
def create_gib(life, icon, size, limb, velocity, color=(tcod.white, None)):
	_gib = {'name': 'gib',
		'prefix': 'a',
		'type': 'magazine',
		'icon': icon,
		'flags': ['BLOODY'],
		'description': '%s\'s %s.' % (' '.join(life['name']), limb),
		'size': '%sx1' % size,
		'material': 'flesh',
		'thickness': size,
		'color': color}
	
	_i = items.get_item_from_uid(items.create_item('gib', position=life['pos'][:], item=_gib))
	_i['velocity'] = [numbers.clip(velocity[0], -3, 3), numbers.clip(velocity[1], -3, 3), velocity[2]]
	
	logging.debug('Created gib.')
Exemple #29
0
def draw_vapor(pos, vapor):
    gfx.tint_tile(
        pos[0], pos[1], vapor['color'],
        numbers.clip(
            vapor['max_intensity'] *
            (1 - (vapor['age'] / float(vapor['age_max']))), 0,
            vapor['max_intensity']))
Exemple #30
0
def draw_dijkstra(dijkstra,path=None):
	for _y in range(dijkstra['y_range'][0],dijkstra['y_range'][1]):
		y = _y-dijkstra['y_range'][0]
		
		for _x in range(dijkstra['x_range'][0],dijkstra['x_range'][1]):
			x = _x-dijkstra['x_range'][0]
			
			if not path:
				if (_x,_y) in dijkstra['ignore']:
					print '# ',
					continue
				#else:
				#	print '.',
				_n = str(numbers.clip(abs(int(dijkstra['map'][y,x])),0,41))
				
				if len(_n)==1:
					print '%s ' % _n,
				else:
					print _n,
			else:
				#print path
				if (_x,_y,0) in path:
					print 'o',
				elif (_x,_y) in dijkstra['ignore']:
					print '#',
				else:
					print ' ',
		print
Exemple #31
0
def understand(life):
	if SETTINGS['controlling']:
		_dist_to_player = numbers.distance(life['pos'], LIFE[SETTINGS['controlling']]['pos'])
		if _dist_to_player < 100:
			if life['think_rate_max']>=30:
				if _dist_to_player < 75:
					life['think_rate_max'] = 1
					life['online'] = True
					logging.debug('[Agent] %s brought online (Reason: Near viewer)' % ' '.join(life['name']))
				
			else:
				life['think_rate_max'] = 1
		else:
			if _dist_to_player >= OFFLINE_ALIFE_DISTANCE and life['online']:
				life['online'] = False
				logging.debug('[Agent] %s went offline (Reason: Away from viewer)' % ' '.join(life['name']))
			elif life['think_rate_max']<30:
				if _dist_to_player < OFFLINE_ALIFE_DISTANCE:
					life['online'] = True
				
				logging.debug('[Agent] %s went passive (Reason: Away from viewer)' % ' '.join(life['name']))
			
			life['think_rate_max'] = numbers.clip(15*(((_dist_to_player-100)+30)/30), 30, 60)
	else:
		life['think_rate_max'] = 5
	
	if not life['online'] or life['asleep']:
		return False
	
	if len(life['actions'])-len(lfe.find_action(life, matches=[{'action': 'move'}, {'action': 'dijkstra_move'}]))>0:
		lfe.clear_actions(life)
		life['path'] = []
		
		return False
	
	if life['think_rate']>0:
		life['think_rate'] -= 1
		
		return False
	
	for module in CONSTANT_MODULES:
		module.setup(life)
	
	life['think_rate'] = life['think_rate_max']
	
	#if life['name'][0].startswith('Tim'):
	#	_goal, _tier, _plan = planner.get_next_goal(life, debug='attack')
	#else:
	_goal, _tier, _plan = planner.get_next_goal(life)
	
	if _goal:
		lfe.change_goal(life, _goal, _tier, _plan)
	else:
		lfe.change_goal(life, 'idle', TIER_RELAXED, [])
		#logging.error('%s has no possible goal.' % ' '.join(life['name']))
		
		return False
	
	planner.think(life)
	
Exemple #32
0
def broadcast(messages, event_time, glitch=False):
    _time = WORLD_INFO['ticks'] + event_time
    _i = 0

    for entry in messages:
        if 'source' in entry:
            _source = entry['source']
        else:
            _source = '???'

        if glitch:
            if 'change_only' in entry:
                _change = entry['change_only']
            else:
                _change = False

            _delay = (50 *
                      numbers.clip(_i, 0, 1)) + (len(entry['text']) * 2) * _i

            WORLD_INFO['scheme'].append({
                'glitch': entry['text'],
                'change': _change,
                'time': _time + _delay
            })
        else:
            WORLD_INFO['scheme'].append({
                'radio': [_source, entry['text']],
                'time': _time
            })

        _time += int(round(len(entry['text']) * 1.25))
        _i += 1
Exemple #33
0
def get_engage_distance(life):
	_weapons = get_equipped_weapons(life)
	
	if _weapons:
		return numbers.clip(int(round(ITEMS[_weapons[0]]['accuracy']*27)), 3, sight.get_vision(life))
	else:
		return sight.get_vision(life)/2
Exemple #34
0
def draw_dijkstra(dijkstra, path=None):
    for _y in range(dijkstra['y_range'][0], dijkstra['y_range'][1]):
        y = _y - dijkstra['y_range'][0]

        for _x in range(dijkstra['x_range'][0], dijkstra['x_range'][1]):
            x = _x - dijkstra['x_range'][0]

            if not path:
                if (_x, _y) in dijkstra['ignore']:
                    print '# ',
                    continue
                #else:
                #	print '.',
                _n = str(numbers.clip(abs(int(dijkstra['map'][y, x])), 0, 41))

                if len(_n) == 1:
                    print '%s ' % _n,
                else:
                    print _n,
            else:
                #print path
                if (_x, _y, 0) in path:
                    print 'o',
                elif (_x, _y) in dijkstra['ignore']:
                    print '#',
                else:
                    print ' ',
        print
Exemple #35
0
def generate_los(life, target, at, source_map, score_callback, invert=False, ignore_starting=False):
	_stime = time.time()
	_cover = {'pos': None,'score': 9000}
	
	_x = numbers.clip(at[0]-(SETTINGS['los']/2),0,MAP_SIZE[0]-(SETTINGS['los']/2))
	_y = numbers.clip(at[1]-(SETTINGS['los']/2),0,MAP_SIZE[1]-(SETTINGS['los']/2))
	_top_left = (_x,_y,at[2])
	
	target_los = render_fast_los.render_fast_los(at,
		SETTINGS['los'],
		source_map)
	
	for pos in render_los.draw_circle(life['pos'][0],life['pos'][1],30):
		x = pos[0]-_top_left[0]
		y = pos[1]-_top_left[1]
		
		if pos[0]<0 or pos[1]<0 or pos[0]>=MAP_SIZE[0] or pos[1]>=MAP_SIZE[0]:
			continue
		
		if x<0 or y<0 or x>=target_los.shape[1] or y>=target_los.shape[0]:
			continue
		
		if life['pos'][0]-_top_left[0]>=target_los.shape[1] or life['pos'][1]-_top_left[1]>=target_los.shape[0]:
			continue
		
		if target_los[life['pos'][1]-_top_left[1],life['pos'][0]-_top_left[0]]==invert and not ignore_starting:
			_cover['pos'] = life['pos'][:]
			return False
		
		if source_map[pos[0]][pos[1]][at[2]+1] or source_map[pos[0]][pos[1]][at[2]+2]:
			continue
		
		if target_los[y,x] == invert:
			#TODO: Additional scores, like distance from target
			_score = score_callback(life, target, pos)
			
			if _score<_cover['score']:
				_cover['score'] = _score
				_cover['pos'] = list(pos)
	
	#print time.time()-_stime
	if not _cover['pos']:
		print 'Nowhere to hide', target['life']['name'], _top_left
				
		return False
	
	return _cover
Exemple #36
0
def clear(*args):
	console_rect(0,0,0,WINDOW_SIZE[0],WINDOW_SIZE[1],True,flag=BKGND_DEFAULT)
	_c = random.choice([tcod.sepia, tcod.brass, tcod.gray])
	
	for y in range(WINDOW_SIZE[1]):
		for x in range(WINDOW_SIZE[0]):
			if not time.time()%0.1:
				continue
			
			_mod = random.randint(0, 10)
			tcod.console_put_char_ex(0, x, y, chr(random.randint(0, 125)),
			                         tcod.Color(numbers.clip(_c.r+_mod, 0, 255),
			                                    numbers.clip(_c.g+_mod, 0, 255),
			                                    numbers.clip(_c.b+_mod, 0, 255)),
			                         tcod.Color(_c.r+_mod, _c.g+_mod, _c.b+_mod))
	
	console_flush()
Exemple #37
0
def parse_raw_judgements(life, target_id):
	lfe.execute_raw(life, 'judge', 'trust', break_on_false=False, life_id=target_id)
	
	if lfe.execute_raw(life, 'judge', 'break_trust', life_id=target_id):
		brain.knows_alife_by_id(life, target_id)['trust'] = numbers.clip(brain.knows_alife_by_id(life, target_id)['trust'], -1000, -1)
		return True
	
	return False
Exemple #38
0
def get_tension_with(life, life_id):
    _target = brain.knows_alife_by_id(life, life_id)

    if _target["alignment"] in ["trust"] or not _target["last_seen_at"]:
        return 0

    if not _target["last_seen_time"] and _target["dead"]:
        return 0

    _distance = numbers.clip(numbers.distance(life["pos"], _target["last_seen_at"]), 0, sight.get_vision(life))
    _tension = get_ranged_combat_rating_of_target(life, life_id) / float(get_ranged_combat_rating_of_self(life))

    return (
        abs(((sight.get_vision(life) - _distance) / float(sight.get_vision(life))) * _tension)
        * (100 - numbers.clip(_target["last_seen_time"], 0, 100))
        / 100.0
    )
Exemple #39
0
def draw_dialog(dialog_id):
	_dialog = get_dialog(dialog_id)
	_last_message = get_last_message(dialog_id)
	_x = numbers.clip(MAP_WINDOW_SIZE[0]/2-len(_last_message['text'])/2, 3, 100)
	_y = 10
	_line_of_sight = drawing.diag_line(LIFE[_dialog['started_by']]['pos'], LIFE[_dialog['target']]['pos'])
	
	locks.unlock('camera_free')
	
	if len(_line_of_sight)<=1:
		_center_pos = LIFE[_dialog['started_by']]['pos']
	else:
		_center_pos = list(_line_of_sight[len(_line_of_sight)/2])
		_center_pos.append(2)
	
	if SETTINGS['controlling'] == _dialog['started_by']:
		_target = _dialog['target']
	else:
		_target = _dialog['started_by']
	
	_target_portrait = lfe.draw_life_icon(LIFE[_target])
	_lines = []
	                                   
	gfx.camera_track(_center_pos)
	gfx.blit_string(_x-2, _y-2, ' '.join(LIFE[_target]['name']), 'overlay', fore_color=_target_portrait[1])
	gfx.blit_string(_x-2, _y, _target_portrait[0], 'overlay', fore_color=_target_portrait[1])#, back_color=tcod.darkest_gray)
	
	_text = _last_message['text']
	_y_mod = 0
	while _text:
		_x = MAP_WINDOW_SIZE[0]/2-len(_text[:MAP_WINDOW_SIZE[0]-4])/2
		
		gfx.blit_string(_x, _y+_y_mod, _text[:MAP_WINDOW_SIZE[0]-4], 'overlay')
		_text = _text[MAP_WINDOW_SIZE[0]-4:]
		_y_mod += 1
	
	for choice in _dialog['choices']:
		_text = choice['text'][choice['text'].index('\"')+1:choice['text'].index('\"')-1]
		
		if not _text.startswith('>'):
			_text = '> '+_text
		
		_n_x = MAP_WINDOW_SIZE[0]/2-len(_text)/2
		
		if _n_x < _x:
			_x = _n_x
	
	for choice in _dialog['choices']:
		_text = choice['text'][choice['text'].index('\"')+1:choice['text'].index('\"')-1]
		
		if _dialog['cursor_index'] == _dialog['choices'].index(choice):
			_text = '> '+_text
		
		_lines.append(_text)
	
	for line in _lines:
		gfx.blit_string(_x, _y+3, line, 'overlay')#, back_color=tcod.darkest_gray)
		_y += 2
Exemple #40
0
def parse_raw_judgements(life, target_id):
    lfe.execute_raw(life, "judge", "trust", break_on_false=False, life_id=target_id)

    if lfe.execute_raw(life, "judge", "break_trust", life_id=target_id):
        brain.knows_alife_by_id(life, target_id)["trust"] = numbers.clip(
            brain.knows_alife_by_id(life, target_id)["trust"], -1000, -1
        )
        return True

    return False
Exemple #41
0
def evaluate_overwatch_mood():
	_stats = WORLD_INFO['overwatch']
	_hardship = get_overwatch_hardship(no_mod=True)
	_success = get_overwatch_success()
	
	_hardship_rate = _hardship/10.0
	_success_rate = _success/10.0
	
	_activity = _stats['last_updated']/float(WORLD_INFO['ticks'])
	_difficulty = numbers.clip(_hardship_rate-_success_rate, 0.0, 1.0)
	
	#print _activity, numbers.clip(_success_rate, 0.3, 0.85)
	
	if _activity>numbers.clip(_success_rate, 0.3, 0.85):
		_stats['mood'] = 'rest'
	elif _success_rate<.3:
		_stats['mood'] = 'help'
	elif _success_rate>_hardship_rate:
		_stats['mood'] = 'intrigue'
	else:
		_stats['mood'] = 'idle'
Exemple #42
0
def get_tension_with(life, life_id):
	_target = brain.knows_alife_by_id(life, life_id)
	
	if _target['alignment'] in ['trust', 'feign_trust'] or not _target['last_seen_at']:
		return 0
	
	if not _target['last_seen_time'] and _target['dead']:
		return 0
	
	_distance = numbers.clip(numbers.distance(life['pos'], _target['last_seen_at']), 0, sight.get_vision(life))
	_tension = get_ranged_combat_rating_of_target(life, life_id)/float(get_ranged_combat_rating_of_self(life))
	
	return abs(((sight.get_vision(life)-_distance)/float(sight.get_vision(life)))*_tension)*(100-numbers.clip(_target['last_seen_time'], 0, 100))/100.0
Exemple #43
0
def get_overwatch_success():
	_stats = WORLD_INFO['overwatch']
	_situation = get_player_situation()
	
	if not _situation:
		return 0
	
	#TODO: Check ammo
	_success = len(_situation['weapons'])
	_success += _stats['intervention']
	#_success += len(_situation['equipped_gear'])
	
	return numbers.clip(float(_success), 0.0, 10.0)
Exemple #44
0
def create_gib(life, icon, size, limb, velocity, color=(tcod.white, None)):
    _gib = {
        'name': 'gib',
        'prefix': 'a',
        'type': 'magazine',
        'icon': icon,
        'flags': ['BLOODY'],
        'description': '%s\'s %s.' % (' '.join(life['name']), limb),
        'size': '%sx1' % size,
        'material': 'flesh',
        'thickness': size,
        'color': color
    }

    _i = items.get_item_from_uid(
        items.create_item('gib', position=life['pos'][:], item=_gib))
    _i['velocity'] = [
        numbers.clip(velocity[0], -3, 3),
        numbers.clip(velocity[1], -3, 3), velocity[2]
    ]

    logging.debug('Created gib.')
Exemple #45
0
def create_effects(item, pos, real_z_pos, z_min):
	for _z in range(0, 2):
		_z_level = numbers.clip(z_min-_z, 0, maputils.get_map_size(WORLD_INFO['map'])[2]-1)
		
		if WORLD_INFO['map'][pos[0]][pos[1]][_z_level]:
			if int(round(real_z_pos))-_z_level<=2:
				if 'BLOODY' in item['flags']:
					if random.randint(0,50)<=35:
						effects.create_splatter('blood', [pos[0]+random.randint(-2, 2), pos[1]+random.randint(-2, 2), _z_level])
				
				if 'SMOKING' in item['flags']:
					if random.randint(0, 50)<=25:
						effects.create_smoke_streamer([pos[0]+random.randint(-item['size'], item['size']), pos[1]+random.randint(-item['size'], item['size']), _z_level],
						                              item['size']/2,
						                              random.randint(item['size']*2, (item['size']*2)+5))
				if 'BURNING' in item['flags']:
					if random.randint(0, 50)<=25:
						effects.create_smoke_cloud([pos[0]+random.randint(-item['size'], item['size']), pos[1]+random.randint(-item['size'], item['size']), _z_level],
						                              random.randint(item['size'], (item['size'])+3),
						                              color=tcod.light_crimson)
				if 'max_speed' in item and is_moving(item):
					effects.create_vapor(item['pos'], 5, numbers.clip(item['speed']/20, 0, 1))
Exemple #46
0
def get_vision(life):
    if not 'CAN_SEE' in life['life_flags']:
        return 0

    #if 'player' in life:
    _fov_mod = 1
    #else:
    #	_fov_mod = numbers.clip(1-(life['think_rate']/float(life['think_rate_max'])), 0.5, 1)

    _world_light = tcod.white - weather.get_lighting()
    _light_percentage = numbers.clip(
        ((_world_light.r + _world_light.g + _world_light.b) * .30) / 200.0, 0,
        1)

    return int(round((life['vision_max'] * _light_percentage) * _fov_mod))
Exemple #47
0
def create_ash(pos):
    _color = random.randint(0, 25)
    _intensity = numbers.clip(_color / float(25), .3, 1)

    _effect = {
        'type': 'ash',
        'color': tcod.Color(_color, _color, _color),
        'intensity': _intensity,
        'pos': list(pos),
        'callback': lambda x: 1 == 1,
        'draw_callback': draw_ash,
        'unregister_callback': lambda ash: unregister_effect(ash)
    }

    register_effect(_effect)
Exemple #48
0
def create_search_map(life, pos, size):
	_map = numpy.ones((size, size))
	
	_x_top_left = numbers.clip(pos[0]-(size/2), 0, MAP_SIZE[0])
	_y_top_left = numbers.clip(pos[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 is_solid((_x, _y, pos[2])) or is_solid((_x, _y, pos[2]+1)):
				_map[y, x] = 0
			else:
				_map[y, x] = alife.judgement.judge_search_pos(life, (_x, _y))
	
	return _map
Exemple #49
0
def clear(*args):
    console_rect(0,
                 0,
                 0,
                 WINDOW_SIZE[0],
                 WINDOW_SIZE[1],
                 True,
                 flag=BKGND_DEFAULT)
    _c = random.choice([tcod.sepia, tcod.brass, tcod.gray])

    for y in range(WINDOW_SIZE[1]):
        for x in range(WINDOW_SIZE[0]):
            if not time.time() % 0.1:
                continue

            _mod = random.randint(0, 10)
            tcod.console_put_char_ex(
                0, x, y, chr(random.randint(0, 125)),
                tcod.Color(numbers.clip(_c.r + _mod, 0, 255),
                           numbers.clip(_c.g + _mod, 0, 255),
                           numbers.clip(_c.b + _mod, 0, 255)),
                tcod.Color(_c.r + _mod, _c.g + _mod, _c.b + _mod))

    console_flush()
Exemple #50
0
def generate_effects(size):
	_current_weather = WORLD_INFO['real_time_of_day']/(WORLD_INFO['length_of_day']/len(WORLD_INFO['weather']['colors']))
	_current_weather = numbers.clip(_current_weather, 0, len(WORLD_INFO['weather']['colors'])-1)
	
	if 'raining' in WORLD_INFO['weather']['colors'][_current_weather]['effects']:
		rain(size)
	
	if 'lightning' in WORLD_INFO['weather']['colors'][_current_weather]['effects'] and not random.randint(0, 200):
		RGB_LIGHT_BUFFER[0] -= 155
		RGB_LIGHT_BUFFER[1] -= 155
		RGB_LIGHT_BUFFER[2] -= 155
		
		RGB_LIGHT_BUFFER[0] = RGB_LIGHT_BUFFER[0].clip(0, 255)
		RGB_LIGHT_BUFFER[1] = RGB_LIGHT_BUFFER[1].clip(0, 255)
		RGB_LIGHT_BUFFER[2] = RGB_LIGHT_BUFFER[2].clip(0, 255)
Exemple #51
0
def _calculate_trust(life, target_id):
	_knows = brain.knows_alife_by_id(life, target_id)
	_hard_trust = 0
	_soft_trust = 0
	
	if life['group'] and groups.is_member(life, life['group'], target_id):
		_hard_trust += 1
	
	for memory in lfe.get_memory(life, matches={'target': target_id, 'trust': '*'}):
		_soft_trust += memory['trust']
	
	_total_trust = _hard_trust+_soft_trust	
	
	if _hard_trust:
		_total_trust = numbers.clip(_total_trust, _hard_trust, 10)
	
	return _total_trust
Exemple #52
0
def create_smoke_cloud(pos,
                       size,
                       color=tcod.gray,
                       age=0,
                       factor_distance=False):
    for new_pos in render_los.draw_circle(pos[0], pos[1], size):
        if not gfx.position_is_in_frame(pos):
            continue

        if not alife.sight._can_see_position(pos, new_pos, distance=False):
            continue

        _age_mod = 1
        if factor_distance:
            _age_mod = 1 - numbers.clip(
                numbers.distance(pos, new_pos) / float(size), 0.1, 1)

        create_smoke(new_pos, color=color, age=age * _age_mod)
Exemple #53
0
def draw_event():
    _event = None

    for event in EVENTS:
        if not event['delay']:
            _event = event
            break

    if not _event:
        return False

    locks.unlock('camera_free')
    gfx.camera_track(_event['pos'])

    if len(event['text']) >= MAP_WINDOW_SIZE[0] - 1:
        _lines = list(_event['text'].partition(','))

        if not len(_lines[1]):
            _lines = list(_event['text'].partition('.'))

        if len(_lines[1]):
            _lines.pop(1)
        else:
            lines = ['????']

    else:
        _lines = [_event['text']]

    for line in _lines:
        if len(line) >= MAP_WINDOW_SIZE[0] - 1:
            _lines = ['The most annoying error.']
            break

    _i = 0
    for line in _lines:
        _half = len(line) / 2
        _x = numbers.clip((MAP_WINDOW_SIZE[0] / 2) - _half, 0,
                          MAP_WINDOW_SIZE[0] - len(line) - 1)

        gfx.blit_string(_x, 10 + _i, line, 'overlay')

        _i += 1

    return True
Exemple #54
0
def _refill_feed(life, feed):
	if not lfe.is_holding(life, feed['uid']) and not lfe.can_hold_item(life):
		logging.warning('No hands free to load ammo!')
		
		return False

	if not lfe.get_held_items(life, matches=[{'id': feed['uid']}]) and lfe.item_is_stored(life, feed['uid']) and not lfe.find_action(life, matches=[{'action': 'removeandholditem'}]):
		lfe.add_action(life,{'action': 'removeandholditem',
			'item': feed['uid']},
			200,
			delay=0)
		
		return False

	#TODO: No check for ammo type.
	
	_loading_rounds = len(lfe.find_action(life, matches=[{'action': 'refillammo'}]))
	_bullets_in_inventory = len(lfe.get_all_inventory_items(life, matches=[{'type': 'bullet', 'ammotype': feed['ammotype']}]))
	
	if _loading_rounds:# >= _bullets_in_inventory:
		return False
	
	if len(lfe.find_action(life,matches=[{'action': 'refillammo'}])):
		return False
	
	_rounds = len(feed['rounds'])
	
	if _rounds>=feed['maxrounds'] or (not _bullets_in_inventory and _rounds):
		print 'Full?'
		return True
	
	_ammo_count = len(lfe.get_all_inventory_items(life,matches=[{'type': 'bullet', 'ammotype': feed['ammotype']}]))
	_ammo_count += len(feed['rounds'])
	_rounds_to_load = numbers.clip(_ammo_count,0,feed['maxrounds'])
	for ammo in lfe.get_all_inventory_items(life,matches=[{'type': 'bullet', 'ammotype': feed['ammotype']}])[:_rounds_to_load]:		
		lfe.add_action(life,{'action': 'refillammo',
			'ammo': feed,
			'round': ammo},
			200,
			delay=3)
		
		_rounds += 1
	
	return False