signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def set_title(title):
|
if not _rootinitialized:<EOL><INDENT>raise TDLError('<STR_LIT>')<EOL><DEDENT>_lib.TCOD_console_set_window_title(_encodeString(title))<EOL>
|
Change the window title.
Args:
title (Text): The new title text.
|
f3164:m11
|
def screenshot(path=None):
|
if not _rootinitialized:<EOL><INDENT>raise TDLError('<STR_LIT>')<EOL><DEDENT>if isinstance(path, str):<EOL><INDENT>_lib.TCOD_sys_save_screenshot(_encodeString(path))<EOL><DEDENT>elif path is None: <EOL><INDENT>filelist = _os.listdir('<STR_LIT:.>')<EOL>n = <NUM_LIT:1><EOL>filename = '<STR_LIT>' % n<EOL>while filename in filelist:<EOL><INDENT>n += <NUM_LIT:1><EOL>filename = '<STR_LIT>' % n<EOL><DEDENT>_lib.TCOD_sys_save_screenshot(_encodeString(filename))<EOL><DEDENT>else: <EOL><INDENT>tmpname = _os.tempnam()<EOL>_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))<EOL>with tmpname as tmpfile:<EOL><INDENT>path.write(tmpfile.read())<EOL><DEDENT>_os.remove(tmpname)<EOL><DEDENT>
|
Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
|
f3164:m12
|
def set_fps(fps):
|
_lib.TCOD_sys_set_fps(fps or <NUM_LIT:0>)<EOL>
|
Set the maximum frame rate.
Further calls to :any:`tdl.flush` will limit the speed of
the program to run at `fps` frames per second. This can
also be set to None to remove the frame rate limit.
Args:
fps (optional[int]): The frames per second limit, or None.
|
f3164:m13
|
def get_fps():
|
return _lib.TCOD_sys_get_fps()<EOL>
|
Return the current frames per second of the running program set by
:any:`set_fps`
Returns:
int: The frame rate set by :any:`set_fps`.
If there is no current limit, this will return 0.
|
f3164:m14
|
def force_resolution(width, height):
|
_lib.TCOD_sys_force_fullscreen_resolution(width, height)<EOL>
|
Change the fullscreen resoulution.
Args:
width (int): Width in pixels.
height (int): Height in pixels.
|
f3164:m15
|
def _normalizePoint(self, x, y):
|
<EOL>x = int(x)<EOL>y = int(y)<EOL>assert (-self.width <= x < self.width) and(-self.height <= y < self.height),('<STR_LIT>' % (x, y, self))<EOL>return (x % self.width, y % self.height)<EOL>
|
Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
|
f3164:c1:m1
|
def _normalizeRect(self, x, y, width, height):
|
x, y = self._normalizePoint(x, y) <EOL>assert width is None or isinstance(width, _INTTYPES), '<STR_LIT>' % repr(width)<EOL>assert height is None or isinstance(height, _INTTYPES), '<STR_LIT>' % repr(height)<EOL>if width is None:<EOL><INDENT>width = self.width - x<EOL><DEDENT>elif width < <NUM_LIT:0>: <EOL><INDENT>width += self.width<EOL>width = max(<NUM_LIT:0>, width) <EOL><DEDENT>if height is None:<EOL><INDENT>height = self.height - y<EOL>height = max(<NUM_LIT:0>, height)<EOL><DEDENT>elif height < <NUM_LIT:0>:<EOL><INDENT>height += self.height<EOL><DEDENT>width = min(width, self.width - x)<EOL>height = min(height, self.height - y)<EOL>return x, y, width, height<EOL>
|
Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
|
f3164:c1:m2
|
def _normalizeCursor(self, x, y):
|
width, height = self.get_size()<EOL>assert width != <NUM_LIT:0> and height != <NUM_LIT:0>, '<STR_LIT>'<EOL>while x >= width:<EOL><INDENT>x -= width<EOL>y += <NUM_LIT:1><EOL><DEDENT>while y >= height:<EOL><INDENT>if self._scrollMode == '<STR_LIT>':<EOL><INDENT>y -= <NUM_LIT:1><EOL>self.scroll(<NUM_LIT:0>, -<NUM_LIT:1>)<EOL><DEDENT>elif self._scrollMode == '<STR_LIT:error>':<EOL><INDENT>self._cursor = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL>raise TDLError('<STR_LIT>')<EOL><DEDENT><DEDENT>return (x, y)<EOL>
|
return the normalized the cursor position.
|
f3164:c1:m3
|
def set_mode(self, mode):
|
MODES = ['<STR_LIT:error>', '<STR_LIT>']<EOL>if mode.lower() not in MODES:<EOL><INDENT>raise TDLError('<STR_LIT>' % (MODES, repr(mode)))<EOL><DEDENT>self._scrollMode = mode.lower()<EOL>
|
Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
|
f3164:c1:m4
|
def set_colors(self, fg=None, bg=None):
|
if fg is not None:<EOL><INDENT>self._fg = _format_color(fg, self._fg)<EOL><DEDENT>if bg is not None:<EOL><INDENT>self._bg = _format_color(bg, self._bg)<EOL><DEDENT>
|
Sets the colors to be used with the L{print_str} and draw_* methods.
Values of None will only leave the current values unchanged.
Args:
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
.. seealso:: :any:`move`, :any:`print_str`
|
f3164:c1:m5
|
def print_str(self, string):
|
x, y = self._cursor<EOL>for char in string:<EOL><INDENT>if char == '<STR_LIT:\n>': <EOL><INDENT>x = <NUM_LIT:0><EOL>y += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if char == '<STR_LIT:\r>': <EOL><INDENT>x = <NUM_LIT:0><EOL>continue<EOL><DEDENT>x, y = self._normalizeCursor(x, y)<EOL>self.draw_char(x, y, char, self._fg, self._bg)<EOL>x += <NUM_LIT:1><EOL><DEDENT>self._cursor = (x, y)<EOL>
|
Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
|
f3164:c1:m6
|
def write(self, string):
|
<EOL>x, y = self._normalizeCursor(*self._cursor)<EOL>width, height = self.get_size()<EOL>wrapper = _textwrap.TextWrapper(initial_indent=('<STR_LIT:U+0020>'*x), width=width)<EOL>writeLines = []<EOL>for line in string.split('<STR_LIT:\n>'):<EOL><INDENT>if line:<EOL><INDENT>writeLines += wrapper.wrap(line)<EOL>wrapper.initial_indent = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>writeLines.append([])<EOL><DEDENT><DEDENT>for line in writeLines:<EOL><INDENT>x, y = self._normalizeCursor(x, y)<EOL>self.draw_str(x, y, line[x:], self._fg, self._bg)<EOL>y += <NUM_LIT:1><EOL>x = <NUM_LIT:0><EOL><DEDENT>y -= <NUM_LIT:1><EOL>self._cursor = (x, y)<EOL>
|
This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
|
f3164:c1:m7
|
def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis):
|
<EOL>_put_char_ex(self.console_c, x, y, _format_char(char),<EOL>_format_color(fg, self._fg), _format_color(bg, self._bg), <NUM_LIT:1>)<EOL>
|
Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
|
f3164:c1:m8
|
def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):
|
x, y = self._normalizePoint(x, y)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>width, height = self.get_size()<EOL>def _drawStrGen(x=x, y=y, string=string, width=width, height=height):<EOL><INDENT>"""<STR_LIT>"""<EOL>for char in _format_str(string):<EOL><INDENT>if y == height:<EOL><INDENT>raise TDLError('<STR_LIT>')<EOL><DEDENT>yield((x, y), char)<EOL>x += <NUM_LIT:1> <EOL>if x == width: <EOL><INDENT>x = <NUM_LIT:0><EOL>y += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>self._set_batch(_drawStrGen(), fg, bg)<EOL>
|
Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
|
f3164:c1:m9
|
def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
|
x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>char = _format_char(string)<EOL>grid = _itertools.product((x for x in range(x, x + width)),<EOL>(y for y in range(y, y + height)))<EOL>batch = zip(grid, _itertools.repeat(char, width * height))<EOL>self._set_batch(batch, fg, bg, nullChar=(char is None))<EOL>
|
Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
|
f3164:c1:m10
|
def draw_frame(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
|
x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>char = _format_char(string)<EOL>if width == <NUM_LIT:1> or height == <NUM_LIT:1>: <EOL><INDENT>return self.draw_rect(x, y, width, height, char, fg, bg)<EOL><DEDENT>self.draw_rect(x, y, <NUM_LIT:1>, height, char, fg, bg)<EOL>self.draw_rect(x, y, width, <NUM_LIT:1>, char, fg, bg)<EOL>self.draw_rect(x + width - <NUM_LIT:1>, y, <NUM_LIT:1>, height, char, fg, bg)<EOL>self.draw_rect(x, y + height - <NUM_LIT:1>, width, <NUM_LIT:1>, char, fg, bg)<EOL>
|
Similar to L{draw_rect} but only draws the outline of the rectangle.
`width or `height` can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
Args:
x (int): The x-coordinate to start on.
y (int): The y-coordinate to start on.
width (Optional[int]): Width of the rectangle.
height (Optional[int]): Height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set this parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`draw_rect`, :any:`Window`
|
f3164:c1:m11
|
def blit(self, source, x=<NUM_LIT:0>, y=<NUM_LIT:0>, width=None, height=None, srcX=<NUM_LIT:0>, srcY=<NUM_LIT:0>,<EOL>fg_alpha=<NUM_LIT:1.0>, bg_alpha=<NUM_LIT:1.0>):
|
assert isinstance(source, (Console, Window)), "<STR_LIT>"<EOL>x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)<EOL>srcX, srcY = source._translate(srcX, srcY)<EOL>source = source.console<EOL>x, y = self._translate(x, y)<EOL>self = self.console<EOL>if self == source:<EOL><INDENT>tmp = Console(width, height)<EOL>_lib.TCOD_console_blit(source.console_c,<EOL>srcX, srcY, width, height,<EOL>tmp.console_c, <NUM_LIT:0>, <NUM_LIT:0>, fg_alpha, bg_alpha)<EOL>_lib.TCOD_console_blit(tmp.console_c, <NUM_LIT:0>, <NUM_LIT:0>, width, height,<EOL>self.console_c, x, y, fg_alpha, bg_alpha)<EOL><DEDENT>else:<EOL><INDENT>_lib.TCOD_console_blit(source.console_c,<EOL>srcX, srcY, width, height,<EOL>self.console_c, x, y, fg_alpha, bg_alpha)<EOL><DEDENT>
|
Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
|
f3164:c1:m12
|
def get_cursor(self):
|
x, y = self._cursor<EOL>width, height = self.parent.get_size()<EOL>while x >= width:<EOL><INDENT>x -= width<EOL>y += <NUM_LIT:1><EOL><DEDENT>if y >= height and self.scrollMode == '<STR_LIT>':<EOL><INDENT>y = height - <NUM_LIT:1><EOL><DEDENT>return x, y<EOL>
|
Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
|
f3164:c1:m13
|
def get_size(self):
|
return self.width, self.height<EOL>
|
Return the size of the console as (width, height)
Returns:
Tuple[int, int]: A (width, height) tuple.
|
f3164:c1:m14
|
def __iter__(self):
|
return _itertools.product(range(self.width), range(self.height))<EOL>
|
Return an iterator with every possible (x, y) value for this console.
It goes without saying that working on the console this way is a
slow process, especially for Python, and should be minimized.
Returns:
Iterator[Tuple[int, int]]: An ((x, y), ...) iterator.
|
f3164:c1:m15
|
def move(self, x, y):
|
self._cursor = self._normalizePoint(x, y)<EOL>
|
Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
|
f3164:c1:m16
|
def scroll(self, x, y):
|
assert isinstance(x, _INTTYPES), "<STR_LIT>" % repr(x)<EOL>assert isinstance(y, _INTTYPES), "<STR_LIT>" % repr(x)<EOL>def getSlide(x, length):<EOL><INDENT>"""<STR_LIT>"""<EOL>if x > <NUM_LIT:0>:<EOL><INDENT>srcx = <NUM_LIT:0><EOL>length -= x<EOL><DEDENT>elif x < <NUM_LIT:0>:<EOL><INDENT>srcx = abs(x)<EOL>x = <NUM_LIT:0><EOL>length -= srcx<EOL><DEDENT>else:<EOL><INDENT>srcx = <NUM_LIT:0><EOL><DEDENT>return x, length, srcx<EOL><DEDENT>def getCover(x, length):<EOL><INDENT>"""<STR_LIT>"""<EOL>cover = (<NUM_LIT:0>, length) <EOL>uncover = None <EOL>if x > <NUM_LIT:0>: <EOL><INDENT>cover = (x, length - x)<EOL>uncover = (<NUM_LIT:0>, x)<EOL><DEDENT>elif x < <NUM_LIT:0>: <EOL><INDENT>x = abs(x)<EOL>cover = (<NUM_LIT:0>, length - x)<EOL>uncover = (length - x, x)<EOL><DEDENT>return cover, uncover<EOL><DEDENT>width, height = self.get_size()<EOL>if abs(x) >= width or abs(y) >= height:<EOL><INDENT>return self.clear() <EOL><DEDENT>coverX, uncoverX = getCover(x, width)<EOL>coverY, uncoverY = getCover(y, height)<EOL>x, width, srcx = getSlide(x, width)<EOL>y, height, srcy = getSlide(y, height)<EOL>self.blit(self, x, y, width, height, srcx, srcy)<EOL>if uncoverX: <EOL><INDENT>self.draw_rect(uncoverX[<NUM_LIT:0>], coverY[<NUM_LIT:0>], uncoverX[<NUM_LIT:1>], coverY[<NUM_LIT:1>],<EOL><NUM_LIT>, self._fg, self._bg)<EOL><DEDENT>if uncoverY: <EOL><INDENT>self.draw_rect(coverX[<NUM_LIT:0>], uncoverY[<NUM_LIT:0>], coverX[<NUM_LIT:1>], uncoverY[<NUM_LIT:1>],<EOL><NUM_LIT>, self._fg, self._bg)<EOL><DEDENT>if uncoverX and uncoverY: <EOL><INDENT>self.draw_rect(uncoverX[<NUM_LIT:0>], uncoverY[<NUM_LIT:0>], uncoverX[<NUM_LIT:1>], uncoverY[<NUM_LIT:1>],<EOL><NUM_LIT>, self._fg, self._bg)<EOL><DEDENT>
|
Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
|
f3164:c1:m17
|
def clear(self, fg=Ellipsis, bg=Ellipsis):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Clears the entire L{Console}/L{Window}.
Unlike other drawing functions, fg and bg can not be None.
Args:
fg (Union[Tuple[int, int, int], int, Ellipsis])
bg (Union[Tuple[int, int, int], int, Ellipsis])
.. seealso:: :any:`draw_rect`
|
f3164:c1:m18
|
def get_char(self, x, y):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Return the character and colors of a tile as (ch, fg, bg)
This method runs very slowly as is not recommended to be called
frequently.
Args:
x (int): The x-coordinate to pick.
y (int): The y-coordinate to pick.
Returns:
Tuple[int, Tuple[int, int, int], Tuple[int, int, int]]: A 3-item
tuple: `(int, fg, bg)`
The first item is an integer of the
character at the position (x, y) the second and third are the
foreground and background colors respectfully.
.. seealso:: :any:`draw_char`
|
f3164:c1:m19
|
def __contains__(self, position):
|
x, y = position<EOL>return (<NUM_LIT:0> <= x < self.width) and (<NUM_LIT:0> <= y < self.height)<EOL>
|
Use ``((x, y) in console)`` to check if a position is drawable on
this console.
|
f3164:c1:m20
|
@classmethod<EOL><INDENT>def _newConsole(cls, console):<DEDENT>
|
self = cls.__new__(cls)<EOL>_BaseConsole.__init__(self)<EOL>self.console_c = console<EOL>self.console = self<EOL>self.width = _lib.TCOD_console_get_width(console)<EOL>self.height = _lib.TCOD_console_get_height(console)<EOL>return self<EOL>
|
Make a Console instance, from a console ctype
|
f3164:c2:m3
|
def _root_unhook(self):
|
global _rootinitialized, _rootConsoleRef<EOL>if(_rootConsoleRef and _rootConsoleRef() is self):<EOL><INDENT>unhooked = _lib.TCOD_console_new(self.width, self.height)<EOL>_lib.TCOD_console_blit(self.console_c,<EOL><NUM_LIT:0>, <NUM_LIT:0>, self.width, self.height,<EOL>unhooked, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>_rootinitialized = False<EOL>_rootConsoleRef = None<EOL>_lib.TCOD_console_delete(self.console_c)<EOL>self.console_c = unhooked<EOL><DEDENT>
|
Change this root console into a normal Console object and
delete the root console from TCOD
|
f3164:c2:m4
|
def __del__(self):
|
if self.console_c is None:<EOL><INDENT>return <EOL><DEDENT>if self.console_c is _ffi.NULL:<EOL><INDENT>self._root_unhook() <EOL>return<EOL><DEDENT>_lib.TCOD_console_delete(self.console_c)<EOL>self.console_c = None<EOL>
|
If the main console is garbage collected then the window will be closed as well
|
f3164:c2:m5
|
@staticmethod<EOL><INDENT>def _translate(x, y):<DEDENT>
|
return x, y<EOL>
|
Convertion x and y to their position on the root Console for this Window
Because this is a Console instead of a Window we return the paramaters
untouched
|
f3164:c2:m9
|
def _set_char(self, x, y, char, fg=None, bg=None,<EOL>bgblend=_lib.TCOD_BKGND_SET):
|
<EOL>return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend)<EOL>
|
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this.
|
f3164:c2:m11
|
def _set_batch(self, batch, fg, bg, bgblend=<NUM_LIT:1>, nullChar=False):
|
for (x, y), char in batch:<EOL><INDENT>self._set_char(x, y, char, fg, bg, bgblend)<EOL><DEDENT>
|
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.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
|
f3164:c2:m12
|
def _translate(self, x, y):
|
<EOL>return self.parent._translate((x + self.x), (y + self.y))<EOL>
|
Convertion x and y to their position on the root Console
|
f3164:c3:m1
|
def get_point(self, *position):
|
<EOL>array = _ffi.new(self._arrayType, position)<EOL>if self._useOctaves:<EOL><INDENT>return (self._noiseFunc(self._noise, array, self._octaves) + <NUM_LIT:1>) * <NUM_LIT:0.5><EOL><DEDENT>return (self._noiseFunc(self._noise, array) + <NUM_LIT:1>) * <NUM_LIT:0.5><EOL>
|
Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range.
|
f3165:c0:m4
|
def _parseKeyNames(lib):
|
_keyNames = {}<EOL>for attr in dir(lib): <EOL><INDENT>if attr[:<NUM_LIT:6>] == '<STR_LIT>': <EOL><INDENT>_keyNames[getattr(lib, attr)] = attr[<NUM_LIT:6>:] <EOL><DEDENT><DEDENT>return _keyNames<EOL>
|
returns a dictionary mapping of human readable key names to their keycodes
this parses constants with the names of K_* and makes code=name pairs
this is for KeyEvent.key variable and that enables things like:
if (event.key == 'PAGEUP'):
|
f3166:m0
|
def _processEvents():
|
global _mousel, _mousem, _mouser, _eventsflushed, _pushedEvents<EOL>_eventsflushed = True<EOL>events = _pushedEvents <EOL>_pushedEvents = [] <EOL>mouse = _ffi.new('<STR_LIT>')<EOL>libkey = _ffi.new('<STR_LIT>')<EOL>while <NUM_LIT:1>:<EOL><INDENT>libevent = _lib.TCOD_sys_check_for_event(_lib.TCOD_EVENT_ANY, libkey, mouse)<EOL>if not libevent: <EOL><INDENT>break<EOL><DEDENT>if libevent & _lib.TCOD_EVENT_MOUSE_MOVE:<EOL><INDENT>events.append(MouseMotion((mouse.x, mouse.y),<EOL>(mouse.cx, mouse.cy),<EOL>(mouse.dx, mouse.dy),<EOL>(mouse.dcx, mouse.dcy)))<EOL><DEDENT>mousepos = ((mouse.x, mouse.y), (mouse.cx, mouse.cy))<EOL>for oldstate, newstate, released, button inzip((_mousel, _mousem, _mouser),<EOL>(mouse.lbutton, mouse.mbutton, mouse.rbutton),<EOL>(mouse.lbutton_pressed, mouse.mbutton_pressed,<EOL>mouse.rbutton_pressed),<EOL>(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>)):<EOL><INDENT>if released:<EOL><INDENT>if not oldstate:<EOL><INDENT>events.append(MouseDown(button, *mousepos))<EOL><DEDENT>events.append(MouseUp(button, *mousepos))<EOL>if newstate:<EOL><INDENT>events.append(MouseDown(button, *mousepos))<EOL><DEDENT><DEDENT>elif newstate and not oldstate:<EOL><INDENT>events.append(MouseDown(button, *mousepos))<EOL><DEDENT><DEDENT>if mouse.wheel_up:<EOL><INDENT>events.append(MouseDown(<NUM_LIT:4>, *mousepos))<EOL><DEDENT>if mouse.wheel_down:<EOL><INDENT>events.append(MouseDown(<NUM_LIT:5>, *mousepos))<EOL><DEDENT>_mousel = mouse.lbutton<EOL>_mousem = mouse.mbutton<EOL>_mouser = mouse.rbutton<EOL>if libkey.vk == _lib.TCODK_NONE:<EOL><INDENT>break<EOL><DEDENT>if libkey.pressed:<EOL><INDENT>keyevent = KeyDown<EOL><DEDENT>else:<EOL><INDENT>keyevent = KeyUp<EOL><DEDENT>events.append(<EOL>keyevent(<EOL>libkey.vk,<EOL>libkey.c.decode('<STR_LIT:ascii>', errors='<STR_LIT:ignore>'),<EOL>_ffi.string(libkey.text).decode('<STR_LIT:utf-8>'),<EOL>libkey.shift,<EOL>libkey.lalt,<EOL>libkey.ralt,<EOL>libkey.lctrl,<EOL>libkey.rctrl,<EOL>libkey.lmeta,<EOL>libkey.rmeta,<EOL>)<EOL>)<EOL><DEDENT>if _lib.TCOD_console_is_window_closed():<EOL><INDENT>events.append(Quit())<EOL><DEDENT>_eventQueue.extend(events)<EOL>
|
Flushes the event queue from libtcod into the global list _eventQueue
|
f3166:m1
|
def get():
|
_processEvents()<EOL>return _event_generator()<EOL>
|
Flushes the event queue and returns the list of events.
This function returns :any:`Event` objects that can be identified by their
type attribute or their class.
Returns: Iterator[Type[Event]]: An iterable of Events or anything
put in a :any:`push` call.
If the iterator is deleted or otherwise interrupted before finishing
the excess items are preserved for the next call.
|
f3166:m2
|
def wait(timeout=None, flush=True):
|
if timeout is not None:<EOL><INDENT>timeout = timeout + _time.clock() <EOL><DEDENT>while True:<EOL><INDENT>if _eventQueue:<EOL><INDENT>return _eventQueue.pop(<NUM_LIT:0>)<EOL><DEDENT>if flush:<EOL><INDENT>_tdl.flush()<EOL><DEDENT>if timeout and _time.clock() >= timeout:<EOL><INDENT>return None <EOL><DEDENT>_time.sleep(<NUM_LIT>) <EOL>_processEvents()<EOL><DEDENT>
|
Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out.
Anything added via :any:`push` will also be returned.
|
f3166:m4
|
def push(event):
|
_pushedEvents.append(event)<EOL>
|
Push an event into the event buffer.
Args:
event (Any): This event will be available on the next call to
:any:`event.get`.
An event pushed in the middle of a :any:`get` will not show until
the next time :any:`get` called preventing push related
infinite loops.
This object should at least have a 'type' attribute.
|
f3166:m5
|
def key_wait():
|
while <NUM_LIT:1>:<EOL><INDENT>for event in get():<EOL><INDENT>if event.type == '<STR_LIT>':<EOL><INDENT>return event<EOL><DEDENT>if event.type == '<STR_LIT>':<EOL><INDENT>return KeyDown('<STR_LIT>', '<STR_LIT>', True, False, True, False, False)<EOL><DEDENT><DEDENT>_time.sleep(<NUM_LIT>)<EOL><DEDENT>
|
Waits until the user presses a key.
Then returns a :any:`KeyDown` event.
Key events will repeat if held down.
A click to close the window will be converted into an Alt+F4 KeyDown event.
Returns:
tdl.event.KeyDown: The pressed key.
|
f3166:m6
|
def set_key_repeat(delay=<NUM_LIT>, interval=<NUM_LIT:0>):
|
pass<EOL>
|
Does nothing.
|
f3166:m7
|
def is_window_closed():
|
return _lib.TCOD_console_is_window_closed()<EOL>
|
Returns True if the exit button on the window has been clicked and
stays True afterwards.
Returns: bool:
|
f3166:m8
|
def __repr__(self):
|
attrdict = {}<EOL>for varname in dir(self):<EOL><INDENT>if '<STR_LIT:_>' == varname[<NUM_LIT:0>]:<EOL><INDENT>continue<EOL><DEDENT>attrdict[varname] = self.__getattribute__(varname)<EOL><DEDENT>return '<STR_LIT>' % (self.__class__.__name__, repr(attrdict))<EOL>
|
List an events public attributes when printed.
|
f3166:c0:m0
|
def ev_QUIT(self, event):
|
raise SystemExit()<EOL>
|
Unless overridden this method raises a SystemExit exception closing
the program.
|
f3166:c9:m0
|
def ev_KEYDOWN(self, event):
|
Override this method to handle a :any:`KeyDown` event.
|
f3166:c9:m1
|
|
def ev_KEYUP(self, event):
|
Override this method to handle a :any:`KeyUp` event.
|
f3166:c9:m2
|
|
def ev_MOUSEDOWN(self, event):
|
Override this method to handle a :any:`MouseDown` event.
|
f3166:c9:m3
|
|
def ev_MOUSEUP(self, event):
|
Override this method to handle a :any:`MouseUp` event.
|
f3166:c9:m4
|
|
def ev_MOUSEMOTION(self, event):
|
Override this method to handle a :any:`MouseMotion` event.
|
f3166:c9:m5
|
|
def update(self, deltaTime):
|
pass<EOL>
|
Override this method to handle per frame logic and drawing.
Args:
deltaTime (float):
This parameter tells the amount of time passed since
the last call measured in seconds as a floating point
number.
You can use this variable to make your program
frame rate independent.
Use this parameter to adjust the speed of motion,
timers, and other game logic.
|
f3166:c9:m6
|
def suspend(self):
|
self.__running = False<EOL>
|
When called the App will begin to return control to where
:any:`App.run` was called.
Some further events are processed and the :any:`App.update` method
will be called one last time before exiting
(unless suspended during a call to :any:`App.update`.)
|
f3166:c9:m7
|
def run(self):
|
if getattr(self, '<STR_LIT>', False):<EOL><INDENT>raise _tdl.TDLError('<STR_LIT>')<EOL><DEDENT>self.__running = True<EOL>while self.__running:<EOL><INDENT>self.runOnce()<EOL><DEDENT>
|
Delegate control over to this App instance. This function will
process all events and send them to the special methods ev_* and key_*.
A call to :any:`App.suspend` will return the control flow back to where
this function is called. And then the App can be run again.
But a single App instance can not be run multiple times simultaneously.
|
f3166:c9:m8
|
def run_once(self):
|
if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.__prevTime = _time.clock() <EOL><DEDENT>for event in get():<EOL><INDENT>if event.type: <EOL><INDENT>method = '<STR_LIT>' % event.type <EOL>getattr(self, method)(event)<EOL><DEDENT>if event.type == '<STR_LIT>':<EOL><INDENT>method = '<STR_LIT>' % event.key <EOL>if hasattr(self, method): <EOL><INDENT>getattr(self, method)(event)<EOL><DEDENT><DEDENT><DEDENT>newTime = _time.clock()<EOL>self.update(newTime - self.__prevTime)<EOL>self.__prevTime = newTime<EOL>
|
Pump events to this App instance and then return.
This works in the way described in :any:`App.run` except it immediately
returns after the first :any:`update` call.
Having multiple :any:`App` instances and selectively calling runOnce on
them is a decent way to create a state machine.
|
f3166:c9:m9
|
def __init__(self, data, bbox):
|
if verbose:<EOL><INDENT>print(data)<EOL><DEDENT>self.encoding = int(re.search('<STR_LIT>', data).groups()[<NUM_LIT:0>])<EOL>if self.encoding < <NUM_LIT:0>:<EOL><INDENT>self.encoding += <NUM_LIT> <EOL><DEDENT>match = re.search('<STR_LIT>', data)<EOL>if match:<EOL><INDENT>gbbox = [int(i) for i in match.groups()]<EOL><DEDENT>else:<EOL><INDENT>gbbox = bbox<EOL><DEDENT>self.font_bbox = bbox<EOL>self.bbox = gbbox<EOL>self.width, self.height = self.bbox[:<NUM_LIT:2>]<EOL>match = re.search('<STR_LIT>', data, re.IGNORECASE)<EOL>self.bitmap = numpy.empty([self.height, self.width], bool)<EOL>if self.height == self.width == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>for y,hexcode in enumerate(match.groups()[<NUM_LIT:0>].split('<STR_LIT:\n>')):<EOL><INDENT>for x, bit in self.parseBits(hexcode, self.width):<EOL><INDENT>self.bitmap[y,x] = bit<EOL><DEDENT><DEDENT>self.sizeAdjust()<EOL>
|
Make a new glyph with the data between STARTCHAR and ENDCHAR
|
f3167:c0:m0
|
def sizeAdjust(self):
|
font_width, font_height = self.font_bbox[:<NUM_LIT:2>]<EOL>self.width = min(self.width, font_width)<EOL>self.height = min(self.height, font_height)<EOL>self.bbox[:<NUM_LIT:2>] = self.width, self.height<EOL>self.crop()<EOL>
|
If the glyph is bigger than the font (because the user set it smaller)
this should be able to shorten the size
|
f3167:c0:m1
|
def blit(self, image, x, y):
|
<EOL>x += self.font_bbox[<NUM_LIT:2>] - self.bbox[<NUM_LIT:2>]<EOL>y += self.font_bbox[<NUM_LIT:3>] - self.bbox[<NUM_LIT:3>]<EOL>x += self.font_bbox[<NUM_LIT:0>] - self.bbox[<NUM_LIT:0>]<EOL>y += self.font_bbox[<NUM_LIT:1>] - self.bbox[<NUM_LIT:1>]<EOL>image[y:y+self.height, x:x+self.width] = self.bitmap * <NUM_LIT:255><EOL>
|
blit to the image array
|
f3167:c0:m4
|
def parseBits(self, hexcode, width):
|
bitarray = []<EOL>for byte in hexcode[::-<NUM_LIT:1>]:<EOL><INDENT>bits = int(byte, <NUM_LIT:16>)<EOL>for x in range(<NUM_LIT:4>):<EOL><INDENT>bitarray.append(bool((<NUM_LIT:2> ** x) & bits))<EOL><DEDENT><DEDENT>bitarray = bitarray[::-<NUM_LIT:1>]<EOL>return enumerate(bitarray[:width])<EOL>
|
enumerate over bits in a line of data
|
f3167:c0:m5
|
def seen_nonce(id, nonce, timestamp):
|
key = '<STR_LIT>'.format(id=id, n=nonce, ts=timestamp)<EOL>if cache.get(key):<EOL><INDENT>log.warning('<STR_LIT>'<EOL>.format(k=key))<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>'.format(k=key))<EOL>cache.set(key, True,<EOL>timeout=getattr(settings, '<STR_LIT>',<EOL>default_message_expiration) + <NUM_LIT:5>)<EOL>return False<EOL><DEDENT>
|
Returns True if the Hawk nonce has been seen already.
|
f3178:m2
|
def __init__(self, word, acc):
|
self.word = self.__work_word = word.lower().strip()<EOL>if not self.word:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>_sylls = self.get_sylls()<EOL>if not _sylls:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.acc = int(acc)<EOL>if not (<NUM_LIT:0> < self.acc <= _sylls):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.replace_ends()<EOL>for old, new in sorted(<EOL>self.replace_map.items(),<EOL>key=lambda x: len(x[<NUM_LIT:0>]),<EOL>reverse=True<EOL>):<EOL><INDENT>self.__work_word = self.__work_word.replace(old, new)<EOL><DEDENT>
|
:word: Слово для разбора.
:acc: Номер ударного слога.
|
f3184:c0:m0
|
def __init__(self, letter, prev_letter=None, shock=False):
|
if prev_letter is not None:<EOL><INDENT>if not isinstance(prev_letter, self.__class__):<EOL><INDENT>raise Exception(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(self.__class__, prev_letter.__class__)<EOL>)<EOL><DEDENT><DEDENT>self.__letter = letter.lower().strip()<EOL>self.__prev_letter = prev_letter<EOL>if len(self.__letter) != <NUM_LIT:1>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if not (self.is_vowel() or self.is_consonant() or self.is_mark()):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.__shock = (self.is_vowel() if shock else False)<EOL>self.__forced_hard = None<EOL>self.__forsed_sonorus = None<EOL>self._forced_not_show = False<EOL>self._is_double = False<EOL>self.set_prev_sonorus()<EOL>self.set_prev_hard()<EOL>self.set_double_sound()<EOL>
|
:letter:
Сама буква.
:prev_letter:
Предыдущая буква в слове, если есть.
:shock:
Если гласная, то ударная ли.
|
f3184:c1:m0
|
def set_prev_sonorus(self):
|
prev = self.get_prev_letter()<EOL>if not prev:<EOL><INDENT>return<EOL><DEDENT>if not (self.is_consonant() and prev.is_consonant()):<EOL><INDENT>return<EOL><DEDENT>if self.is_sonorus() and self.is_paired_consonant():<EOL><INDENT>if self._get_sound(False) != '<STR_LIT>':<EOL><INDENT>prev.set_sonorus(True)<EOL><DEDENT>return<EOL><DEDENT>if self.is_deaf():<EOL><INDENT>prev.set_sonorus(False)<EOL>return<EOL><DEDENT>
|
Выставляет параметры звонкости/глухости, для предыдущих согласных.
|
f3184:c1:m2
|
def set_prev_hard(self):
|
prev = self.get_prev_letter()<EOL>if not prev:<EOL><INDENT>return<EOL><DEDENT>if not prev.is_consonant():<EOL><INDENT>return<EOL><DEDENT>if self.is_softener(prev):<EOL><INDENT>prev.set_hard(False)<EOL><DEDENT>elif self.letter in self.vovels_set_hard:<EOL><INDENT>prev.set_hard(True)<EOL><DEDENT>
|
Выставляет параметры твёрдости/мягкости, для предыдущих согласных.
|
f3184:c1:m3
|
def is_after_acc(self):
|
prev = self._prev_letter()<EOL>while True:<EOL><INDENT>if not prev:<EOL><INDENT>return False<EOL><DEDENT>if prev.is_shock():<EOL><INDENT>return True<EOL><DEDENT>prev = prev._prev_letter()<EOL><DEDENT>
|
Буква распологается после ударения.
|
f3184:c1:m4
|
def get_prev_letter(self):
|
prev = self._prev_letter()<EOL>while True:<EOL><INDENT>if not prev:<EOL><INDENT>return prev<EOL><DEDENT>if prev.letter in prev.marks:<EOL><INDENT>prev = prev._prev_letter()<EOL>continue<EOL><DEDENT>return prev<EOL><DEDENT>
|
Возвращает предыдущий объект буквы, если она не является знаком.
Если знак, то рекурсивно спускается, до ближайшей.
|
f3184:c1:m11
|
def _prev_letter(self):
|
return self.__prev_letter<EOL>
|
Возвращает предыдущую букву, без особых указаний.
|
f3184:c1:m12
|
def get_variant(self, return_deaf):
|
return_deaf = bool(return_deaf)<EOL>for variants in self.sonorus_deaf_pairs:<EOL><INDENT>if self.__letter in variants:<EOL><INDENT>return variants[return_deaf]<EOL><DEDENT><DEDENT>return self.__letter<EOL>
|
Возвращает вариант буквы.
:return_deaf:
True - вернуть глухой вариант. Если False - звонкий.
|
f3184:c1:m13
|
def is_paired_consonant(self):
|
if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>for variants in self.sonorus_deaf_pairs:<EOL><INDENT>if self.letter in variants:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Парная ли согласная.
|
f3184:c1:m14
|
def is_sonorus(self):
|
if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.forever_sonorus:<EOL><INDENT>return True<EOL><DEDENT>if self.letter in self.forever_deaf:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus:<EOL><INDENT>return True<EOL><DEDENT>if self.__forsed_sonorus is False:<EOL><INDENT>return False<EOL><DEDENT>for son, _ in self.sonorus_deaf_pairs:<EOL><INDENT>if self.letter == son:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Звонкая ли согласная.
|
f3184:c1:m15
|
def is_deaf(self):
|
if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.forever_deaf:<EOL><INDENT>return True<EOL><DEDENT>if self.letter in self.forever_sonorus:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus is False:<EOL><INDENT>return True<EOL><DEDENT>for _, df in self.sonorus_deaf_pairs:<EOL><INDENT>if self.letter == df:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Глухая ли согласная.
|
f3184:c1:m16
|
def end(self, string):
|
prev = self._prev_letter()<EOL>for s in reversed(string):<EOL><INDENT>if prev.letter != s:<EOL><INDENT>return False<EOL><DEDENT>if not prev:<EOL><INDENT>return False<EOL><DEDENT>prev = prev._prev_letter()<EOL><DEDENT>return True<EOL>
|
Проверяет, заканчивается ли последовательность букв переданной строкой.
Скан производится, без учёта текущей.
|
f3184:c1:m19
|
def is_softener(self, let):
|
if let.letter in let.forever_hard:<EOL><INDENT>return False<EOL><DEDENT>if not let.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.vovels_set_soft:<EOL><INDENT>return True<EOL><DEDENT>if self.letter == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>if self.is_soft() and (let.letter in "<STR_LIT>"):<EOL><INDENT>return True<EOL><DEDENT>if self.letter == '<STR_LIT>':<EOL><INDENT>if self.end("<STR_LIT>") or self.end("<STR_LIT>") or self.end("<STR_LIT>"):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Является ли символ смягчающим.
:let: Объект буквы, которую пытаемся смягчить.
|
f3184:c1:m20
|
def encrypt(data, key):
|
data = __tobytes(data)<EOL>data_len = len(data)<EOL>data = ffi.from_buffer(data)<EOL>key = ffi.from_buffer(__tobytes(key))<EOL>out_len = ffi.new('<STR_LIT>')<EOL>result = lib.xxtea_encrypt(data, data_len, key, out_len)<EOL>ret = ffi.buffer(result, out_len[<NUM_LIT:0>])[:]<EOL>lib.free(result)<EOL>return ret<EOL>
|
encrypt the data with the key
|
f3188:m0
|
def decrypt(data, key):
|
data_len = len(data)<EOL>data = ffi.from_buffer(data)<EOL>key = ffi.from_buffer(__tobytes(key))<EOL>out_len = ffi.new('<STR_LIT>')<EOL>result = lib.xxtea_decrypt(data, data_len, key, out_len)<EOL>ret = ffi.buffer(result, out_len[<NUM_LIT:0>])[:]<EOL>lib.free(result)<EOL>return ret<EOL>
|
decrypt the data with the key
|
f3188:m1
|
def decrypt_utf8(data, key):
|
return decrypt(data, key).decode('<STR_LIT:utf-8>')<EOL>
|
decrypt the data with the key to string
|
f3188:m2
|
def eq(self, lilypond, answer):
|
result = parse(lilypond)<EOL>self.assertEqual(len(answer), len(result))<EOL>for i, event in enumerate(answer):<EOL><INDENT>r = result[i].tuple(OFFSET_64, MIDI_PITCH, DURATION_64)<EOL>self.assertEqual(event, r)<EOL><DEDENT>
|
The first is a lilypond fragment. The second is
the intended interpretation, a sequence of (offset, pitch, duration) tuples
where offset and duration are in multiples of a 64th note and pitch is MIDI
note number.
|
f3195:c0:m0
|
def alberti(triad):
|
return HSeq(triad[i] for i in [<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>])<EOL>
|
takes a VSeq of 3 notes and returns an HSeq of those notes in an
alberti figuration.
|
f3197:m0
|
@transform_sequence<EOL>def arpeggio(pattern, point):
|
point['<STR_LIT>'] = HSeq(point['<STR_LIT>'][i] for i in pattern)<EOL>return point<EOL>
|
turns each subsequence into an arpeggio matching the given ``pattern``.
|
f3204:m2
|
@transform_sequence<EOL>def fill(duration, point):
|
point['<STR_LIT>'] = point['<STR_LIT>'] * (point[DURATION_64] / (<NUM_LIT:8> * duration)) | add({DURATION_64: duration})<EOL>return point<EOL>
|
fills the subsequence of the point with repetitions of its subsequence and
sets the ``duration`` of each point.
|
f3204:m3
|
def expand(sequence):
|
expanse = []<EOL>for point in sequence:<EOL><INDENT>if '<STR_LIT>' in point:<EOL><INDENT>expanse.extend(expand(point['<STR_LIT>']))<EOL><DEDENT>else:<EOL><INDENT>expanse.append(point)<EOL><DEDENT><DEDENT>return sequence.__class__(expanse)<EOL>
|
expands a tree of sequences into a single, flat sequence, recursively.
|
f3204:m4
|
def debug(sequence):
|
points = []<EOL>for i, p in enumerate(sequence):<EOL><INDENT>copy = Point(p)<EOL>copy['<STR_LIT:index>'] = i<EOL>points.append(copy)<EOL><DEDENT>return sequence.__class__(points)<EOL>
|
adds information to the sequence for better debugging, currently only
an index property on each point in the sequence.
|
f3204:m5
|
def transform_sequence(f):
|
@wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return lambda seq: seq.map_points(partial(f, *args, **kwargs))<EOL><DEDENT>return wrapper<EOL>
|
A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument
|
f3210:m0
|
@transform_sequence<EOL>def transpose(interval, point):
|
if "<STR_LIT>" in point:<EOL><INDENT>point["<STR_LIT>"] = point["<STR_LIT>"] + interval<EOL><DEDENT>return point<EOL>
|
Transpose a point by an interval, using the Sebastian interval system
|
f3210:m4
|
def subseq(start_offset=<NUM_LIT:0>, end_offset=None):
|
def _(sequence):<EOL><INDENT>return sequence.subseq(start_offset, end_offset)<EOL><DEDENT>return _<EOL>
|
Return a portion of the input sequence
|
f3210:m8
|
@transform_sequence<EOL>def lilypond(point):
|
<EOL>if "<STR_LIT>" in point:<EOL><INDENT>return point<EOL><DEDENT>pitch_string = "<STR_LIT>"<EOL>octave_string = "<STR_LIT>"<EOL>duration_string = "<STR_LIT>"<EOL>preamble = "<STR_LIT>"<EOL>dynamic_string = "<STR_LIT>"<EOL>if "<STR_LIT>" in point:<EOL><INDENT>octave = point["<STR_LIT>"]<EOL>pitch = point["<STR_LIT>"]<EOL>if octave > <NUM_LIT:4>:<EOL><INDENT>octave_string = "<STR_LIT:'>" * (octave - <NUM_LIT:4>)<EOL><DEDENT>elif octave < <NUM_LIT:4>:<EOL><INDENT>octave_string = "<STR_LIT:U+002C>" * (<NUM_LIT:4> - octave)<EOL><DEDENT>else:<EOL><INDENT>octave_string = "<STR_LIT>"<EOL><DEDENT>m = modifiers(pitch)<EOL>if m > <NUM_LIT:0>:<EOL><INDENT>modifier_string = "<STR_LIT>" * m<EOL><DEDENT>elif m < <NUM_LIT:0>:<EOL><INDENT>modifier_string = "<STR_LIT>" * -m<EOL><DEDENT>else:<EOL><INDENT>modifier_string = "<STR_LIT>"<EOL><DEDENT>pitch_string = letter(pitch).lower() + modifier_string<EOL><DEDENT>if DURATION_64 in point:<EOL><INDENT>duration = point[DURATION_64]<EOL>if duration > <NUM_LIT:0>:<EOL><INDENT>if duration % <NUM_LIT:3> == <NUM_LIT:0>: <EOL><INDENT>duration_string = str(<NUM_LIT> // (<NUM_LIT:2> * duration)) + "<STR_LIT:.>"<EOL><DEDENT>else:<EOL><INDENT>duration_string = str(<NUM_LIT:64> // duration)<EOL><DEDENT><DEDENT>if duration_string:<EOL><INDENT>if not pitch_string:<EOL><INDENT>pitch_string = "<STR_LIT:c>"<EOL>octave_string = "<STR_LIT:'>"<EOL>preamble = r'<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>if "<STR_LIT>" in point:<EOL><INDENT>dynamic = point["<STR_LIT>"]<EOL>if dynamic == "<STR_LIT>":<EOL><INDENT>dynamic_string = "<STR_LIT>"<EOL><DEDENT>elif dynamic == "<STR_LIT>":<EOL><INDENT>dynamic_string = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>dynamic_string = "<STR_LIT>" % (dynamic,)<EOL><DEDENT><DEDENT>point["<STR_LIT>"] = "<STR_LIT>" % (preamble, pitch_string, octave_string, duration_string, dynamic_string)<EOL>return point<EOL>
|
Generate lilypond representation for a point
|
f3210:m11
|
def dynamics(start, end=None):
|
def _(sequence):<EOL><INDENT>if start in _dynamic_markers_to_velocity:<EOL><INDENT>start_velocity = _dynamic_markers_to_velocity[start]<EOL>start_marker = start<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % (start, _dynamic_markers_to_velocity.keys()))<EOL><DEDENT>if end is None:<EOL><INDENT>end_velocity = start_velocity<EOL>end_marker = start_marker<EOL><DEDENT>elif end in _dynamic_markers_to_velocity:<EOL><INDENT>end_velocity = _dynamic_markers_to_velocity[end]<EOL>end_marker = end<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % (start, _dynamic_markers_to_velocity.keys()))<EOL><DEDENT>retval = sequence.__class__([Point(point) for point in sequence._elements])<EOL>velocity_interval = (float(end_velocity) - float(start_velocity)) / (len(retval) - <NUM_LIT:1>) if len(retval) > <NUM_LIT:1> else <NUM_LIT:0><EOL>velocities = [int(start_velocity + velocity_interval * pos) for pos in range(len(retval))]<EOL>if start_velocity > end_velocity:<EOL><INDENT>retval[<NUM_LIT:0>]["<STR_LIT>"] = "<STR_LIT>"<EOL>retval[-<NUM_LIT:1>]["<STR_LIT>"] = end_marker<EOL><DEDENT>elif start_velocity < end_velocity:<EOL><INDENT>retval[<NUM_LIT:0>]["<STR_LIT>"] = "<STR_LIT>"<EOL>retval[-<NUM_LIT:1>]["<STR_LIT>"] = end_marker<EOL><DEDENT>else:<EOL><INDENT>retval[<NUM_LIT:0>]["<STR_LIT>"] = start_marker<EOL><DEDENT>for point, velocity in zip(retval, velocities):<EOL><INDENT>point["<STR_LIT>"] = velocity<EOL><DEDENT>return retval<EOL><DEDENT>return _<EOL>
|
Apply dynamics to a sequence. If end is specified, it will crescendo or diminuendo linearly from start to end dynamics.
You can pass any of these strings as dynamic markers: ['pppppp', 'ppppp', 'pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'f', 'ff', 'fff', ''ffff]
Args:
start: beginning dynamic marker, if no end is specified all notes will get this marker
end: ending dynamic marker, if unspecified the entire sequence will get the start dynamic marker
Example usage:
s1 | dynamics('p') # play a sequence in piano
s2 | dynamics('p', 'ff') # crescendo from p to ff
s3 | dynamics('ff', 'p') # diminuendo from ff to p
|
f3210:m12
|
def transform(self, func):
|
return func(self)<EOL>
|
applies function to a sequence to produce a new sequence
|
f3212:c2:m7
|
def zip(self, other):
|
return self.__class__(p1 % p2 for p1, p2 in zip(self, other))<EOL>
|
zips two sequences unifying the corresponding points.
|
f3212:c2:m8
|
def display(self, format="<STR_LIT>"):
|
from sebastian.core.transforms import lilypond<EOL>seq = HSeq(self) | lilypond()<EOL>lily_output = write_lilypond.lily_format(seq)<EOL>if not lily_output.strip():<EOL><INDENT>return self<EOL><DEDENT>if format == "<STR_LIT>":<EOL><INDENT>suffix = "<STR_LIT>"<EOL>args = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>elif format == "<STR_LIT>":<EOL><INDENT>suffix = "<STR_LIT>"<EOL>args = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>f = tempfile.NamedTemporaryFile(suffix=suffix)<EOL>basename = f.name[:-len(suffix)]<EOL>args.extend(["<STR_LIT>" + basename, "<STR_LIT:->"])<EOL>p = sp.Popen("<STR_LIT:U+0020>".join(args), stdin=sp.PIPE, shell=True)<EOL>stdout, stderr = p.communicate("<STR_LIT>" % lily_output)<EOL>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>if not ipython:<EOL><INDENT>return f.read()<EOL><DEDENT>if format == "<STR_LIT>":<EOL><INDENT>return Image(data=f.read(), filename=f.name, format="<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return SVG(data=f.read(), filename=f.name)<EOL><DEDENT>
|
Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg"
|
f3212:c2:m9
|
def append(self, point):
|
point = Point(point)<EOL>self._elements.append(point)<EOL>
|
appends a copy of the given point to this sequence
|
f3212:c3:m0
|
def concatenate(self, next_seq):
|
return HSeq(self._elements + next_seq._elements)<EOL>
|
concatenates two sequences to produce a new sequence
|
f3212:c3:m1
|
def repeat(self, count):
|
x = HSeq()<EOL>for i in range(count):<EOL><INDENT>x = x.concatenate(self)<EOL><DEDENT>return x<EOL>
|
repeat sequence given number of times to produce a new sequence
|
f3212:c3:m2
|
def subseq(self, start_offset=<NUM_LIT:0>, end_offset=None):
|
from sebastian.core import DURATION_64<EOL>def subseq_iter(start_offset, end_offset):<EOL><INDENT>cur_offset = <NUM_LIT:0><EOL>for point in self._elements:<EOL><INDENT>try:<EOL><INDENT>cur_offset += point[DURATION_64]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % DURATION_64)<EOL><DEDENT>if cur_offset < start_offset:<EOL><INDENT>continue<EOL><DEDENT>if end_offset is None or cur_offset < end_offset:<EOL><INDENT>yield point<EOL><DEDENT>else:<EOL><INDENT>raise StopIteration<EOL><DEDENT><DEDENT><DEDENT>return HSeq(subseq_iter(start_offset, end_offset))<EOL>
|
Return a subset of the sequence
starting at start_offset (defaulting to the beginning)
ending at end_offset (None representing the end, whih is the default)
Raises ValueError if duration_64 is missing on any element
|
f3212:c3:m3
|
def append(self, point):
|
point = Point(point)<EOL>self._elements.append(point)<EOL>
|
appends a copy of the given point to this sequence
|
f3212:c4:m0
|
def merge(self, parallel_seq):
|
return VSeq(self._elements + parallel_seq._elements)<EOL>
|
combine the points in two sequences
|
f3212:c4:m1
|
def write_meta_info(self, byte1, byte2, data):
|
write_varlen(self.data, <NUM_LIT:0>) <EOL>write_byte(self.data, byte1)<EOL>write_byte(self.data, byte2)<EOL>write_varlen(self.data, len(data))<EOL>write_chars(self.data, data)<EOL>
|
Worker method for writing meta info
|
f3217:c2:m1
|
def instrument(self, inst):
|
self.write_meta_info(<NUM_LIT>, <NUM_LIT>, inst)<EOL>
|
This works, but does not affect the 'instrument' used.
|
f3217:c2:m2
|
def set_range(self, accel=<NUM_LIT:1>, gyro=<NUM_LIT:1>):
|
self.i2c_write_register(<NUM_LIT>, accel)<EOL>self.i2c_write_register(<NUM_LIT>, gyro)<EOL>self.accel_range = accel<EOL>self.gyro_range = gyro<EOL>
|
Set the measurement range for the accel and gyro MEMS. Higher range means less resolution.
:param accel: a RANGE_ACCEL_* constant
:param gyro: a RANGE_GYRO_* constant
:Example:
.. code-block:: python
sensor = MPU6050I2C(gateway_class_instance)
sensor.set_range(
accel=MPU6050I2C.RANGE_ACCEL_2G,
gyro=MPU6050I2C.RANGE_GYRO_250DEG
)
|
f3219:c0:m1
|
def set_slave_bus_bypass(self, enable):
|
current = self.i2c_read_register(<NUM_LIT>, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if enable:<EOL><INDENT>current |= <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>current &= <NUM_LIT><EOL><DEDENT>self.i2c_write_register(<NUM_LIT>, current)<EOL>
|
Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly
Dont forget to use wakeup() or else the slave bus is unavailable
:param enable:
:return:
|
f3219:c0:m2
|
def wakeup(self):
|
self.i2c_write_register(<NUM_LIT>, <NUM_LIT>)<EOL>self.awake = True<EOL>
|
Wake the sensor from sleep.
|
f3219:c0:m3
|
def sleep(self):
|
self.i2c_write_register(<NUM_LIT>, <NUM_LIT>)<EOL>self.awake = False<EOL>
|
Put the sensor back to sleep.
|
f3219:c0:m4
|
def temperature(self):
|
if not self.awake:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>raw = self.i2c_read_register(<NUM_LIT>, <NUM_LIT:2>)<EOL>raw = struct.unpack('<STR_LIT>', raw)[<NUM_LIT:0>]<EOL>return round((raw / <NUM_LIT>) + <NUM_LIT>, <NUM_LIT:2>)<EOL>
|
Read the value for the internal temperature sensor.
:returns: Temperature in degree celcius as float
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.temperature()
49.38
|
f3219:c0:m5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.