idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
53,100 | def _int ( int_or_str : Any ) -> int : "return an integer where a single character string may be expected" if isinstance ( int_or_str , str ) : return ord ( int_or_str ) if isinstance ( int_or_str , bytes ) : return int_or_str [ 0 ] return int ( int_or_str ) | return an integer where a single character string may be expected |
53,101 | def _console ( console : Any ) -> Any : try : return console . console_c except AttributeError : warnings . warn ( ( "Falsy console parameters are deprecated, " "always use the root console instance returned by " "console_init_root." ) , DeprecationWarning , stacklevel = 3 , ) return ffi . NULL | Return a cffi console . |
53,102 | def _new_from_cdata ( cls , cdata : Any ) -> "Color" : return cls ( cdata . r , cdata . g , cdata . b ) | new in libtcod - cffi |
53,103 | def _describe_bitmask ( bits : int , table : Dict [ Any , str ] , default : str = "0" ) -> str : result = [ ] for bit , name in table . items ( ) : if bit & bits : result . append ( name ) if not result : return default return "|" . join ( result ) | Returns a bitmask in human readable form . |
53,104 | def _pixel_to_tile ( x : float , y : float ) -> Tuple [ float , float ] : xy = tcod . ffi . new ( "double[2]" , ( x , y ) ) tcod . lib . TCOD_sys_pixel_to_tile ( xy , xy + 1 ) return xy [ 0 ] , xy [ 1 ] | Convert pixel coordinates to tile coordinates . |
53,105 | def get ( ) -> Iterator [ Any ] : sdl_event = tcod . ffi . new ( "SDL_Event*" ) while tcod . lib . SDL_PollEvent ( sdl_event ) : if sdl_event . type in _SDL_TO_CLASS_TABLE : yield _SDL_TO_CLASS_TABLE [ sdl_event . type ] . from_sdl_event ( sdl_event ) else : yield Undefined . from_sdl_event ( sdl_event ) | Return an iterator for all pending events . |
53,106 | def wait ( timeout : Optional [ float ] = None ) -> Iterator [ Any ] : if timeout is not None : tcod . lib . SDL_WaitEventTimeout ( tcod . ffi . NULL , int ( timeout * 1000 ) ) else : tcod . lib . SDL_WaitEvent ( tcod . ffi . NULL ) return get ( ) | Block until events exist then return an event iterator . |
53,107 | def get_mouse_state ( ) -> MouseState : xy = tcod . ffi . new ( "int[2]" ) buttons = tcod . lib . SDL_GetMouseState ( xy , xy + 1 ) x , y = _pixel_to_tile ( * xy ) return MouseState ( ( xy [ 0 ] , xy [ 1 ] ) , ( int ( x ) , int ( y ) ) , buttons ) | Return the current state of the mouse . |
53,108 | def deprecate ( message : str , category : Any = DeprecationWarning , stacklevel : int = 0 ) -> Callable [ [ F ] , F ] : def decorator ( func : F ) -> F : if not __debug__ : return func @ functools . wraps ( func ) def wrapper ( * args , ** kargs ) : warnings . warn ( message , category , stacklevel = stacklevel + 2 ) return func ( * args , ** kargs ) return cast ( F , wrapper ) return decorator | Return a decorator which adds a warning to functions . |
53,109 | def pending_deprecate ( message : str = "This function may be deprecated in the future." " Consider raising an issue on GitHub if you need this feature." , category : Any = PendingDeprecationWarning , stacklevel : int = 0 , ) -> Callable [ [ F ] , F ] : return deprecate ( message , category , stacklevel ) | Like deprecate but the default parameters are filled out for a generic pending deprecation warning . |
53,110 | def _format_char ( char ) : if char is None : return - 1 if isinstance ( char , _STRTYPES ) and len ( char ) == 1 : return ord ( char ) try : return int ( char ) except : raise TypeError ( 'char single character string, integer, or None\nReceived: ' + repr ( char ) ) | Prepares a single character for passing to ctypes calls needs to return an integer but can also pass None which will keep the current character instead of overwriting it . |
53,111 | def _format_str ( string ) : if isinstance ( string , _STRTYPES ) : if _IS_PYTHON3 : array = _array . array ( 'I' ) array . frombytes ( string . encode ( _utf32_codec ) ) else : if isinstance ( string , unicode ) : array = _array . array ( b'I' ) array . fromstring ( string . encode ( _utf32_codec ) ) else : array = _array . array ( b'B' ) array . fromstring ( string ) return array return string | Attempt fast string handing by decoding directly into an array . |
53,112 | def _getImageSize ( filename ) : result = None file = open ( filename , 'rb' ) if file . read ( 8 ) == b'\x89PNG\r\n\x1a\n' : while 1 : length , = _struct . unpack ( '>i' , file . read ( 4 ) ) chunkID = file . read ( 4 ) if chunkID == '' : break if chunkID == b'IHDR' : result = _struct . unpack ( '>ii' , file . read ( 8 ) ) break file . seek ( 4 + length , 1 ) file . close ( ) return result file . seek ( 0 ) if file . read ( 8 ) == b'BM' : file . seek ( 18 , 0 ) result = _struct . unpack ( '<ii' , file . read ( 8 ) ) file . close ( ) return result | Try to get the width and height of a bmp of png image file |
53,113 | def init ( width , height , title = None , fullscreen = False , renderer = 'SDL' ) : RENDERERS = { 'GLSL' : 0 , 'OPENGL' : 1 , 'SDL' : 2 } global _rootinitialized , _rootConsoleRef if not _fontinitialized : set_font ( _os . path . join ( __path__ [ 0 ] , 'terminal8x8.png' ) , None , None , True , True ) if renderer . upper ( ) not in RENDERERS : raise TDLError ( 'No such render type "%s", expected one of "%s"' % ( renderer , '", "' . join ( RENDERERS ) ) ) renderer = RENDERERS [ renderer . upper ( ) ] if _rootConsoleRef and _rootConsoleRef ( ) : _rootConsoleRef ( ) . _root_unhook ( ) if title is None : if _sys . argv : title = _os . path . basename ( _sys . argv [ 0 ] ) else : title = 'python-tdl' _lib . TCOD_console_init_root ( width , height , _encodeString ( title ) , fullscreen , renderer ) event . _eventsflushed = False _rootinitialized = True rootconsole = Console . _newConsole ( _ffi . NULL ) _rootConsoleRef = _weakref . ref ( rootconsole ) return rootconsole | Start the main console with the given width and height and return the root console . |
53,114 | def screenshot ( path = None ) : if not _rootinitialized : raise TDLError ( 'Initialize first with tdl.init' ) if isinstance ( path , str ) : _lib . TCOD_sys_save_screenshot ( _encodeString ( path ) ) elif path is None : filelist = _os . listdir ( '.' ) n = 1 filename = 'screenshot%.3i.png' % n while filename in filelist : n += 1 filename = 'screenshot%.3i.png' % n _lib . TCOD_sys_save_screenshot ( _encodeString ( filename ) ) else : tmpname = _os . tempnam ( ) _lib . TCOD_sys_save_screenshot ( _encodeString ( tmpname ) ) with tmpname as tmpfile : path . write ( tmpfile . read ( ) ) _os . remove ( tmpname ) | Capture the screen and save it as a png file . |
53,115 | def _normalizePoint ( self , x , y ) : x = int ( x ) y = int ( y ) assert ( - self . width <= x < self . width ) and ( - self . height <= y < self . height ) , ( '(%i, %i) is an invalid postition on %s' % ( x , y , self ) ) return ( x % self . width , y % self . height ) | Check if a point is in bounds and make minor adjustments . |
53,116 | def _normalizeRect ( self , x , y , width , height ) : x , y = self . _normalizePoint ( x , y ) assert width is None or isinstance ( width , _INTTYPES ) , 'width must be an integer or None, got %s' % repr ( width ) assert height is None or isinstance ( height , _INTTYPES ) , 'height must be an integer or None, got %s' % repr ( height ) if width is None : width = self . width - x elif width < 0 : width += self . width width = max ( 0 , width ) if height is None : height = self . height - y height = max ( 0 , height ) elif height < 0 : height += self . height width = min ( width , self . width - x ) height = min ( height , self . height - y ) return x , y , width , height | Check if the rectangle is in bounds and make minor adjustments . raise AssertionError s for any problems |
53,117 | def _normalizeCursor ( self , x , y ) : width , height = self . get_size ( ) assert width != 0 and height != 0 , 'can not print on a console with a width or height of zero' while x >= width : x -= width y += 1 while y >= height : if self . _scrollMode == 'scroll' : y -= 1 self . scroll ( 0 , - 1 ) elif self . _scrollMode == 'error' : self . _cursor = ( 0 , 0 ) raise TDLError ( 'Cursor has reached the end of the console' ) return ( x , y ) | return the normalized the cursor position . |
53,118 | def set_mode ( self , mode ) : MODES = [ 'error' , 'scroll' ] if mode . lower ( ) not in MODES : raise TDLError ( 'mode must be one of %s, got %s' % ( MODES , repr ( mode ) ) ) self . _scrollMode = mode . lower ( ) | Configure how this console will react to the cursor writing past the end if the console . |
53,119 | def print_str ( self , string ) : x , y = self . _cursor for char in string : if char == '\n' : x = 0 y += 1 continue if char == '\r' : x = 0 continue x , y = self . _normalizeCursor ( x , y ) self . draw_char ( x , y , char , self . _fg , self . _bg ) x += 1 self . _cursor = ( x , y ) | Print a string at the virtual cursor . |
53,120 | def write ( self , string ) : x , y = self . _normalizeCursor ( * self . _cursor ) width , height = self . get_size ( ) wrapper = _textwrap . TextWrapper ( initial_indent = ( ' ' * x ) , width = width ) writeLines = [ ] for line in string . split ( '\n' ) : if line : writeLines += wrapper . wrap ( line ) wrapper . initial_indent = '' else : writeLines . append ( [ ] ) for line in writeLines : x , y = self . _normalizeCursor ( x , y ) self . draw_str ( x , y , line [ x : ] , self . _fg , self . _bg ) y += 1 x = 0 y -= 1 self . _cursor = ( x , y ) | This method mimics basic file - like behaviour . |
53,121 | def draw_char ( self , x , y , char , fg = Ellipsis , bg = Ellipsis ) : _put_char_ex ( self . console_c , x , y , _format_char ( char ) , _format_color ( fg , self . _fg ) , _format_color ( bg , self . _bg ) , 1 ) | Draws a single character . |
53,122 | def draw_str ( self , x , y , string , fg = Ellipsis , bg = Ellipsis ) : x , y = self . _normalizePoint ( x , y ) fg , bg = _format_color ( fg , self . _fg ) , _format_color ( bg , self . _bg ) width , height = self . get_size ( ) def _drawStrGen ( x = x , y = y , string = string , width = width , height = height ) : for char in _format_str ( string ) : if y == height : raise TDLError ( 'End of console reached.' ) yield ( ( x , y ) , char ) x += 1 if x == width : x = 0 y += 1 self . _set_batch ( _drawStrGen ( ) , fg , bg ) | Draws a string starting at x and y . |
53,123 | def draw_rect ( self , x , y , width , height , string , fg = Ellipsis , bg = Ellipsis ) : x , y , width , height = self . _normalizeRect ( x , y , width , height ) fg , bg = _format_color ( fg , self . _fg ) , _format_color ( bg , self . _bg ) char = _format_char ( string ) grid = _itertools . product ( ( x for x in range ( x , x + width ) ) , ( y for y in range ( y , y + height ) ) ) batch = zip ( grid , _itertools . repeat ( char , width * height ) ) self . _set_batch ( batch , fg , bg , nullChar = ( char is None ) ) | Draws a rectangle starting from x and y and extending to width and height . |
53,124 | def blit ( self , source , x = 0 , y = 0 , width = None , height = None , srcX = 0 , srcY = 0 , fg_alpha = 1.0 , bg_alpha = 1.0 ) : assert isinstance ( source , ( Console , Window ) ) , "source muse be a Window or Console instance" x , y , width , height = self . _normalizeRect ( x , y , width , height ) srcX , srcY , width , height = source . _normalizeRect ( srcX , srcY , width , height ) srcX , srcY = source . _translate ( srcX , srcY ) source = source . console x , y = self . _translate ( x , y ) self = self . console if self == source : tmp = Console ( width , height ) _lib . TCOD_console_blit ( source . console_c , srcX , srcY , width , height , tmp . console_c , 0 , 0 , fg_alpha , bg_alpha ) _lib . TCOD_console_blit ( tmp . console_c , 0 , 0 , width , height , self . console_c , x , y , fg_alpha , bg_alpha ) else : _lib . TCOD_console_blit ( source . console_c , srcX , srcY , width , height , self . console_c , x , y , fg_alpha , bg_alpha ) | Blit another console or Window onto the current console . |
53,125 | def get_cursor ( self ) : x , y = self . _cursor width , height = self . parent . get_size ( ) while x >= width : x -= width y += 1 if y >= height and self . scrollMode == 'scroll' : y = height - 1 return x , y | Return the virtual cursor position . |
53,126 | def move ( self , x , y ) : self . _cursor = self . _normalizePoint ( x , y ) | Move the virtual cursor . |
53,127 | def scroll ( self , x , y ) : assert isinstance ( x , _INTTYPES ) , "x must be an integer, got %s" % repr ( x ) assert isinstance ( y , _INTTYPES ) , "y must be an integer, got %s" % repr ( x ) def getSlide ( x , length ) : if x > 0 : srcx = 0 length -= x elif x < 0 : srcx = abs ( x ) x = 0 length -= srcx else : srcx = 0 return x , length , srcx def getCover ( x , length ) : cover = ( 0 , length ) uncover = None if x > 0 : cover = ( x , length - x ) uncover = ( 0 , x ) elif x < 0 : x = abs ( x ) cover = ( 0 , length - x ) uncover = ( length - x , x ) return cover , uncover width , height = self . get_size ( ) if abs ( x ) >= width or abs ( y ) >= height : return self . clear ( ) coverX , uncoverX = getCover ( x , width ) coverY , uncoverY = getCover ( y , height ) x , width , srcx = getSlide ( x , width ) y , height , srcy = getSlide ( y , height ) self . blit ( self , x , y , width , height , srcx , srcy ) if uncoverX : self . draw_rect ( uncoverX [ 0 ] , coverY [ 0 ] , uncoverX [ 1 ] , coverY [ 1 ] , 0x20 , self . _fg , self . _bg ) if uncoverY : self . draw_rect ( coverX [ 0 ] , uncoverY [ 0 ] , coverX [ 1 ] , uncoverY [ 1 ] , 0x20 , self . _fg , self . _bg ) if uncoverX and uncoverY : self . draw_rect ( uncoverX [ 0 ] , uncoverY [ 0 ] , uncoverX [ 1 ] , uncoverY [ 1 ] , 0x20 , self . _fg , self . _bg ) | Scroll the contents of the console in the direction of x y . |
53,128 | def _newConsole ( cls , console ) : self = cls . __new__ ( cls ) _BaseConsole . __init__ ( self ) self . console_c = console self . console = self self . width = _lib . TCOD_console_get_width ( console ) self . height = _lib . TCOD_console_get_height ( console ) return self | Make a Console instance from a console ctype |
53,129 | def _root_unhook ( self ) : global _rootinitialized , _rootConsoleRef if ( _rootConsoleRef and _rootConsoleRef ( ) is self ) : unhooked = _lib . TCOD_console_new ( self . width , self . height ) _lib . TCOD_console_blit ( self . console_c , 0 , 0 , self . width , self . height , unhooked , 0 , 0 , 1 , 1 ) _rootinitialized = False _rootConsoleRef = None _lib . TCOD_console_delete ( self . console_c ) self . console_c = unhooked | Change this root console into a normal Console object and delete the root console from TCOD |
53,130 | def _set_char ( self , x , y , char , fg = None , bg = None , bgblend = _lib . TCOD_BKGND_SET ) : return _put_char_ex ( self . console_c , x , y , char , fg , bg , bgblend ) | Sets a character . This is called often and is designed to be as fast as possible . |
53,131 | def _set_batch ( self , batch , fg , bg , bgblend = 1 , nullChar = False ) : for ( x , y ) , char in batch : self . _set_char ( x , y , char , fg , bg , bgblend ) | Try to perform a batch operation otherwise fall back to _set_char . If fg and bg are defined then this is faster but not by very much . |
53,132 | def _translate ( self , x , y ) : return self . parent . _translate ( ( x + self . x ) , ( y + self . y ) ) | Convertion x and y to their position on the root Console |
53,133 | def _pycall_path_old ( x1 : int , y1 : int , x2 : int , y2 : int , handle : Any ) -> float : func , userData = ffi . from_handle ( handle ) return func ( x1 , y1 , x2 , y2 , userData ) | libtcodpy style callback needs to preserve the old userData issue . |
53,134 | def _pycall_path_simple ( x1 : int , y1 : int , x2 : int , y2 : int , handle : Any ) -> float : return ffi . from_handle ( handle ) ( x1 , y1 , x2 , y2 ) | Does less and should run faster just calls the handle function . |
53,135 | def _get_pathcost_func ( name : str ) -> Callable [ [ int , int , int , int , Any ] , float ] : return ffi . cast ( "TCOD_path_func_t" , ffi . addressof ( lib , name ) ) | Return a properly cast PathCostArray callback . |
53,136 | def set_goal ( self , x : int , y : int ) -> None : lib . TCOD_dijkstra_compute ( self . _path_c , x , y ) | Set the goal point and recompute the Dijkstra path - finder . |
53,137 | def poll_event ( self ) : for e in tdl . event . get ( ) : self . e . type = e . type if e . type == 'KEYDOWN' : self . e . key = e . key return self . e . gettuple ( ) | Wait for an event and return it . |
53,138 | def _new_from_cdata ( cls , cdata : Any ) -> "Random" : self = object . __new__ ( cls ) self . random_c = cdata return self | Return a new instance encapsulating this cdata . |
53,139 | def guass ( self , mu : float , sigma : float ) -> float : return float ( lib . TCOD_random_get_gaussian_double ( self . random_c , mu , sigma ) ) | Return a random number using Gaussian distribution . |
53,140 | def inverse_guass ( self , mu : float , sigma : float ) -> float : return float ( lib . TCOD_random_get_gaussian_double_inv ( self . random_c , mu , sigma ) ) | Return a random Gaussian number using the Box - Muller transform . |
53,141 | def get_point ( self , * position ) : array = _ffi . new ( self . _arrayType , position ) if self . _useOctaves : return ( self . _noiseFunc ( self . _noise , array , self . _octaves ) + 1 ) * 0.5 return ( self . _noiseFunc ( self . _noise , array ) + 1 ) * 0.5 | Return the noise value of a specific position . |
53,142 | def compute_fov ( transparency : np . array , x : int , y : int , radius : int = 0 , light_walls : bool = True , algorithm : int = tcod . constants . FOV_RESTRICTIVE , ) -> np . array : if len ( transparency . shape ) != 2 : raise TypeError ( "transparency must be an array of 2 dimensions" " (shape is %r)" % transparency . shape ) map_ = Map ( transparency . shape [ 1 ] , transparency . shape [ 0 ] ) map_ . transparent [ ... ] = transparency map_ . compute_fov ( x , y , radius , light_walls , algorithm ) return map_ . fov | Return the visible area of a field - of - view computation . |
53,143 | def compute_fov ( self , x : int , y : int , radius : int = 0 , light_walls : bool = True , algorithm : int = tcod . constants . FOV_RESTRICTIVE , ) -> None : lib . TCOD_map_compute_fov ( self . map_c , x , y , radius , light_walls , algorithm ) | Compute a field - of - view on the current instance . |
53,144 | def sample_mgrid ( self , mgrid : np . array ) -> np . array : mgrid = np . ascontiguousarray ( mgrid , np . float32 ) if mgrid . shape [ 0 ] != self . dimensions : raise ValueError ( "mgrid.shape[0] must equal self.dimensions, " "%r[0] != %r" % ( mgrid . shape , self . dimensions ) ) out = np . ndarray ( mgrid . shape [ 1 : ] , np . float32 ) if mgrid . shape [ 1 : ] != out . shape : raise ValueError ( "mgrid.shape[1:] must equal out.shape, " "%r[1:] != %r" % ( mgrid . shape , out . shape ) ) lib . NoiseSampleMeshGrid ( self . _tdl_noise_c , out . size , ffi . cast ( "float*" , mgrid . ctypes . data ) , ffi . cast ( "float*" , out . ctypes . data ) , ) return out | Sample a mesh - grid array and return the result . |
53,145 | def sample_ogrid ( self , ogrid : np . array ) -> np . array : if len ( ogrid ) != self . dimensions : raise ValueError ( "len(ogrid) must equal self.dimensions, " "%r != %r" % ( len ( ogrid ) , self . dimensions ) ) ogrids = [ np . ascontiguousarray ( array , np . float32 ) for array in ogrid ] out = np . ndarray ( [ array . size for array in ogrids ] , np . float32 ) lib . NoiseSampleOpenMeshGrid ( self . _tdl_noise_c , len ( ogrids ) , out . shape , [ ffi . cast ( "float*" , array . ctypes . data ) for array in ogrids ] , ffi . cast ( "float*" , out . ctypes . data ) , ) return out | Sample an open mesh - grid array and return the result . |
53,146 | def _processEvents ( ) : global _mousel , _mousem , _mouser , _eventsflushed , _pushedEvents _eventsflushed = True events = _pushedEvents _pushedEvents = [ ] mouse = _ffi . new ( 'TCOD_mouse_t *' ) libkey = _ffi . new ( 'TCOD_key_t *' ) while 1 : libevent = _lib . TCOD_sys_check_for_event ( _lib . TCOD_EVENT_ANY , libkey , mouse ) if not libevent : break if libevent & _lib . TCOD_EVENT_MOUSE_MOVE : events . append ( MouseMotion ( ( mouse . x , mouse . y ) , ( mouse . cx , mouse . cy ) , ( mouse . dx , mouse . dy ) , ( mouse . dcx , mouse . dcy ) ) ) mousepos = ( ( mouse . x , mouse . y ) , ( mouse . cx , mouse . cy ) ) for oldstate , newstate , released , button in zip ( ( _mousel , _mousem , _mouser ) , ( mouse . lbutton , mouse . mbutton , mouse . rbutton ) , ( mouse . lbutton_pressed , mouse . mbutton_pressed , mouse . rbutton_pressed ) , ( 1 , 2 , 3 ) ) : if released : if not oldstate : events . append ( MouseDown ( button , * mousepos ) ) events . append ( MouseUp ( button , * mousepos ) ) if newstate : events . append ( MouseDown ( button , * mousepos ) ) elif newstate and not oldstate : events . append ( MouseDown ( button , * mousepos ) ) if mouse . wheel_up : events . append ( MouseDown ( 4 , * mousepos ) ) if mouse . wheel_down : events . append ( MouseDown ( 5 , * mousepos ) ) _mousel = mouse . lbutton _mousem = mouse . mbutton _mouser = mouse . rbutton if libkey . vk == _lib . TCODK_NONE : break if libkey . pressed : keyevent = KeyDown else : keyevent = KeyUp events . append ( keyevent ( libkey . vk , libkey . c . decode ( 'ascii' , errors = 'ignore' ) , _ffi . string ( libkey . text ) . decode ( 'utf-8' ) , libkey . shift , libkey . lalt , libkey . ralt , libkey . lctrl , libkey . rctrl , libkey . lmeta , libkey . rmeta , ) ) if _lib . TCOD_console_is_window_closed ( ) : events . append ( Quit ( ) ) _eventQueue . extend ( events ) | Flushes the event queue from libtcod into the global list _eventQueue |
53,147 | def wait ( timeout = None , flush = True ) : if timeout is not None : timeout = timeout + _time . clock ( ) while True : if _eventQueue : return _eventQueue . pop ( 0 ) if flush : _tdl . flush ( ) if timeout and _time . clock ( ) >= timeout : return None _time . sleep ( 0.001 ) _processEvents ( ) | Wait for an event . |
53,148 | def run_once ( self ) : if not hasattr ( self , '_App__prevTime' ) : self . __prevTime = _time . clock ( ) for event in get ( ) : if event . type : method = 'ev_%s' % event . type getattr ( self , method ) ( event ) if event . type == 'KEYDOWN' : method = 'key_%s' % event . key if hasattr ( self , method ) : getattr ( self , method ) ( event ) newTime = _time . clock ( ) self . update ( newTime - self . __prevTime ) self . __prevTime = newTime | Pump events to this App instance and then return . |
53,149 | def load_truetype_font ( path : str , tile_width : int , tile_height : int ) -> Tileset : if not os . path . exists ( path ) : raise RuntimeError ( "File not found:\n\t%s" % ( os . path . realpath ( path ) , ) ) return Tileset . _claim ( lib . TCOD_load_truetype_font_ ( path . encode ( ) , tile_width , tile_height ) ) | Return a new Tileset from a . ttf or . otf file . |
53,150 | def set_truetype_font ( path : str , tile_width : int , tile_height : int ) -> None : if not os . path . exists ( path ) : raise RuntimeError ( "File not found:\n\t%s" % ( os . path . realpath ( path ) , ) ) lib . TCOD_tileset_load_truetype_ ( path . encode ( ) , tile_width , tile_height ) | Set the default tileset from a . ttf or . otf file . |
53,151 | def get_tile ( self , codepoint : int ) -> np . array : tile = np . zeros ( self . tile_shape + ( 4 , ) , dtype = np . uint8 ) lib . TCOD_tileset_get_tile_ ( self . _tileset_p , codepoint , ffi . cast ( "struct TCOD_ColorRGBA*" , tile . ctypes . data ) , ) return tile | Return a copy of a tile for the given codepoint . |
53,152 | def set_tile ( self , codepoint : int , tile : np . array ) -> None : tile = np . ascontiguousarray ( tile , dtype = np . uint8 ) if tile . shape == self . tile_shape : full_tile = np . empty ( self . tile_shape + ( 4 , ) , dtype = np . uint8 ) full_tile [ : , : , : 3 ] = 255 full_tile [ : , : , 3 ] = tile return self . set_tile ( codepoint , full_tile ) required = self . tile_shape + ( 4 , ) if tile . shape != required : raise ValueError ( "Tile shape must be %r or %r, got %r." % ( required , self . tile_shape , tile . shape ) ) lib . TCOD_tileset_set_tile_ ( self . _tileset_p , codepoint , ffi . cast ( "struct TCOD_ColorRGBA*" , tile . ctypes . data ) , ) | Upload a tile into this array . |
53,153 | def fix_header ( filepath ) : with open ( filepath , "r+" ) as f : current = f . read ( ) fixed = "\n" . join ( line . strip ( ) for line in current . split ( "\n" ) ) if current == fixed : return f . seek ( 0 ) f . truncate ( ) f . write ( fixed ) | Removes leading whitespace from a MacOS header file . |
53,154 | def find_sdl_attrs ( prefix : str ) -> Iterator [ Tuple [ str , Any ] ] : from tcod . _libtcod import lib if prefix . startswith ( "SDL_" ) : name_starts_at = 4 elif prefix . startswith ( "SDL" ) : name_starts_at = 3 else : name_starts_at = 0 for attr in dir ( lib ) : if attr . startswith ( prefix ) : yield attr [ name_starts_at : ] , getattr ( lib , attr ) | Return names and values from tcod . lib . |
53,155 | def write_library_constants ( ) : from tcod . _libtcod import lib , ffi import tcod . color with open ( "tcod/constants.py" , "w" ) as f : all_names = [ ] f . write ( CONSTANT_MODULE_HEADER ) for name in dir ( lib ) : value = getattr ( lib , name ) if name [ : 5 ] == "TCOD_" : if name . isupper ( ) : f . write ( "%s = %r\n" % ( name [ 5 : ] , value ) ) all_names . append ( name [ 5 : ] ) elif name . startswith ( "FOV" ) : f . write ( "%s = %r\n" % ( name , value ) ) all_names . append ( name ) elif name [ : 6 ] == "TCODK_" : f . write ( "KEY_%s = %r\n" % ( name [ 6 : ] , value ) ) all_names . append ( "KEY_%s" % name [ 6 : ] ) f . write ( "\n# --- colors ---\n" ) for name in dir ( lib ) : if name [ : 5 ] != "TCOD_" : continue value = getattr ( lib , name ) if not isinstance ( value , ffi . CData ) : continue if ffi . typeof ( value ) != ffi . typeof ( "TCOD_color_t" ) : continue color = tcod . color . Color . _new_from_cdata ( value ) f . write ( "%s = %r\n" % ( name [ 5 : ] , color ) ) all_names . append ( name [ 5 : ] ) all_names = ",\n " . join ( '"%s"' % name for name in all_names ) f . write ( "\n__all__ = [\n %s,\n]\n" % ( all_names , ) ) with open ( "tcod/event_constants.py" , "w" ) as f : all_names = [ ] f . write ( EVENT_CONSTANT_MODULE_HEADER ) f . write ( "# --- SDL scancodes ---\n" ) f . write ( "%s\n_REVERSE_SCANCODE_TABLE = %s\n" % parse_sdl_attrs ( "SDL_SCANCODE" , all_names ) ) f . write ( "\n# --- SDL keyboard symbols ---\n" ) f . write ( "%s\n_REVERSE_SYM_TABLE = %s\n" % parse_sdl_attrs ( "SDLK" , all_names ) ) f . write ( "\n# --- SDL keyboard modifiers ---\n" ) f . write ( "%s\n_REVERSE_MOD_TABLE = %s\n" % parse_sdl_attrs ( "KMOD" , all_names ) ) f . write ( "\n# --- SDL wheel ---\n" ) f . write ( "%s\n_REVERSE_WHEEL_TABLE = %s\n" % parse_sdl_attrs ( "SDL_MOUSEWHEEL" , all_names ) ) all_names = ",\n " . join ( '"%s"' % name for name in all_names ) f . write ( "\n__all__ = [\n %s,\n]\n" % ( all_names , ) ) | Write libtcod constants into the tcod . constants module . |
53,156 | def visit_EnumeratorList ( self , node ) : for type , enum in node . children ( ) : if enum . value is None : pass elif isinstance ( enum . value , ( c_ast . BinaryOp , c_ast . UnaryOp ) ) : enum . value = c_ast . Constant ( "int" , "..." ) elif hasattr ( enum . value , "type" ) : enum . value = c_ast . Constant ( enum . value . type , "..." ) | Replace enumerator expressions with ... stubs . |
53,157 | def bsp_new_with_size ( x : int , y : int , w : int , h : int ) -> tcod . bsp . BSP : return Bsp ( x , y , w , h ) | Create a new BSP instance with the given rectangle . |
53,158 | def _bsp_traverse ( node_iter : Iterable [ tcod . bsp . BSP ] , callback : Callable [ [ tcod . bsp . BSP , Any ] , None ] , userData : Any , ) -> None : for node in node_iter : callback ( node , userData ) | pack callback into a handle for use with the callback _pycall_bsp_callback |
53,159 | def color_lerp ( c1 : Tuple [ int , int , int ] , c2 : Tuple [ int , int , int ] , a : float ) -> Color : return Color . _new_from_cdata ( lib . TCOD_color_lerp ( c1 , c2 , a ) ) | Return the linear interpolation between two colors . |
53,160 | def color_scale_HSV ( c : Color , scoef : float , vcoef : float ) -> None : color_p = ffi . new ( "TCOD_color_t*" ) color_p . r , color_p . g , color_p . b = c . r , c . g , c . b lib . TCOD_color_scale_HSV ( color_p , scoef , vcoef ) c [ : ] = color_p . r , color_p . g , color_p . b | Scale a color s saturation and value . |
53,161 | def color_gen_map ( colors : Iterable [ Tuple [ int , int , int ] ] , indexes : Iterable [ int ] ) -> List [ Color ] : ccolors = ffi . new ( "TCOD_color_t[]" , colors ) cindexes = ffi . new ( "int[]" , indexes ) cres = ffi . new ( "TCOD_color_t[]" , max ( indexes ) + 1 ) lib . TCOD_color_gen_map ( cres , len ( ccolors ) , ccolors , cindexes ) return [ Color . _new_from_cdata ( cdata ) for cdata in cres ] | Return a smoothly defined scale of colors . |
53,162 | def console_init_root ( w : int , h : int , title : Optional [ str ] = None , fullscreen : bool = False , renderer : Optional [ int ] = None , order : str = "C" , ) -> tcod . console . Console : if title is None : title = os . path . basename ( sys . argv [ 0 ] ) if renderer is None : warnings . warn ( "A renderer should be given, see the online documentation." , DeprecationWarning , stacklevel = 2 , ) renderer = tcod . constants . RENDERER_SDL elif renderer in ( tcod . constants . RENDERER_SDL , tcod . constants . RENDERER_OPENGL , tcod . constants . RENDERER_GLSL , ) : warnings . warn ( "The SDL, OPENGL, and GLSL renderers are deprecated." , DeprecationWarning , stacklevel = 2 , ) lib . TCOD_console_init_root ( w , h , _bytes ( title ) , fullscreen , renderer ) console = tcod . console . Console . _get_root ( order ) console . clear ( ) return console | Set up the primary display and return the root console . |
53,163 | def console_set_custom_font ( fontFile : AnyStr , flags : int = FONT_LAYOUT_ASCII_INCOL , nb_char_horiz : int = 0 , nb_char_vertic : int = 0 , ) -> None : if not os . path . exists ( fontFile ) : raise RuntimeError ( "File not found:\n\t%s" % ( os . path . realpath ( fontFile ) , ) ) lib . TCOD_console_set_custom_font ( _bytes ( fontFile ) , flags , nb_char_horiz , nb_char_vertic ) | Load the custom font file at fontFile . |
53,164 | def console_get_width ( con : tcod . console . Console ) -> int : return int ( lib . TCOD_console_get_width ( _console ( con ) ) ) | Return the width of a console . |
53,165 | def console_get_height ( con : tcod . console . Console ) -> int : return int ( lib . TCOD_console_get_height ( _console ( con ) ) ) | Return the height of a console . |
53,166 | def console_map_ascii_code_to_font ( asciiCode : int , fontCharX : int , fontCharY : int ) -> None : lib . TCOD_console_map_ascii_code_to_font ( _int ( asciiCode ) , fontCharX , fontCharY ) | Set a character code to new coordinates on the tile - set . |
53,167 | def console_map_ascii_codes_to_font ( firstAsciiCode : int , nbCodes : int , fontCharX : int , fontCharY : int ) -> None : lib . TCOD_console_map_ascii_codes_to_font ( _int ( firstAsciiCode ) , nbCodes , fontCharX , fontCharY ) | Remap a contiguous set of codes to a contiguous set of tiles . |
53,168 | def console_map_string_to_font ( s : str , fontCharX : int , fontCharY : int ) -> None : lib . TCOD_console_map_string_to_font_utf ( _unicode ( s ) , fontCharX , fontCharY ) | Remap a string of codes to a contiguous set of tiles . |
53,169 | def console_set_default_background ( con : tcod . console . Console , col : Tuple [ int , int , int ] ) -> None : lib . TCOD_console_set_default_background ( _console ( con ) , col ) | Change the default background color for a console . |
53,170 | def console_set_default_foreground ( con : tcod . console . Console , col : Tuple [ int , int , int ] ) -> None : lib . TCOD_console_set_default_foreground ( _console ( con ) , col ) | Change the default foreground color for a console . |
53,171 | def console_put_char_ex ( con : tcod . console . Console , x : int , y : int , c : Union [ int , str ] , fore : Tuple [ int , int , int ] , back : Tuple [ int , int , int ] , ) -> None : lib . TCOD_console_put_char_ex ( _console ( con ) , x , y , _int ( c ) , fore , back ) | Draw the character c at x y using the colors fore and back . |
53,172 | def console_set_char_background ( con : tcod . console . Console , x : int , y : int , col : Tuple [ int , int , int ] , flag : int = BKGND_SET , ) -> None : lib . TCOD_console_set_char_background ( _console ( con ) , x , y , col , flag ) | Change the background color of x y to col using a blend mode . |
53,173 | def console_set_char_foreground ( con : tcod . console . Console , x : int , y : int , col : Tuple [ int , int , int ] ) -> None : lib . TCOD_console_set_char_foreground ( _console ( con ) , x , y , col ) | Change the foreground color of x y to col . |
53,174 | def console_set_char ( con : tcod . console . Console , x : int , y : int , c : Union [ int , str ] ) -> None : lib . TCOD_console_set_char ( _console ( con ) , x , y , _int ( c ) ) | Change the character at x y to c keeping the current colors . |
53,175 | def console_set_background_flag ( con : tcod . console . Console , flag : int ) -> None : lib . TCOD_console_set_background_flag ( _console ( con ) , flag ) | Change the default blend mode for this console . |
53,176 | def console_get_background_flag ( con : tcod . console . Console ) -> int : return int ( lib . TCOD_console_get_background_flag ( _console ( con ) ) ) | Return this consoles current blend mode . |
53,177 | def console_set_alignment ( con : tcod . console . Console , alignment : int ) -> None : lib . TCOD_console_set_alignment ( _console ( con ) , alignment ) | Change this consoles current alignment mode . |
53,178 | def console_get_alignment ( con : tcod . console . Console ) -> int : return int ( lib . TCOD_console_get_alignment ( _console ( con ) ) ) | Return this consoles current alignment mode . |
53,179 | def console_print_ex ( con : tcod . console . Console , x : int , y : int , flag : int , alignment : int , fmt : str , ) -> None : lib . TCOD_console_printf_ex ( _console ( con ) , x , y , flag , alignment , _fmt ( fmt ) ) | Print a string on a console using a blend mode and alignment mode . |
53,180 | def console_print_rect_ex ( con : tcod . console . Console , x : int , y : int , w : int , h : int , flag : int , alignment : int , fmt : str , ) -> int : return int ( lib . TCOD_console_printf_rect_ex ( _console ( con ) , x , y , w , h , flag , alignment , _fmt ( fmt ) ) ) | Print a string constrained to a rectangle with blend and alignment . |
53,181 | def console_get_height_rect ( con : tcod . console . Console , x : int , y : int , w : int , h : int , fmt : str ) -> int : return int ( lib . TCOD_console_get_height_rect_fmt ( _console ( con ) , x , y , w , h , _fmt ( fmt ) ) ) | Return the height of this text once word - wrapped into this rectangle . |
53,182 | def console_print_frame ( con : tcod . console . Console , x : int , y : int , w : int , h : int , clear : bool = True , flag : int = BKGND_DEFAULT , fmt : str = "" , ) -> None : fmt = _fmt ( fmt ) if fmt else ffi . NULL lib . TCOD_console_printf_frame ( _console ( con ) , x , y , w , h , clear , flag , fmt ) | Draw a framed rectangle with optinal text . |
53,183 | def console_get_default_background ( con : tcod . console . Console ) -> Color : return Color . _new_from_cdata ( lib . TCOD_console_get_default_background ( _console ( con ) ) ) | Return this consoles default background color . |
53,184 | def console_get_default_foreground ( con : tcod . console . Console ) -> Color : return Color . _new_from_cdata ( lib . TCOD_console_get_default_foreground ( _console ( con ) ) ) | Return this consoles default foreground color . |
53,185 | def console_get_char_background ( con : tcod . console . Console , x : int , y : int ) -> Color : return Color . _new_from_cdata ( lib . TCOD_console_get_char_background ( _console ( con ) , x , y ) ) | Return the background color at the x y of this console . |
53,186 | def console_get_char_foreground ( con : tcod . console . Console , x : int , y : int ) -> Color : return Color . _new_from_cdata ( lib . TCOD_console_get_char_foreground ( _console ( con ) , x , y ) ) | Return the foreground color at the x y of this console . |
53,187 | def console_get_char ( con : tcod . console . Console , x : int , y : int ) -> int : return lib . TCOD_console_get_char ( _console ( con ) , x , y ) | Return the character at the x y of this console . |
53,188 | def console_wait_for_keypress ( flush : bool ) -> Key : key = Key ( ) lib . TCOD_console_wait_for_keypress_wrapper ( key . key_p , flush ) return key | Block until the user presses a key then returns a new Key . |
53,189 | def console_from_file ( filename : str ) -> tcod . console . Console : return tcod . console . Console . _from_cdata ( lib . TCOD_console_from_file ( filename . encode ( "utf-8" ) ) ) | Return a new console object from a filename . |
53,190 | def console_blit ( src : tcod . console . Console , x : int , y : int , w : int , h : int , dst : tcod . console . Console , xdst : int , ydst : int , ffade : float = 1.0 , bfade : float = 1.0 , ) -> None : lib . TCOD_console_blit ( _console ( src ) , x , y , w , h , _console ( dst ) , xdst , ydst , ffade , bfade ) | Blit the console src from x y w h to console dst at xdst ydst . |
53,191 | def console_delete ( con : tcod . console . Console ) -> None : con = _console ( con ) if con == ffi . NULL : lib . TCOD_console_delete ( con ) warnings . warn ( "Instead of this call you should use a with statement to ensure" " the root console closes, for example:" "\n with tcod.console_init_root(...) as root_console:" "\n ..." , DeprecationWarning , stacklevel = 2 , ) else : warnings . warn ( "You no longer need to make this call, " "Console's are deleted when they go out of scope." , DeprecationWarning , stacklevel = 2 , ) | Closes the window if con is the root console . |
53,192 | def console_fill_foreground ( con : tcod . console . Console , r : Sequence [ int ] , g : Sequence [ int ] , b : Sequence [ int ] , ) -> None : if len ( r ) != len ( g ) or len ( r ) != len ( b ) : raise TypeError ( "R, G and B must all have the same size." ) if ( isinstance ( r , np . ndarray ) and isinstance ( g , np . ndarray ) and isinstance ( b , np . ndarray ) ) : r_ = np . ascontiguousarray ( r , dtype = np . intc ) g_ = np . ascontiguousarray ( g , dtype = np . intc ) b_ = np . ascontiguousarray ( b , dtype = np . intc ) cr = ffi . cast ( "int *" , r_ . ctypes . data ) cg = ffi . cast ( "int *" , g_ . ctypes . data ) cb = ffi . cast ( "int *" , b_ . ctypes . data ) else : cr = ffi . new ( "int[]" , r ) cg = ffi . new ( "int[]" , g ) cb = ffi . new ( "int[]" , b ) lib . TCOD_console_fill_foreground ( _console ( con ) , cr , cg , cb ) | Fill the foregound of a console with r g b . |
53,193 | def console_fill_char ( con : tcod . console . Console , arr : Sequence [ int ] ) -> None : if isinstance ( arr , np . ndarray ) : np_array = np . ascontiguousarray ( arr , dtype = np . intc ) carr = ffi . cast ( "int *" , np_array . ctypes . data ) else : carr = ffi . new ( "int[]" , arr ) lib . TCOD_console_fill_char ( _console ( con ) , carr ) | Fill the character tiles of a console with an array . |
53,194 | def console_load_asc ( con : tcod . console . Console , filename : str ) -> bool : return bool ( lib . TCOD_console_load_asc ( _console ( con ) , filename . encode ( "utf-8" ) ) ) | Update a console from a non - delimited ASCII . asc file . |
53,195 | def console_save_asc ( con : tcod . console . Console , filename : str ) -> bool : return bool ( lib . TCOD_console_save_asc ( _console ( con ) , filename . encode ( "utf-8" ) ) ) | Save a console to a non - delimited ASCII . asc file . |
53,196 | def console_load_apf ( con : tcod . console . Console , filename : str ) -> bool : return bool ( lib . TCOD_console_load_apf ( _console ( con ) , filename . encode ( "utf-8" ) ) ) | Update a console from an ASCII Paint . apf file . |
53,197 | def console_save_apf ( con : tcod . console . Console , filename : str ) -> bool : return bool ( lib . TCOD_console_save_apf ( _console ( con ) , filename . encode ( "utf-8" ) ) ) | Save a console to an ASCII Paint . apf file . |
53,198 | def console_load_xp ( con : tcod . console . Console , filename : str ) -> bool : return bool ( lib . TCOD_console_load_xp ( _console ( con ) , filename . encode ( "utf-8" ) ) ) | Update a console from a REXPaint . xp file . |
53,199 | def console_save_xp ( con : tcod . console . Console , filename : str , compress_level : int = 9 ) -> bool : return bool ( lib . TCOD_console_save_xp ( _console ( con ) , filename . encode ( "utf-8" ) , compress_level ) ) | Save a console to a REXPaint . xp file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.