コード例 #1
0
def get_keyboard_input():
    global KEYBOARD_STRING

    if not KEY.vk:
        return False

    if KEY.c:
        _key = chr(KEY.c)
    else:
        if KEY.pressed:
            if KEY.vk == tcod.KEY_RIGHT:
                INPUT['right'] = True
            elif KEY.vk == tcod.KEY_LEFT:
                INPUT['left'] = True
            elif KEY.vk == tcod.KEY_DOWN:
                INPUT['down'] = True
            elif KEY.vk == tcod.KEY_UP:
                INPUT['up'] = True

        return True

    if SETTINGS['draw console']:
        if KEY.vk == tcod.KEY_ENTER and len(KEYBOARD_STRING[0]):
            #Taken from: http://stackoverflow.com/a/3906309
            old_stdout = sys.stdout
            redirected_output = sys.stdout = StringIO()
            exec(scripting.parse_console(KEYBOARD_STRING[0].rstrip()))
            sys.stdout = old_stdout

            gfx.log('>' + KEYBOARD_STRING[0].rstrip())
            gfx.log(' ' + redirected_output.getvalue())

            KEYBOARD_STRING[0] = ''

        elif KEY.vk == tcod.KEY_BACKSPACE:
            KEYBOARD_STRING[0] = KEYBOARD_STRING[0][:len(KEYBOARD_STRING[0]) -
                                                    1]

    if not ACTIVE_MENU['menu'] == -1:
        _item = menus.is_getting_input(ACTIVE_MENU['menu'])
        if _item and KEY.pressed:
            _item['values'][0] += _key

    if not INPUT.has_key(_key):
        INPUT[_key] = False

    if not INPUT[_key] and KEY.pressed:
        if SETTINGS['draw console']:
            KEYBOARD_STRING[0] += _key

        INPUT[_key] = True
    else:
        #if INPUT[_key]:
        #	#TODO: A 'true' release...?
        #	pass

        INPUT[_key] = False
コード例 #2
0
ファイル: inputs.py プロジェクト: athros/Reactor-3
def get_keyboard_input():
	global KEYBOARD_STRING
	
	if not KEY.vk:
		return False

	if KEY.c:
		_key = chr(KEY.c)
	else:
		if KEY.pressed:
			if KEY.vk == tcod.KEY_RIGHT:
				INPUT['right'] = True
			elif KEY.vk == tcod.KEY_LEFT:
				INPUT['left'] = True
			elif KEY.vk == tcod.KEY_DOWN:
				INPUT['down'] = True
			elif KEY.vk == tcod.KEY_UP:
				INPUT['up'] = True
		
		return True
	
	if SETTINGS['draw console']:
		if KEY.vk == tcod.KEY_ENTER and len(KEYBOARD_STRING[0]):
			#Taken from: http://stackoverflow.com/a/3906309
			old_stdout = sys.stdout
			redirected_output = sys.stdout = StringIO()
			exec(scripting.parse_console(KEYBOARD_STRING[0].rstrip()))
			sys.stdout = old_stdout
			
			gfx.log('>'+KEYBOARD_STRING[0].rstrip())
			gfx.log(' '+redirected_output.getvalue())
			
			KEYBOARD_STRING[0] = ''
			
		elif KEY.vk == tcod.KEY_BACKSPACE:
			KEYBOARD_STRING[0] = KEYBOARD_STRING[0][:len(KEYBOARD_STRING[0])-1]
	
	if not ACTIVE_MENU['menu'] == -1:
		_item = menus.is_getting_input(ACTIVE_MENU['menu'])
		if _item and KEY.pressed:
			_item['values'][0] += _key
	
	if not INPUT.has_key(_key):
		INPUT[_key] = False
	
	if not INPUT[_key] and KEY.pressed:
		if SETTINGS['draw console']:
			KEYBOARD_STRING[0] += _key
		
		INPUT[_key] = True
	else:
		#if INPUT[_key]:
		#	#TODO: A 'true' release...?
		#	pass
		
		INPUT[_key] = False
コード例 #3
0
def load_map(map_name, base_dir=MAP_DIR, cache_map=False):
    _map_dir = os.path.join(base_dir, map_name)

    WORLD_INFO['map'] = []

    with open(os.path.join(_map_dir, 'world.meta'), 'r') as _map_file:
        for line in _map_file.readlines():
            line = line.rstrip()
            value = line.split(':')

            if line.startswith('chunk'):
                WORLD_INFO['chunk_map'][value[1]] = json.loads(':'.join(
                    value[2:]))
            #elif line.startswith('slice_map'):
            #	WORLD_INFO['slice_map'] = json.loads(':'.join(value[1:]))
            elif line.startswith('slice'):
                WORLD_INFO['slices'][value[1]] = json.loads(':'.join(
                    value[2:]))
            elif line.startswith('world_info'):
                WORLD_INFO.update(json.loads(':'.join(value[1:])))

        if 'items' in WORLD_INFO:
            ITEMS.update(WORLD_INFO['items'])

        MAP_SIZE[0] = WORLD_INFO['map_size'][0]
        MAP_SIZE[1] = WORLD_INFO['map_size'][1]
        MAP_SIZE[2] = WORLD_INFO['map_size'][2]

        WORLD_INFO['chunk_map'].update(WORLD_INFO['chunk_map'])

        if WORLD_INFO['weather']:
            weather.create_light_map(WORLD_INFO['weather'])

    logging.debug('Caching zones...')
    zones.cache_zones()
    logging.debug('Done!')

    logging.debug('Creating position maps...')
    create_position_maps()
    logging.debug('Done!')

    logging.debug('Reloading references...')
    reload_reference_maps()
    logging.debug('Done!')

    WORLD_INFO['map'] = create_map(blank=True)
    SETTINGS['base_dir'] = _map_dir

    if cache_map:
        cache_all_clusters()

    logging.info('Map \'%s\' loaded.' % map_name)
    gfx.log('Map \'%s\' loaded.' % map_name)
コード例 #4
0
ファイル: maps.py プロジェクト: athros/Reactor-3
def load_map(map_name, base_dir=MAP_DIR, cache_map=False):
	_map_dir = os.path.join(base_dir, map_name)

	WORLD_INFO['map'] = []

	with open(os.path.join(_map_dir, 'world.meta'),'r') as _map_file:
		for line in _map_file.readlines():
			line = line.rstrip()
			value = line.split(':')
			
			if line.startswith('chunk'):
				WORLD_INFO['chunk_map'][value[1]] = json.loads(':'.join(value[2:]))
			#elif line.startswith('slice_map'):
			#	WORLD_INFO['slice_map'] = json.loads(':'.join(value[1:]))
			elif line.startswith('slice'):
				WORLD_INFO['slices'][value[1]] = json.loads(':'.join(value[2:]))
			elif line.startswith('world_info'):
				WORLD_INFO.update(json.loads(':'.join(value[1:])))
		
		if 'items' in WORLD_INFO:
			ITEMS.update(WORLD_INFO['items'])
		
		MAP_SIZE[0] = WORLD_INFO['map_size'][0]
		MAP_SIZE[1] = WORLD_INFO['map_size'][1]
		MAP_SIZE[2] = WORLD_INFO['map_size'][2]
		
		WORLD_INFO['chunk_map'].update(WORLD_INFO['chunk_map'])
		
		if WORLD_INFO['weather']:
			weather.create_light_map(WORLD_INFO['weather'])
	
	logging.debug('Caching zones...')
	zones.cache_zones()
	logging.debug('Done!')
	
	logging.debug('Creating position maps...')
	create_position_maps()
	logging.debug('Done!')
	
	logging.debug('Reloading references...')
	reload_reference_maps()
	logging.debug('Done!')
	
	WORLD_INFO['map'] = create_map(blank=True)
	SETTINGS['base_dir'] = _map_dir
	
	if cache_map:
		cache_all_clusters()
	
	logging.info('Map \'%s\' loaded.' % map_name)
	gfx.log('Map \'%s\' loaded.' % map_name)
コード例 #5
0
ファイル: reactor-3.py プロジェクト: penny64/Reactor-3
                '[Cython] Run \'python compile_cython_modules.py build_ext --inplace\''
            )
            sys.exit(1)

    except ImportError, e:
        CYTHON_ENABLED = False
        logging.warning('[Cython] ImportError with module: %s' % e)
        logging.warning(
            '[Cython] Certain functions can run faster if compiled with Cython.'
        )
        logging.warning(
            '[Cython] Run \'python compile_cython_modules.py build_ext --inplace\''
        )

    logging.info(WINDOW_TITLE)
    gfx.log(WINDOW_TITLE)

    if os.path.exists('git-version.txt'):
        with open('git-version.txt', 'r') as ver:
            logging.info('Build %s' % ver.readline().strip())

    logging.debug('Renderer: %s' % tcod.sys_get_renderer())

    tiles.create_all_tiles()
    language.load_strings()
    missions.load_all_missions()
    alife.rawparse.create_function_map()
    locks.create_lock('camera_free', locked=True)

    gfx.init_libtcod()
    threads.init()
コード例 #6
0
ファイル: reactor-3.py プロジェクト: hovatterz/Reactor-3
        if render_map.VERSION == MAP_RENDER_VERSION:
            CYTHON_ENABLED = True
        else:
            logging.error("[Cython] render_map is out of date!")
            logging.error("[Cython] Run 'python compile_cython_modules.py build_ext --inplace'")
            sys.exit(1)

    except ImportError, e:
        CYTHON_ENABLED = False
        logging.warning("[Cython] ImportError with module: %s" % e)
        logging.warning("[Cython] Certain functions can run faster if compiled with Cython.")
        logging.warning("[Cython] Run 'python compile_cython_modules.py build_ext --inplace'")

    logging.info(WINDOW_TITLE)
    gfx.log(WINDOW_TITLE)

    if os.path.exists("git-version.txt"):
        with open("git-version.txt", "r") as ver:
            logging.info("Build %s" % ver.readline().strip())

    logging.debug("Renderer: %s" % tcod.sys_get_renderer())

    tiles.create_all_tiles()
    language.load_strings()
    alife.rawparse.create_function_map()

    gfx.init_libtcod()
    # smp.init()

    SETTINGS["draw z-levels below"] = True
コード例 #7
0
def save_map(map_name, base_dir=MAP_DIR, only_cached=True):
    _map_dir = os.path.join(base_dir, map_name)

    #if base_dir == DATA_DIR:
    #	_map_dir = os.path.join(_map_dir, map_name)

    try:
        os.makedirs(_map_dir)
    except:
        pass

    for light in WORLD_INFO['lights']:
        if 'los' in light:
            del light['los']

        if 'old_pos' in light:
            del light['old_pos']

    with open(os.path.join(_map_dir, 'world.meta'), 'w') as _map_file:
        try:
            _slices = WORLD_INFO['slices']
            _references = WORLD_INFO['references']
            _chunk_map = WORLD_INFO['chunk_map']
            _map = WORLD_INFO['map']
            _weather_light_map = None

            del WORLD_INFO['slices']
            del WORLD_INFO['chunk_map']
            del WORLD_INFO['references']
            del WORLD_INFO['map']

            WORLD_INFO['map_size'] = maputils.get_map_size(_map)

            if 'light_map' in WORLD_INFO['weather']:
                _weather_light_map = WORLD_INFO['weather']['light_map']

                del WORLD_INFO['weather']['light_map']

            logging.debug('Writing map metadata to disk...')

            _map_file.write('world_info:%s\n' % json.dumps(WORLD_INFO))

            for _slice in _slices.keys():
                if '_map' in _slices[_slice]:
                    del _slices[_slice]['_map']

                _map_file.write('slice:%s:%s\n' %
                                (_slice, json.dumps(_slices[_slice])))

            for _chunk_key in _chunk_map:
                _map_file.write(
                    'chunk:%s:%s\n' %
                    (_chunk_key, json.dumps(_chunk_map[_chunk_key])))

            #_map_file.write('slice_map:%s' % json.dumps(_slice_map))

            WORLD_INFO['slices'] = _slices
            WORLD_INFO['chunk_map'] = _chunk_map
            WORLD_INFO['references'] = _references
            WORLD_INFO['map'] = _map
            #WORLD_INFO['slice_map'] = _slice_map

            if _weather_light_map:
                WORLD_INFO['weather']['light_map'] = _weather_light_map

            #logging.debug('Reloading slices...')
            #reload_slices()
            #logging.debug('Done!')

        except TypeError as e:
            logging.critical('FATAL: Map not JSON serializable.')
            gfx.log(
                'TypeError: Failed to save map (Map not JSON serializable).')

            raise e

    _chunk_cluster_size = WORLD_INFO['chunk_size'] * 10
    _map = WORLD_INFO['map']

    del WORLD_INFO['map']

    if only_cached:
        _cluster_keys = LOADED_CHUNKS
    else:
        _cluster_keys = []

        for y1 in range(0, MAP_SIZE[1], _chunk_cluster_size):
            for x1 in range(0, MAP_SIZE[0], _chunk_cluster_size):
                _cluster_keys.append('%s,%s' % (x1, y1))

    for cluster_key in _cluster_keys:
        _x1 = int(cluster_key.split(',')[0])
        _y1 = int(cluster_key.split(',')[1])

        with open(
                os.path.join(
                    _map_dir,
                    'world_%s.cluster' % cluster_key.replace(',', '_')),
                'w') as _cluster_file:
            for y2 in range(_y1, _y1 + _chunk_cluster_size):
                for x2 in range(_x1, _x1 + _chunk_cluster_size):
                    _cluster_file.write(json.dumps(_map[x2][y2]) + '\n')

    WORLD_INFO['map'] = _map
    SETTINGS['base_dir'] = _map_dir
コード例 #8
0
ファイル: maps.py プロジェクト: athros/Reactor-3
def save_map(map_name, base_dir=MAP_DIR, only_cached=True):
	_map_dir = os.path.join(base_dir, map_name)
	
	#if base_dir == DATA_DIR:
	#	_map_dir = os.path.join(_map_dir, map_name)

	try:
		os.makedirs(_map_dir)
	except:
		pass
		
	for light in WORLD_INFO['lights']:
		if 'los' in light:
			del light['los']
		
		if 'old_pos' in light:
			del light['old_pos']

	with open(os.path.join(_map_dir, 'world.meta'), 'w') as _map_file:
		try:
			_slices = WORLD_INFO['slices']
			_references = WORLD_INFO['references']
			_chunk_map = WORLD_INFO['chunk_map']
			_map = WORLD_INFO['map']
			_weather_light_map = None
			
			del WORLD_INFO['slices']
			del WORLD_INFO['chunk_map']
			del WORLD_INFO['references']
			del WORLD_INFO['map']
			
			WORLD_INFO['map_size'] = maputils.get_map_size(_map)
			
			if 'light_map' in WORLD_INFO['weather']:
				_weather_light_map = WORLD_INFO['weather']['light_map']
				
				del WORLD_INFO['weather']['light_map']
			
			logging.debug('Writing map metadata to disk...')
			
			_map_file.write('world_info:%s\n' % json.dumps(WORLD_INFO))
			
			for _slice in _slices.keys():
				if '_map' in _slices[_slice]:
					del _slices[_slice]['_map']
				
				_map_file.write('slice:%s:%s\n' % (_slice, json.dumps(_slices[_slice])))
			
			for _chunk_key in _chunk_map:
				_map_file.write('chunk:%s:%s\n' % (_chunk_key, json.dumps(_chunk_map[_chunk_key])))
			
			#_map_file.write('slice_map:%s' % json.dumps(_slice_map))
			
			WORLD_INFO['slices'] = _slices
			WORLD_INFO['chunk_map'] = _chunk_map
			WORLD_INFO['references'] = _references
			WORLD_INFO['map'] = _map
			#WORLD_INFO['slice_map'] = _slice_map
			
			if _weather_light_map:
				WORLD_INFO['weather']['light_map'] = _weather_light_map
			
			#logging.debug('Reloading slices...')
			#reload_slices()
			#logging.debug('Done!')
			
		except TypeError as e:
			logging.critical('FATAL: Map not JSON serializable.')
			gfx.log('TypeError: Failed to save map (Map not JSON serializable).')
			
			raise e
		
	_chunk_cluster_size = WORLD_INFO['chunk_size']*10
	_map = WORLD_INFO['map']
	
	del WORLD_INFO['map']
	
	if only_cached:
		_cluster_keys = LOADED_CHUNKS
	else:
		_cluster_keys = []
		
		for y1 in range(0, MAP_SIZE[1], _chunk_cluster_size):
			for x1 in range(0, MAP_SIZE[0], _chunk_cluster_size):
				_cluster_keys.append('%s,%s' % (x1, y1))
				
	for cluster_key in _cluster_keys:
		_x1 = int(cluster_key.split(',')[0])
		_y1 = int(cluster_key.split(',')[1])
		
		with open(os.path.join(_map_dir, 'world_%s.cluster' % cluster_key.replace(',', '_')), 'w') as _cluster_file:
			for y2 in range(_y1, _y1+_chunk_cluster_size):
				for x2 in range(_x1, _x1+_chunk_cluster_size):
					_cluster_file.write(json.dumps(_map[x2][y2])+'\n')
	
	WORLD_INFO['map'] = _map
	SETTINGS['base_dir'] = _map_dir
コード例 #9
0
ファイル: maps.py プロジェクト: hovatterz/Reactor-3
def save_map(map_name, base_dir=DATA_DIR):
	_map_dir = os.path.join(base_dir,'maps')
	if not map_name.count('.dat'):
		map_name+='.dat'

	try:
		os.mkdir(_map_dir)
	except:
		pass
		
	for light in WORLD_INFO['lights']:
		if 'los' in light:
			del light['los']
		
		if 'old_pos' in light:
			del light['old_pos']

	with open(os.path.join(_map_dir,map_name), 'w') as _map_file:
		try:
			_map = WORLD_INFO['map']
			_slices = WORLD_INFO['slices']
			_chunk_map = WORLD_INFO['chunk_map']
			_weather_light_map = None
			
			del WORLD_INFO['map']
			del WORLD_INFO['slices']
			del WORLD_INFO['chunk_map']
			
			if 'light_map' in WORLD_INFO['weather']:
				_weather_light_map = WORLD_INFO['weather']['light_map']
				del WORLD_INFO['weather']['light_map']
			
			_map_file.write('world_info:%s\n' % json.dumps(WORLD_INFO))
			
			for _slice in _slices.keys():
				if '_map' in _slices[_slice]:
					del _slices[_slice]['_map']
				
				_map_file.write('slice:%s:%s\n' % (_slice, json.dumps(_slices[_slice])))
			
			for _chunk_key in _chunk_map:
				_map_file.write('chunk:%s:%s\n' % (_chunk_key, json.dumps(_chunk_map[_chunk_key])))
			
			logging.debug('Writing map to disk...')
			
			for x in range(MAP_SIZE[0]):
				_map_file.write('map:%s:%s\n' % (x, json.dumps(_map[x])))
				#logging.debug('Wrote segment %s/%s' % (x+1, MAP_SIZE[0]))
			
			logging.info('Map \'%s\' saved to disk.' % map_name)			
			
			WORLD_INFO['map'] = _map
			WORLD_INFO['slices'] = _slices
			WORLD_INFO['chunk_map'] = _chunk_map
			
			if _weather_light_map:
				WORLD_INFO['weather']['light_map'] = _weather_light_map
			
			logging.debug('Reloading slices...')
			reload_slices()
			logging.debug('Done!')
			
			logging.info('Map \'%s\' saved.' % map_name)
			gfx.log('Map \'%s\' saved.' % map_name)
		except TypeError as e:
			logging.critical('FATAL: Map not JSON serializable.')
			gfx.log('TypeError: Failed to save map (Map not JSON serializable).')
			
			raise e
コード例 #10
0
ファイル: maps.py プロジェクト: hovatterz/Reactor-3
def load_map(map_name, base_dir=DATA_DIR):
	_map_dir = os.path.join(base_dir,'maps')
	if not map_name.count('.dat'):
		map_name+='.dat'
		
	WORLD_INFO['map'] = []

	with open(os.path.join(_map_dir,map_name),'r') as _map_file:
		#try:
		#WORLD_INFO.update(json.loads(' '.join(_map_file.readlines())))
		for line in _map_file.readlines():
			line = line.rstrip()
			value = line.split(':')
			
			if line.startswith('chunk'):
				WORLD_INFO['chunk_map'][value[1]] = json.loads(':'.join(value[2:]))
			elif line.startswith('map'):
				WORLD_INFO['map'].append(json.loads(':'.join(value[2:])))
			elif line.startswith('slice'):
				WORLD_INFO['slices'][value[1]] = json.loads(':'.join(value[2:]))
			elif line.startswith('world_info'):
				WORLD_INFO.update(json.loads(':'.join(value[1:])))
		
		if 'items' in WORLD_INFO:
			ITEMS.update(WORLD_INFO['items'])
				
		#if not (x, y) in zone['map']:
		#for slice 
		
		_map_size = maputils.get_map_size(WORLD_INFO['map'])
		MAP_SIZE[0] = _map_size[0]
		MAP_SIZE[1] = _map_size[1]
		MAP_SIZE[2] = _map_size[2]
		
		reload_slices()
		
		WORLD_INFO['chunk_map'].update(WORLD_INFO['chunk_map'])
		
		alife.chunks.generate_cache()
		
		if WORLD_INFO['weather']:
			weather.create_light_map(WORLD_INFO['weather'])
		
		_map_size = maputils.get_map_size(WORLD_INFO['map'])
		
		for x in range(MAP_SIZE[0]):
			for y in range(MAP_SIZE[1]):
				for z in range(MAP_SIZE[2]):
					if not WORLD_INFO['map'][x][y][z]:
						continue
					
					for key in TILE_STRUCT_DEP:
						if key in WORLD_INFO['map'][x][y][z]:
							del WORLD_INFO['map'][x][y][z][key]
					
					for key in TILE_STRUCT:
						if not key in WORLD_INFO['map'][x][y][z]:
							WORLD_INFO['map'][x][y][z][key] = copy.copy(TILE_STRUCT[key])
		
		zones.cache_zones()
		create_position_maps()
		logging.info('Map \'%s\' loaded.' % map_name)
		gfx.log('Map \'%s\' loaded.' % map_name)

		return True