Completed
Push — master ( e9e2ae...b6e5e0 )
by Kyle
01:34
created

console_fill_foreground()   D

Complexity

Conditions 8

Size

Total Lines 28

Duplication

Lines 28
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
c 2
b 0
f 0
dl 28
loc 28
rs 4
1
"""This module handles backward compatibility with the ctypes libtcodpy module.
2
"""
3
4
from __future__ import absolute_import as _
5
6
import threading as _threading
7
8
import numpy as _np
0 ignored issues
show
Configuration introduced by
The import numpy could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
9
10
from tcod.libtcod import *
0 ignored issues
show
Coding Style introduced by
The usage of wildcard imports like tcod.libtcod should generally be avoided.
Loading history...
Unused Code introduced by
FOV_PERMISSIVE was imported with wildcard, but is not used.
Loading history...
Unused Code introduced by
BKGND_ALPHA was imported with wildcard, but is not used.
Loading history...
Unused Code introduced by
BKGND_ADDALPHA was imported with wildcard, but is not used.
Loading history...
11
12
from tcod.tcod import _int, _unpack_char_p
13
from tcod.tcod import _bytes, _unicode, _fmt_bytes, _fmt_unicode
14
from tcod.tcod import _CDataWrapper
15
from tcod.tcod import _PropagateException
16
17
import tcod.bsp
18
from tcod.color import *
0 ignored issues
show
Coding Style introduced by
The usage of wildcard imports like tcod.color should generally be avoided.
Loading history...
19
import tcod.console
20
import tcod.image
21
import tcod.map
22
import tcod.noise
23
import tcod.path
24
import tcod.random
25
26
Bsp = tcod.bsp.BSP
27
28
29
class ConsoleBuffer(object):
30
    """Simple console that allows direct (fast) access to cells. simplifies
31
    use of the "fill" functions.
32
33
    Args:
34
        width (int): Width of the new ConsoleBuffer.
35
        height (int): Height of the new ConsoleBuffer.
36
        back_r (int): Red background color, from 0 to 255.
37
        back_g (int): Green background color, from 0 to 255.
38
        back_b (int): Blue background color, from 0 to 255.
39
        fore_r (int): Red foreground color, from 0 to 255.
40
        fore_g (int): Green foreground color, from 0 to 255.
41
        fore_b (int): Blue foreground color, from 0 to 255.
42
        char (AnyStr): A single character str or bytes object.
43
    """
44
    def __init__(self, width, height, back_r=0, back_g=0, back_b=0, fore_r=0, fore_g=0, fore_b=0, char=' '):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (108/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
45
        """initialize with given width and height. values to fill the buffer
46
        are optional, defaults to black with no characters.
47
        """
48
        n = width * height
0 ignored issues
show
Unused Code introduced by
The variable n seems to be unused.
Loading history...
49
        self.width = width
50
        self.height = height
51
        self.clear(back_r, back_g, back_b, fore_r, fore_g, fore_b, char)
52
53
    def clear(self, back_r=0, back_g=0, back_b=0, fore_r=0, fore_g=0, fore_b=0, char=' '):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (90/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
54
        """Clears the console.  Values to fill it with are optional, defaults
55
        to black with no characters.
56
57
        Args:
58
            back_r (int): Red background color, from 0 to 255.
59
            back_g (int): Green background color, from 0 to 255.
60
            back_b (int): Blue background color, from 0 to 255.
61
            fore_r (int): Red foreground color, from 0 to 255.
62
            fore_g (int): Green foreground color, from 0 to 255.
63
            fore_b (int): Blue foreground color, from 0 to 255.
64
            char (AnyStr): A single character str or bytes object.
65
        """
66
        n = self.width * self.height
67
        self.back_r = [back_r] * n
68
        self.back_g = [back_g] * n
69
        self.back_b = [back_b] * n
70
        self.fore_r = [fore_r] * n
71
        self.fore_g = [fore_g] * n
72
        self.fore_b = [fore_b] * n
73
        self.char = [ord(char)] * n
74
75
    def copy(self):
76
        """Returns a copy of this ConsoleBuffer.
77
78
        Returns:
79
            ConsoleBuffer: A new ConsoleBuffer copy.
80
        """
81
        other = ConsoleBuffer(0, 0)
82
        other.width = self.width
83
        other.height = self.height
84
        other.back_r = list(self.back_r)  # make explicit copies of all lists
0 ignored issues
show
Coding Style introduced by
The attribute back_r was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
85
        other.back_g = list(self.back_g)
0 ignored issues
show
Coding Style introduced by
The attribute back_g was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
86
        other.back_b = list(self.back_b)
0 ignored issues
show
Coding Style introduced by
The attribute back_b was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
87
        other.fore_r = list(self.fore_r)
0 ignored issues
show
Coding Style introduced by
The attribute fore_r was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
88
        other.fore_g = list(self.fore_g)
0 ignored issues
show
Coding Style introduced by
The attribute fore_g was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
89
        other.fore_b = list(self.fore_b)
0 ignored issues
show
Coding Style introduced by
The attribute fore_b was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
90
        other.char = list(self.char)
0 ignored issues
show
Coding Style introduced by
The attribute char was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
91
        return other
92
93
    def set_fore(self, x, y, r, g, b, char):
94
        """Set the character and foreground color of one cell.
95
96
        Args:
97
            x (int): X position to change.
98
            y (int): Y position to change.
99
            r (int): Red foreground color, from 0 to 255.
100
            g (int): Green foreground color, from 0 to 255.
101
            b (int): Blue foreground color, from 0 to 255.
102
            char (AnyStr): A single character str or bytes object.
103
        """
104
        i = self.width * y + x
105
        self.fore_r[i] = r
106
        self.fore_g[i] = g
107
        self.fore_b[i] = b
108
        self.char[i] = ord(char)
109
110
    def set_back(self, x, y, r, g, b):
111
        """Set the background color of one cell.
112
113
        Args:
114
            x (int): X position to change.
115
            y (int): Y position to change.
116
            r (int): Red background color, from 0 to 255.
117
            g (int): Green background color, from 0 to 255.
118
            b (int): Blue background color, from 0 to 255.
119
            char (AnyStr): A single character str or bytes object.
120
        """
121
        i = self.width * y + x
122
        self.back_r[i] = r
123
        self.back_g[i] = g
124
        self.back_b[i] = b
125
126
    def set(self, x, y, back_r, back_g, back_b, fore_r, fore_g, fore_b, char):
127
        """Set the background color, foreground color and character of one cell.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (80/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
128
129
        Args:
130
            x (int): X position to change.
131
            y (int): Y position to change.
132
            back_r (int): Red background color, from 0 to 255.
133
            back_g (int): Green background color, from 0 to 255.
134
            back_b (int): Blue background color, from 0 to 255.
135
            fore_r (int): Red foreground color, from 0 to 255.
136
            fore_g (int): Green foreground color, from 0 to 255.
137
            fore_b (int): Blue foreground color, from 0 to 255.
138
            char (AnyStr): A single character str or bytes object.
139
        """
140
        i = self.width * y + x
141
        self.back_r[i] = back_r
142
        self.back_g[i] = back_g
143
        self.back_b[i] = back_b
144
        self.fore_r[i] = fore_r
145
        self.fore_g[i] = fore_g
146
        self.fore_b[i] = fore_b
147
        self.char[i] = ord(char)
148
149
    def blit(self, dest, fill_fore=True, fill_back=True):
150
        """Use libtcod's "fill" functions to write the buffer to a console.
151
152
        Args:
153
            dest (Console): Console object to modify.
154
            fill_fore (bool):
155
                If True, fill the foreground color and characters.
156
            fill_back (bool):
157
                If True, fill the background color.
158
        """
159
        dest = dest.console_c if dest else ffi.NULL
160
        if (console_get_width(dest) != self.width or
161
            console_get_height(dest) != self.height):
162
            raise ValueError('ConsoleBuffer.blit: Destination console has an incorrect size.')
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (94/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
163
164
        if fill_back:
165
            lib.TCOD_console_fill_background(dest or ffi.NULL,
166
                                              ffi.new('int[]', self.back_r),
167
                                              ffi.new('int[]', self.back_g),
168
                                              ffi.new('int[]', self.back_b))
169
        if fill_fore:
170
            lib.TCOD_console_fill_foreground(dest or ffi.NULL,
171
                                              ffi.new('int[]', self.fore_r),
172
                                              ffi.new('int[]', self.fore_g),
173
                                              ffi.new('int[]', self.fore_b))
174
            lib.TCOD_console_fill_char(dest or ffi.NULL,
175
                                        ffi.new('int[]', self.char))
176
177
178
class Dice(_CDataWrapper):
179
    """
180
181
    Args:
182
        nb_dices (int): Number of dice.
183
        nb_faces (int): Number of sides on a die.
184
        multiplier (float): Multiplier.
185
        addsub (float): Addition.
186
187
    .. versionchanged:: 2.0
188
        This class now acts like the other CData wrapped classes
189
        and no longer acts like a list.
190
191
    .. deprecated:: 2.0
192
        You should make your own dice functions instead of using this class
193
        which is tied to a CData object.
194
    """
195
196
    def __init__(self, *args, **kargs):
197
        super(Dice, self).__init__(*args, **kargs)
198
        if self.cdata == ffi.NULL:
199
            self._init(*args, **kargs)
200
201
    def _init(self, nb_dices=0, nb_faces=0, multiplier=0, addsub=0):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
202
        self.cdata = ffi.new('TCOD_dice_t*')
203
        self.nb_dices = nb_dices
204
        self.nb_faces = nb_faces
205
        self.multiplier = multiplier
206
        self.addsub = addsub
207
208
    def _get_nb_dices(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
209
        return self.nb_rolls
210
    def _set_nb_dices(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
211
        self.nb_rolls = value
0 ignored issues
show
Coding Style introduced by
The attribute nb_rolls was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
212
    nb_dices = property(_get_nb_dices, _set_nb_dices)
213
214
    def __str__(self):
215
        add = '+(%s)' % self.addsub if self.addsub != 0 else ''
216
        return '%id%ix%s%s' % (self.nb_dices, self.nb_faces,
217
                               self.multiplier, add)
218
219
    def __repr__(self):
220
        return ('%s(nb_dices=%r,nb_faces=%r,multiplier=%r,addsub=%r)' %
221
                (self.__class__.__name__, self.nb_dices, self.nb_faces,
222
                 self.multiplier, self.addsub))
223
224
225
class Key(_CDataWrapper):
226
    """Key Event instance
227
228
    Attributes:
229
        vk (int): TCOD_keycode_t key code
230
        c (int): character if vk == TCODK_CHAR else 0
231
        text (Text): text[TCOD_KEY_TEXT_SIZE]; text if vk == TCODK_TEXT else text[0] == '\0'
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (92/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
232
        pressed (bool): does this correspond to a key press or key release event ?
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (82/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
233
        lalt (bool): True when left alt is held.
234
        lctrl (bool): True when left control is held.
235
        lmeta (bool): True when left meta key is held.
236
        ralt (bool): True when right alt is held.
237
        rctrl (bool): True when right control is held.
238
        rmeta (bool): True when right meta key is held.
239
        shift (bool): True when any shift is held.
240
    """
241
242
    _BOOL_ATTRIBUTES = ('lalt', 'lctrl', 'lmeta',
243
                        'ralt', 'rctrl', 'rmeta', 'pressed', 'shift')
244
245
    def __init__(self, *args, **kargs):
246
        super(Key, self).__init__(*args, **kargs)
247
        if self.cdata == ffi.NULL:
248
            self.cdata = ffi.new('TCOD_key_t*')
249
250
    def __getattr__(self, attr):
251
        if attr in self._BOOL_ATTRIBUTES:
252
            return bool(getattr(self.cdata, attr))
253
        if attr == 'c':
254
            return ord(getattr(self.cdata, attr))
255
        if attr == 'text':
256
            return _unpack_char_p(getattr(self.cdata, attr))
257
        return super(Key, self).__getattr__(attr)
258
259
    def __repr__(self):
260
        """Return a representation of this Key object."""
261
        params = []
262
        params.append('vk=%r, c=%r, text=%r, pressed=%r' %
263
                      (self.vk, self.c, self.text, self.pressed))
264
        for attr in ['shift', 'lalt', 'lctrl', 'lmeta',
265
                     'ralt', 'rctrl', 'rmeta']:
266
            if getattr(self, attr):
267
                params.append('%s=%r' % (attr, getattr(self, attr)))
268
        return ('%s(%s)' % (self.__class__.__name__, ', '.join(params)))
0 ignored issues
show
Unused Code Coding Style introduced by
There is an unnecessary parenthesis after return.
Loading history...
269
270
271
class Mouse(_CDataWrapper):
272
    """Mouse event instance
273
274
    Attributes:
275
        x (int): Absolute mouse position at pixel x.
276
        y (int):
277
        dx (int): Movement since last update in pixels.
278
        dy (int):
279
        cx (int): Cell coordinates in the root console.
280
        cy (int):
281
        dcx (int): Movement since last update in console cells.
282
        dcy (int):
283
        lbutton (bool): Left button status.
284
        rbutton (bool): Right button status.
285
        mbutton (bool): Middle button status.
286
        lbutton_pressed (bool): Left button pressed event.
287
        rbutton_pressed (bool): Right button pressed event.
288
        mbutton_pressed (bool): Middle button pressed event.
289
        wheel_up (bool): Wheel up event.
290
        wheel_down (bool): Wheel down event.
291
    """
292
293
    def __init__(self, *args, **kargs):
294
        super(Mouse, self).__init__(*args, **kargs)
295
        if self.cdata == ffi.NULL:
296
            self.cdata = ffi.new('TCOD_mouse_t*')
297
298
    def __repr__(self):
299
        """Return a representation of this Mouse object."""
300
        params = []
301
        for attr in ['x', 'y', 'dx', 'dy', 'cx', 'cy', 'dcx', 'dcy']:
302
            params.append('%s=%r' % (attr, getattr(self, attr)))
303
        for attr in ['lbutton', 'rbutton', 'mbutton',
304
                     'lbutton_pressed', 'rbutton_pressed', 'mbutton_pressed',
305
                     'wheel_up', 'wheel_down']:
306
            if getattr(self, attr):
307
                params.append('%s=%r' % (attr, getattr(self, attr)))
308
        return ('%s(%s)' % (self.__class__.__name__, ', '.join(params)))
0 ignored issues
show
Unused Code Coding Style introduced by
There is an unnecessary parenthesis after return.
Loading history...
309
310
311
def bsp_new_with_size(x, y, w, h):
312
    """Create a new BSP instance with the given rectangle.
313
314
    Args:
315
        x (int): Rectangle left coordinate.
316
        y (int): Rectangle top coordinate.
317
        w (int): Rectangle width.
318
        h (int): Rectangle height.
319
320
    Returns:
321
        BSP: A new BSP instance.
322
323
    .. deprecated:: 2.0
324
       Call the :any:`BSP` class instead.
325
    """
326
    return Bsp(x, y, w, h)
327
328
def bsp_split_once(node, horizontal, position):
329
    """
330
    .. deprecated:: 2.0
331
       Use :any:`BSP.split_once` instead.
332
    """
333
    node.split_once(horizontal, position)
334
335
def bsp_split_recursive(node, randomizer, nb, minHSize, minVSize, maxHRatio,
336
                        maxVRatio):
337
    """
338
    .. deprecated:: 2.0
339
       Use :any:`BSP.split_recursive` instead.
340
    """
341
    node.split_recursive(nb, minHSize, minVSize,
342
                         maxHRatio, maxVRatio, randomizer)
343
344
def bsp_resize(node, x, y, w, h):
345
    """
346
    .. deprecated:: 2.0
347
        Assign directly to :any:`BSP` attributes instead.
348
    """
349
    node.x = x
350
    node.y = y
351
    node.width = w
352
    node.height = h
353
354
def bsp_left(node):
355
    """
356
    .. deprecated:: 2.0
357
       Use :any:`BSP.children` instead.
358
    """
359
    return None if not node.children else node.children[0]
360
361
def bsp_right(node):
362
    """
363
    .. deprecated:: 2.0
364
       Use :any:`BSP.children` instead.
365
    """
366
    return None if not node.children else node.children[1]
367
368
def bsp_father(node):
369
    """
370
    .. deprecated:: 2.0
371
       Use :any:`BSP.parent` instead.
372
    """
373
    return node.parent
374
375
def bsp_is_leaf(node):
376
    """
377
    .. deprecated:: 2.0
378
       Use :any:`BSP.children` instead.
379
    """
380
    return not node.children
381
382
def bsp_contains(node, cx, cy):
383
    """
384
    .. deprecated:: 2.0
385
       Use :any:`BSP.contains` instead.
386
    """
387
    return node.contains(cx, cy)
388
389
def bsp_find_node(node, cx, cy):
390
    """
391
    .. deprecated:: 2.0
392
       Use :any:`BSP.find_node` instead.
393
    """
394
    return node.find_node(cx, cy)
395
396
def _bsp_traverse(node_iter, callback, userData):
397
    """pack callback into a handle for use with the callback
398
    _pycall_bsp_callback
399
    """
400
    for node in node_iter:
401
        callback(node, userData)
402
403
def bsp_traverse_pre_order(node, callback, userData=0):
404
    """Traverse this nodes hierarchy with a callback.
405
406
    .. deprecated:: 2.0
407
       Use :any:`BSP.walk` instead.
408
    """
409
    _bsp_traverse(node._iter_pre_order(), callback, userData)
410
411
def bsp_traverse_in_order(node, callback, userData=0):
412
    """Traverse this nodes hierarchy with a callback.
413
414
    .. deprecated:: 2.0
415
       Use :any:`BSP.walk` instead.
416
    """
417
    _bsp_traverse(node._iter_in_order(), callback, userData)
418
419
def bsp_traverse_post_order(node, callback, userData=0):
420
    """Traverse this nodes hierarchy with a callback.
421
422
    .. deprecated:: 2.0
423
       Use :any:`BSP.walk` instead.
424
    """
425
    _bsp_traverse(node._iter_post_order(), callback, userData)
426
427
def bsp_traverse_level_order(node, callback, userData=0):
428
    """Traverse this nodes hierarchy with a callback.
429
430
    .. deprecated:: 2.0
431
       Use :any:`BSP.walk` instead.
432
    """
433
    _bsp_traverse(node._iter_level_order(), callback, userData)
434
435
def bsp_traverse_inverted_level_order(node, callback, userData=0):
436
    """Traverse this nodes hierarchy with a callback.
437
438
    .. deprecated:: 2.0
439
       Use :any:`BSP.walk` instead.
440
    """
441
    _bsp_traverse(node._iter_inverted_level_order(), callback, userData)
442
443
def bsp_remove_sons(node):
444
    """Delete all children of a given node.  Not recommended.
445
446
    .. note::
447
       This function will add unnecessary complexity to your code.
448
       Don't use it.
449
450
    .. deprecated:: 2.0
451
       BSP deletion is automatic.
452
    """
453
    node.children = ()
454
455
def bsp_delete(node):
0 ignored issues
show
Unused Code introduced by
The argument node seems to be unused.
Loading history...
456
    """Exists for backward compatibility.  Does nothing.
457
458
    BSP's created by this library are automatically garbage collected once
459
    there are no references to the tree.
460
    This function exists for backwards compatibility.
461
462
    .. deprecated:: 2.0
463
       BSP deletion is automatic.
464
    """
465
    pass
466
467
def color_lerp(c1, c2, a):
468
    """Return the linear interpolation between two colors.
469
470
    ``a`` is the interpolation value, with 0 returing ``c1``,
471
    1 returning ``c2``, and 0.5 returing a color halfway between both.
472
473
    Args:
474
        c1 (Union[Tuple[int, int, int], Sequence[int]]):
475
            The first color.  At a=0.
476
        c2 (Union[Tuple[int, int, int], Sequence[int]]):
477
            The second color.  At a=1.
478
        a (float): The interpolation value,
479
480
    Returns:
481
        Color: The interpolated Color.
482
    """
483
    return Color._new_from_cdata(lib.TCOD_color_lerp(c1, c2, a))
484
485
def color_set_hsv(c, h, s, v):
486
    """Set a color using: hue, saturation, and value parameters.
487
488
    Does not return a new Color.  ``c`` is modified inplace.
489
490
    Args:
491
        c (Union[Color, List[Any]]): A Color instance, or a list of any kind.
492
        h (float): Hue, from 0 to 360.
493
        s (float): Saturation, from 0 to 1.
494
        v (float): Value, from 0 to 1.
495
    """
496
    new_color = ffi.new('TCOD_color_t*')
497
    lib.TCOD_color_set_HSV(new_color, h, s, v)
498
    c[:] = new_color.r, new_color.g, new_color.b
499
500
def color_get_hsv(c):
501
    """Return the (hue, saturation, value) of a color.
502
503
    Args:
504
        c (Union[Tuple[int, int, int], Sequence[int]]):
505
            An (r, g, b) sequence or Color instance.
506
507
    Returns:
508
        Tuple[float, float, float]:
509
            A tuple with (hue, saturation, value) values, from 0 to 1.
510
    """
511
    hsv = ffi.new('float [3]')
512
    lib.TCOD_color_get_HSV(c, hsv, hsv + 1, hsv + 2)
513
    return hsv[0], hsv[1], hsv[2]
514
515
def color_scale_HSV(c, scoef, vcoef):
516
    """Scale a color's saturation and value.
517
518
    Does not return a new Color.  ``c`` is modified inplace.
519
520
    Args:
521
        c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
522
        scoef (float): Saturation multiplier, from 0 to 1.
523
                       Use 1 to keep current saturation.
524
        vcoef (float): Value multiplier, from 0 to 1.
525
                       Use 1 to keep current value.
526
    """
527
    color_p = ffi.new('TCOD_color_t*')
528
    color_p.r, color_p.g, color_p.b = c.r, c.g, c.b
529
    lib.TCOD_color_scale_HSV(color_p, scoef, vcoef)
530
    c[:] = color_p.r, color_p.g, color_p.b
531
532
def color_gen_map(colors, indexes):
533
    """Return a smoothly defined scale of colors.
534
535
    If ``indexes`` is [0, 3, 9] for example, the first color from ``colors``
536
    will be returned at 0, the 2nd will be at 3, and the 3rd will be at 9.
537
    All in-betweens will be filled with a gradient.
538
539
    Args:
540
        colors (Iterable[Union[Tuple[int, int, int], Sequence[int]]]):
541
            Array of colors to be sampled.
542
        indexes (Iterable[int]): A list of indexes.
543
544
    Returns:
545
        List[Color]: A list of Color instances.
546
547
    Example:
548
        >>> tcod.color_gen_map([(0, 0, 0), (255, 128, 0)], [0, 5])
549
        [Color(0,0,0), Color(51,25,0), Color(102,51,0), Color(153,76,0), \
550
Color(204,102,0), Color(255,128,0)]
551
    """
552
    ccolors = ffi.new('TCOD_color_t[]', colors)
553
    cindexes = ffi.new('int[]', indexes)
554
    cres = ffi.new('TCOD_color_t[]', max(indexes) + 1)
555
    lib.TCOD_color_gen_map(cres, len(colors), ccolors, cindexes)
556
    return [Color._new_from_cdata(cdata) for cdata in cres]
557
558
_numpy = None
559
560
def _numpy_available():
561
    'check if numpy is available and lazily load it when needed'
562
    global _numpy
563
    if _numpy is None:
564
        try:
565
            import numpy as _numpy
0 ignored issues
show
Comprehensibility Bug introduced by
_numpy is re-defining a name which is already available in the outer-scope (previously defined on line 558).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
566
        except ImportError:
567
            _numpy = False
568
    return _numpy
569
570
def console_init_root(w, h, title, fullscreen=False,
571
                      renderer=RENDERER_GLSL):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'RENDERER_GLSL'
Loading history...
572
    """Set up the primary display and return the root console.
573
574
    Args:
575
        w (int): Width in character tiles for the root console.
576
        h (int): Height in character tiles for the root console.
577
        title (AnyStr):
578
            This string will be displayed on the created windows title bar.
579
        renderer: Rendering mode for libtcod to use.
580
581
    Returns:
582
        Console:
583
            Returns a special Console instance representing the root console.
584
    """
585
    lib.TCOD_console_init_root(w, h, _bytes(title), fullscreen, renderer)
586
    return tcod.console.Console._from_cdata(ffi.NULL) # root console is null
587
588
589
def console_set_custom_font(fontFile, flags=FONT_LAYOUT_ASCII_INCOL,
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'FONT_LAYOUT_ASCII_INCOL'
Loading history...
590
                            nb_char_horiz=0, nb_char_vertic=0):
591
    """Load a custom font file.
592
593
    Call this before function before calling :any:`tcod.console_init_root`.
594
595
    Flags can be a mix of the following:
596
597
    * tcod.FONT_LAYOUT_ASCII_INCOL
598
    * tcod.FONT_LAYOUT_ASCII_INROW
599
    * tcod.FONT_TYPE_GREYSCALE
600
    * tcod.FONT_TYPE_GRAYSCALE
601
    * tcod.FONT_LAYOUT_TCOD
602
603
    Args:
604
        fontFile (AnyStr): Path to a font file.
605
        flags (int):
606
        nb_char_horiz (int):
607
        nb_char_vertic (int):
608
    """
609
    lib.TCOD_console_set_custom_font(_bytes(fontFile), flags,
610
                                     nb_char_horiz, nb_char_vertic)
611
612
613
def console_get_width(con):
614
    """Return the width of a console.
615
616
    Args:
617
        con (Console): Any Console instance.
618
619
    Returns:
620
        int: The width of a Console.
621
622
    .. deprecated:: 2.0
623
        Use `Console.get_width` instead.
624
    """
625
    return lib.TCOD_console_get_width(con.console_c if con else ffi.NULL)
626
627
def console_get_height(con):
628
    """Return the height of a console.
629
630
    Args:
631
        con (Console): Any Console instance.
632
633
    Returns:
634
        int: The height of a Console.
635
636
    .. deprecated:: 2.0
637
        Use `Console.get_hright` instead.
638
    """
639
    return lib.TCOD_console_get_height(con.console_c if con else ffi.NULL)
640
641
def console_map_ascii_code_to_font(asciiCode, fontCharX, fontCharY):
642
    """Set a character code to new coordinates on the tile-set.
643
644
    `asciiCode` must be within the bounds created during the initialization of
645
    the loaded tile-set.  For example, you can't use 255 here unless you have a
646
    256 tile tile-set loaded.  This applies to all functions in this group.
647
648
    Args:
649
        asciiCode (int): The character code to change.
650
        fontCharX (int): The X tile coordinate on the loaded tileset.
651
                         0 is the leftmost tile.
652
        fontCharY (int): The Y tile coordinate on the loaded tileset.
653
                         0 is the topmost tile.
654
    """
655
    lib.TCOD_console_map_ascii_code_to_font(_int(asciiCode), fontCharX,
656
                                                              fontCharY)
657
658
def console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, fontCharX,
659
                                    fontCharY):
660
    """Remap a contiguous set of codes to a contiguous set of tiles.
661
662
    Both the tile-set and character codes must be contiguous to use this
663
    function.  If this is not the case you may want to use
664
    :any:`console_map_ascii_code_to_font`.
665
666
    Args:
667
        firstAsciiCode (int): The starting character code.
668
        nbCodes (int): The length of the contiguous set.
669
        fontCharX (int): The starting X tile coordinate on the loaded tileset.
670
                         0 is the leftmost tile.
671
        fontCharY (int): The starting Y tile coordinate on the loaded tileset.
672
                         0 is the topmost tile.
673
674
    """
675
    lib.TCOD_console_map_ascii_codes_to_font(_int(firstAsciiCode), nbCodes,
676
                                              fontCharX, fontCharY)
677
678
def console_map_string_to_font(s, fontCharX, fontCharY):
679
    """Remap a string of codes to a contiguous set of tiles.
680
681
    Args:
682
        s (AnyStr): A string of character codes to map to new values.
683
                    The null character `'\x00'` will prematurely end this
684
                    function.
685
        fontCharX (int): The starting X tile coordinate on the loaded tileset.
686
                         0 is the leftmost tile.
687
        fontCharY (int): The starting Y tile coordinate on the loaded tileset.
688
                         0 is the topmost tile.
689
    """
690
    lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
691
692
def console_is_fullscreen():
693
    """Returns True if the display is fullscreen.
694
695
    Returns:
696
        bool: True if the display is fullscreen, otherwise False.
697
    """
698
    return bool(lib.TCOD_console_is_fullscreen())
699
700
def console_set_fullscreen(fullscreen):
701
    """Change the display to be fullscreen or windowed.
702
703
    Args:
704
        fullscreen (bool): Use True to change to fullscreen.
705
                           Use False to change to windowed.
706
    """
707
    lib.TCOD_console_set_fullscreen(fullscreen)
708
709
def console_is_window_closed():
710
    """Returns True if the window has received and exit event."""
711
    return lib.TCOD_console_is_window_closed()
712
713
def console_set_window_title(title):
714
    """Change the current title bar string.
715
716
    Args:
717
        title (AnyStr): A string to change the title bar to.
718
    """
719
    lib.TCOD_console_set_window_title(_bytes(title))
720
721
def console_credits():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
722
    lib.TCOD_console_credits()
723
724
def console_credits_reset():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
725
    lib.TCOD_console_credits_reset()
726
727
def console_credits_render(x, y, alpha):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
728
    return lib.TCOD_console_credits_render(x, y, alpha)
729
730
def console_flush():
731
    """Update the display to represent the root consoles current state."""
732
    lib.TCOD_console_flush()
733
734
# drawing on a console
735
def console_set_default_background(con, col):
736
    """Change the default background color for a console.
737
738
    Args:
739
        con (Console): Any Console instance.
740
        col (Union[Tuple[int, int, int], Sequence[int]]):
741
            An (r, g, b) sequence or Color instance.
742
    """
743
    lib.TCOD_console_set_default_background(
744
        con.console_c if con else ffi.NULL, col)
745
746
def console_set_default_foreground(con, col):
747
    """Change the default foreground color for a console.
748
749
    Args:
750
        con (Console): Any Console instance.
751
        col (Union[Tuple[int, int, int], Sequence[int]]):
752
            An (r, g, b) sequence or Color instance.
753
    """
754
    lib.TCOD_console_set_default_foreground(
755
        con.console_c if con else ffi.NULL, col)
756
757
def console_clear(con):
758
    """Reset a console to its default colors and the space character.
759
760
    Args:
761
        con (Console): Any Console instance.
762
763
    .. seealso::
764
       :any:`console_set_default_background`
765
       :any:`console_set_default_foreground`
766
    """
767
    return lib.TCOD_console_clear(con.console_c if con else ffi.NULL)
768
769
def console_put_char(con, x, y, c, flag=BKGND_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_DEFAULT'
Loading history...
770
    """Draw the character c at x,y using the default colors and a blend mode.
771
772
    Args:
773
        con (Console): Any Console instance.
774
        x (int): Character x position from the left.
775
        y (int): Character y position from the top.
776
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
777
        flag (int): Blending mode to use, defaults to BKGND_DEFAULT.
778
    """
779
    lib.TCOD_console_put_char(
780
        con.console_c if con else ffi.NULL, x, y, _int(c), flag)
781
782
def console_put_char_ex(con, x, y, c, fore, back):
783
    """Draw the character c at x,y using the colors fore and back.
784
785
    Args:
786
        con (Console): Any Console instance.
787
        x (int): Character x position from the left.
788
        y (int): Character y position from the top.
789
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
790
        fore (Union[Tuple[int, int, int], Sequence[int]]):
791
            An (r, g, b) sequence or Color instance.
792
        back (Union[Tuple[int, int, int], Sequence[int]]):
793
            An (r, g, b) sequence or Color instance.
794
    """
795
    lib.TCOD_console_put_char_ex(con.console_c if con else ffi.NULL, x, y,
796
                                 _int(c), fore, back)
797
798
def console_set_char_background(con, x, y, col, flag=BKGND_SET):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_SET'
Loading history...
799
    """Change the background color of x,y to col using a blend mode.
800
801
    Args:
802
        con (Console): Any Console instance.
803
        x (int): Character x position from the left.
804
        y (int): Character y position from the top.
805
        col (Union[Tuple[int, int, int], Sequence[int]]):
806
            An (r, g, b) sequence or Color instance.
807
        flag (int): Blending mode to use, defaults to BKGND_SET.
808
    """
809
    lib.TCOD_console_set_char_background(
810
        con.console_c if con else ffi.NULL, x, y, col, flag)
811
812
def console_set_char_foreground(con, x, y, col):
813
    """Change the foreground color of x,y to col.
814
815
    Args:
816
        con (Console): Any Console instance.
817
        x (int): Character x position from the left.
818
        y (int): Character y position from the top.
819
        col (Union[Tuple[int, int, int], Sequence[int]]):
820
            An (r, g, b) sequence or Color instance.
821
    """
822
    lib.TCOD_console_set_char_foreground(
823
        con.console_c if con else ffi.NULL, x, y, col)
824
825
def console_set_char(con, x, y, c):
826
    """Change the character at x,y to c, keeping the current colors.
827
828
    Args:
829
        con (Console): Any Console instance.
830
        x (int): Character x position from the left.
831
        y (int): Character y position from the top.
832
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
833
    """
834
    lib.TCOD_console_set_char(
835
        con.console_c if con else ffi.NULL, x, y, _int(c))
836
837
def console_set_background_flag(con, flag):
838
    """Change the default blend mode for this console.
839
840
    Args:
841
        con (Console): Any Console instance.
842
        flag (int): Blend mode to use by default.
843
    """
844
    lib.TCOD_console_set_background_flag(
845
        con.console_c if con else ffi.NULL, flag)
846
847
def console_get_background_flag(con):
848
    """Return this consoles current blend mode.
849
850
    Args:
851
        con (Console): Any Console instance.
852
    """
853
    return lib.TCOD_console_get_background_flag(
854
        con.console_c if con else ffi.NULL)
855
856
def console_set_alignment(con, alignment):
857
    """Change this consoles current alignment mode.
858
859
    * tcod.LEFT
860
    * tcod.CENTER
861
    * tcod.RIGHT
862
863
    Args:
864
        con (Console): Any Console instance.
865
        alignment (int):
866
    """
867
    lib.TCOD_console_set_alignment(
868
        con.console_c if con else ffi.NULL, alignment)
869
870
def console_get_alignment(con):
871
    """Return this consoles current alignment mode.
872
873
    Args:
874
        con (Console): Any Console instance.
875
    """
876
    return lib.TCOD_console_get_alignment(con.console_c if con else ffi.NULL)
877
878
def console_print(con, x, y, fmt):
879
    """Print a color formatted string on a console.
880
881
    Args:
882
        con (Console): Any Console instance.
883
        x (int): Character x position from the left.
884
        y (int): Character y position from the top.
885
        fmt (AnyStr): A unicode or bytes string optionaly using color codes.
886
    """
887
    lib.TCOD_console_print_utf(
888
        con.console_c if con else ffi.NULL, x, y, _fmt_unicode(fmt))
889
890
def console_print_ex(con, x, y, flag, alignment, fmt):
891
    """Print a string on a console using a blend mode and alignment mode.
892
893
    Args:
894
        con (Console): Any Console instance.
895
        x (int): Character x position from the left.
896
        y (int): Character y position from the top.
897
    """
898
    lib.TCOD_console_print_ex_utf(con.console_c if con else ffi.NULL,
899
                                  x, y, flag, alignment, _fmt_unicode(fmt))
900
901
def console_print_rect(con, x, y, w, h, fmt):
902
    """Print a string constrained to a rectangle.
903
904
    If h > 0 and the bottom of the rectangle is reached,
905
    the string is truncated. If h = 0,
906
    the string is only truncated if it reaches the bottom of the console.
907
908
909
910
    Returns:
911
        int: The number of lines of text once word-wrapped.
912
    """
913
    return lib.TCOD_console_print_rect_utf(
914
        con.console_c if con else ffi.NULL, x, y, w, h, _fmt_unicode(fmt))
915
916
def console_print_rect_ex(con, x, y, w, h, flag, alignment, fmt):
917
    """Print a string constrained to a rectangle with blend and alignment.
918
919
    Returns:
920
        int: The number of lines of text once word-wrapped.
921
    """
922
    return lib.TCOD_console_print_rect_ex_utf(
923
        con.console_c if con else ffi.NULL,
924
        x, y, w, h, flag, alignment, _fmt_unicode(fmt))
925
926
def console_get_height_rect(con, x, y, w, h, fmt):
927
    """Return the height of this text once word-wrapped into this rectangle.
928
929
    Returns:
930
        int: The number of lines of text once word-wrapped.
931
    """
932
    return lib.TCOD_console_get_height_rect_utf(
933
        con.console_c if con else ffi.NULL, x, y, w, h, _fmt_unicode(fmt))
934
935
def console_rect(con, x, y, w, h, clr, flag=BKGND_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_DEFAULT'
Loading history...
936
    """Draw a the background color on a rect optionally clearing the text.
937
938
    If clr is True the affected tiles are changed to space character.
939
    """
940
    lib.TCOD_console_rect(
941
        con.console_c if con else ffi.NULL, x, y, w, h, clr, flag)
942
943
def console_hline(con, x, y, l, flag=BKGND_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_DEFAULT'
Loading history...
944
    """Draw a horizontal line on the console.
945
946
    This always uses the character 196, the horizontal line character.
947
    """
948
    lib.TCOD_console_hline(con.console_c if con else ffi.NULL, x, y, l, flag)
949
950
def console_vline(con, x, y, l, flag=BKGND_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_DEFAULT'
Loading history...
951
    """Draw a vertical line on the console.
952
953
    This always uses the character 179, the vertical line character.
954
    """
955
    lib.TCOD_console_vline(con.console_c if con else ffi.NULL, x, y, l, flag)
956
957
def console_print_frame(con, x, y, w, h, clear=True, flag=BKGND_DEFAULT, fmt=b''):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (82/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'BKGND_DEFAULT'
Loading history...
958
    """Draw a framed rectangle with optinal text.
959
960
    This uses the default background color and blend mode to fill the
961
    rectangle and the default foreground to draw the outline.
962
963
    fmt will be printed on the inside of the rectangle, word-wrapped.
964
    """
965
    lib.TCOD_console_print_frame(
966
        con.console_c if con else ffi.NULL,
967
        x, y, w, h, clear, flag, _fmt_bytes(fmt))
968
969
def console_set_color_control(con, fore, back):
970
    """Configure :any:`color controls`.
971
972
    Args:
973
        con (int): :any:`Color control` constant to modify.
974
        fore (Union[Tuple[int, int, int], Sequence[int]]):
975
            An (r, g, b) sequence or Color instance.
976
        back (Union[Tuple[int, int, int], Sequence[int]]):
977
            An (r, g, b) sequence or Color instance.
978
    """
979
    lib.TCOD_console_set_color_control(con, fore, back)
980
981
def console_get_default_background(con):
982
    """Return this consoles default background color."""
983
    return Color._new_from_cdata(
984
        lib.TCOD_console_get_default_background(
985
            con.console_c if con else ffi.NULL))
986
987
def console_get_default_foreground(con):
988
    """Return this consoles default foreground color."""
989
    return Color._new_from_cdata(
990
        lib.TCOD_console_get_default_foreground(
991
            con.console_c if con else ffi.NULL))
992
993
def console_get_char_background(con, x, y):
994
    """Return the background color at the x,y of this console."""
995
    return Color._new_from_cdata(
996
        lib.TCOD_console_get_char_background(
997
            con.console_c if con else ffi.NULL, x, y))
998
999
def console_get_char_foreground(con, x, y):
1000
    """Return the foreground color at the x,y of this console."""
1001
    return Color._new_from_cdata(
1002
        lib.TCOD_console_get_char_foreground(
1003
            con.console_c if con else ffi.NULL, x, y))
1004
1005
def console_get_char(con, x, y):
1006
    """Return the character at the x,y of this console."""
1007
    return lib.TCOD_console_get_char(con.console_c if con else ffi.NULL, x, y)
1008
1009
def console_set_fade(fade, fadingColor):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1010
    lib.TCOD_console_set_fade(fade, fadingColor)
1011
1012
def console_get_fade():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1013
    return lib.TCOD_console_get_fade()
1014
1015
def console_get_fading_color():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1016
    return Color._new_from_cdata(lib.TCOD_console_get_fading_color())
1017
1018
# handling keyboard input
1019
def console_wait_for_keypress(flush):
1020
    """Block until the user presses a key, then returns a new Key.
1021
1022
    Args:
1023
        flush bool: If True then the event queue is cleared before waiting
1024
                    for the next event.
1025
1026
    Returns:
1027
        Key: A new Key instance.
1028
    """
1029
    k=Key()
0 ignored issues
show
Coding Style introduced by
Exactly one space required around assignment
k=Key()
^
Loading history...
1030
    lib.TCOD_console_wait_for_keypress_wrapper(k.cdata, flush)
1031
    return k
1032
1033
def console_check_for_keypress(flags=KEY_RELEASED):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'KEY_RELEASED'
Loading history...
1034
    k=Key()
0 ignored issues
show
Coding Style introduced by
Exactly one space required around assignment
k=Key()
^
Loading history...
1035
    lib.TCOD_console_check_for_keypress_wrapper(k.cdata, flags)
1036
    return k
1037
1038
def console_is_key_pressed(key):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1039
    return lib.TCOD_console_is_key_pressed(key)
1040
1041
# using offscreen consoles
1042
def console_new(w, h):
1043
    """Return an offscreen console of size: w,h."""
1044
    return tcod.console.Console(w, h)
1045
1046
def console_from_file(filename):
1047
    """Return a new console object from a filename.
1048
1049
    The file format is automactially determined.  This can load REXPaint `.xp`,
1050
    ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files.
1051
1052
    Args:
1053
        filename (Text): The path to the file, as a string.
1054
1055
    Returns: A new :any`Console` instance.
1056
    """
1057
    return tcod.console.Console._from_cdata(
1058
        lib.TCOD_console_from_file(filename.encode('utf-8')))
1059
1060
def console_blit(src, x, y, w, h, dst, xdst, ydst, ffade=1.0,bfade=1.0):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
def console_blit(src, x, y, w, h, dst, xdst, ydst, ffade=1.0,bfade=1.0):
^
Loading history...
1061
    """Blit the console src from x,y,w,h to console dst at xdst,ydst."""
1062
    lib.TCOD_console_blit(
1063
        src.console_c if src else ffi.NULL, x, y, w, h,
1064
        dst.console_c if dst else ffi.NULL, xdst, ydst, ffade, bfade)
1065
1066
def console_set_key_color(con, col):
1067
    """Set a consoles blit transparent color."""
1068
    lib.TCOD_console_set_key_color(con.console_c if con else ffi.NULL, col)
1069
1070
def console_delete(con):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1071
    con = con.console_c if con else ffi.NULL
1072
    if con == ffi.NULL:
1073
        lib.TCOD_console_delete(con)
1074
1075
# fast color filling
1076 View Code Duplication
def console_fill_foreground(con, r, g, b):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1077
    """Fill the foregound of a console with r,g,b.
1078
1079
    Args:
1080
        con (Console): Any Console instance.
1081
        r (Sequence[int]): An array of integers with a length of width*height.
1082
        g (Sequence[int]): An array of integers with a length of width*height.
1083
        b (Sequence[int]): An array of integers with a length of width*height.
1084
    """
1085
    if len(r) != len(g) or len(r) != len(b):
1086
        raise TypeError('R, G and B must all have the same size.')
1087
    if (_numpy_available() and isinstance(r, _numpy.ndarray) and
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ndarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1088
        isinstance(g, _numpy.ndarray) and isinstance(b, _numpy.ndarray)):
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ndarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1089
        #numpy arrays, use numpy's ctypes functions
1090
        r = _numpy.ascontiguousarray(r, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1091
        g = _numpy.ascontiguousarray(g, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1092
        b = _numpy.ascontiguousarray(b, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1093
        cr = ffi.cast('int *', r.ctypes.data)
1094
        cg = ffi.cast('int *', g.ctypes.data)
1095
        cb = ffi.cast('int *', b.ctypes.data)
1096
    else:
1097
        # otherwise convert using ffi arrays
1098
        cr = ffi.new('int[]', r)
1099
        cg = ffi.new('int[]', g)
1100
        cb = ffi.new('int[]', b)
1101
1102
    lib.TCOD_console_fill_foreground(con.console_c if con else ffi.NULL,
1103
                                     cr, cg, cb)
1104
1105 View Code Duplication
def console_fill_background(con, r, g, b):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1106
    """Fill the backgound of a console with r,g,b.
1107
1108
    Args:
1109
        con (Console): Any Console instance.
1110
        r (Sequence[int]): An array of integers with a length of width*height.
1111
        g (Sequence[int]): An array of integers with a length of width*height.
1112
        b (Sequence[int]): An array of integers with a length of width*height.
1113
    """
1114
    if len(r) != len(g) or len(r) != len(b):
1115
        raise TypeError('R, G and B must all have the same size.')
1116
    if (_numpy_available() and isinstance(r, _numpy.ndarray) and
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ndarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1117
        isinstance(g, _numpy.ndarray) and isinstance(b, _numpy.ndarray)):
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ndarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1118
        #numpy arrays, use numpy's ctypes functions
1119
        r = _numpy.ascontiguousarray(r, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1120
        g = _numpy.ascontiguousarray(g, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1121
        b = _numpy.ascontiguousarray(b, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1122
        cr = ffi.cast('int *', r.ctypes.data)
1123
        cg = ffi.cast('int *', g.ctypes.data)
1124
        cb = ffi.cast('int *', b.ctypes.data)
1125
    else:
1126
        # otherwise convert using ffi arrays
1127
        cr = ffi.new('int[]', r)
1128
        cg = ffi.new('int[]', g)
1129
        cb = ffi.new('int[]', b)
1130
1131
    lib.TCOD_console_fill_background(con.console_c if con else ffi.NULL,
1132
                                     cr, cg, cb)
1133
1134
def console_fill_char(con,arr):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
def console_fill_char(con,arr):
^
Loading history...
1135
    """Fill the character tiles of a console with an array.
1136
1137
    Args:
1138
        con (Console): Any Console instance.
1139
        arr (Sequence[int]): An array of integers with a length of width*height.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (80/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1140
    """
1141
    if (_numpy_available() and isinstance(arr, _numpy.ndarray) ):
0 ignored issues
show
Unused Code Coding Style introduced by
There is an unnecessary parenthesis after if.
Loading history...
Coding Style introduced by
No space allowed before bracket
if (_numpy_available() and isinstance(arr, _numpy.ndarray) ):
^
Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named ndarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1142
        #numpy arrays, use numpy's ctypes functions
1143
        arr = _numpy.ascontiguousarray(arr, dtype=_numpy.intc)
0 ignored issues
show
Bug introduced by
The Instance of bool does not seem to have a member named ascontiguousarray.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by
The Instance of bool does not seem to have a member named intc.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
1144
        carr = ffi.cast('int *', arr.ctypes.data)
1145
    else:
1146
        #otherwise convert using the ffi module
1147
        carr = ffi.new('int[]', arr)
1148
1149
    lib.TCOD_console_fill_char(con.console_c if con else ffi.NULL, carr)
1150
1151
def console_load_asc(con, filename):
1152
    """Update a console from a non-delimited ASCII `.asc` file."""
1153
    return lib.TCOD_console_load_asc(
1154
        con.console_c if con else ffi.NULL, filename.encode('utf-8'))
1155
1156
def console_save_asc(con, filename):
1157
    """Save a console to a non-delimited ASCII `.asc` file."""
1158
    return lib.TCOD_console_save_asc(
1159
        con.console_c if con else ffi.NULL, filename.encode('utf-8'))
1160
1161
def console_load_apf(con, filename):
1162
    """Update a console from an ASCII Paint `.apf` file."""
1163
    return lib.TCOD_console_load_apf(
1164
        con.console_c if con else ffi.NULL, filename.encode('utf-8'))
1165
1166
def console_save_apf(con, filename):
1167
    """Save a console to an ASCII Paint `.apf` file."""
1168
    return lib.TCOD_console_save_apf(
1169
        con.console_c if con else ffi.NULL, filename.encode('utf-8'))
1170
1171
def console_load_xp(con, filename):
1172
    """Update a console from a REXPaint `.xp` file."""
1173
    return lib.TCOD_console_load_xp(
1174
        con.console_c if con else ffi.NULL, filename.encode('utf-8'))
1175
1176
def console_save_xp(con, filename, compress_level=9):
1177
    """Save a console to a REXPaint `.xp` file."""
1178
    return lib.TCOD_console_save_xp(
1179
        con.console_c if con else ffi.NULL,
1180
        filename.encode('utf-8'),
1181
        compress_level,
1182
        )
1183
1184
def console_from_xp(filename):
1185
    """Return a single console from a REXPaint `.xp` file."""
1186
    return tcod.console.Console._from_cdata(
1187
        lib.TCOD_console_from_xp(filename.encode('utf-8')))
1188
1189
def console_list_load_xp(filename):
1190
    """Return a list of consoles from a REXPaint `.xp` file."""
1191
    tcod_list = lib.TCOD_console_list_from_xp(filename.encode('utf-8'))
1192
    if tcod_list == ffi.NULL:
1193
        return None
1194
    try:
1195
        python_list = []
1196
        lib.TCOD_list_reverse(tcod_list)
1197
        while not lib.TCOD_list_is_empty(tcod_list):
1198
            python_list.append(
1199
                tcod.console.Console._from_cdata(lib.TCOD_list_pop(tcod_list)),
1200
                )
1201
        return python_list
1202
    finally:
1203
        lib.TCOD_list_delete(tcod_list)
1204
1205
def console_list_save_xp(console_list, filename, compress_level=9):
1206
    """Save a list of consoles to a REXPaint `.xp` file."""
1207
    tcod_list = lib.TCOD_list_new()
1208
    try:
1209
        for console in console_list:
1210
            lib.TCOD_list_push(tcod_list,
1211
                               console.console_c if console else ffi.NULL)
1212
        return lib.TCOD_console_list_save_xp(
1213
            tcod_list, filename.encode('utf-8'), compress_level
1214
            )
1215
    finally:
1216
        lib.TCOD_list_delete(tcod_list)
1217
1218
def path_new_using_map(m, dcost=1.41):
1219
    """Return a new AStar using the given Map.
1220
1221
    Args:
1222
        m (Map): A Map instance.
1223
        dcost (float): The path-finding cost of diagonal movement.
1224
                       Can be set to 0 to disable diagonal movement.
1225
    Returns:
1226
        AStar: A new AStar instance.
1227
    """
1228
    return tcod.path.AStar(m, dcost)
1229
1230
def path_new_using_function(w, h, func, userData=0, dcost=1.41):
1231
    """Return a new AStar using the given callable function.
1232
1233
    Args:
1234
        w (int): Clipping width.
1235
        h (int): Clipping height.
1236
        func (Callable[[int, int, int, int, Any], float]):
1237
        userData (Any):
1238
        dcost (float): A multiplier for the cost of diagonal movement.
1239
                       Can be set to 0 to disable diagonal movement.
1240
    Returns:
1241
        AStar: A new AStar instance.
1242
    """
1243
    return tcod.path.AStar((func, userData), dcost, w, h)
1244
1245
def path_compute(p, ox, oy, dx, dy):
1246
    """Find a path from (ox, oy) to (dx, dy).  Return True if path is found.
1247
1248
    Args:
1249
        p (AStar): An AStar instance.
1250
        ox (int): Starting x position.
1251
        oy (int): Starting y position.
1252
        dx (int): Destination x position.
1253
        dy (int): Destination y position.
1254
    Returns:
1255
        bool: True if a valid path was found.  Otherwise False.
1256
    """
1257
    return lib.TCOD_path_compute(p.cdata, ox, oy, dx, dy)
1258
1259
def path_get_origin(p):
1260
    """Get the current origin position.
1261
1262
    This point moves when :any:`path_walk` returns the next x,y step.
1263
1264
    Args:
1265
        p (AStar): An AStar instance.
1266
    Returns:
1267
        Tuple[int, int]: An (x, y) point.
1268
    """
1269
    x = ffi.new('int *')
1270
    y = ffi.new('int *')
1271
    lib.TCOD_path_get_origin(p.cdata, x, y)
1272
    return x[0], y[0]
1273
1274
def path_get_destination(p):
1275
    """Get the current destination position.
1276
1277
    Args:
1278
        p (AStar): An AStar instance.
1279
    Returns:
1280
        Tuple[int, int]: An (x, y) point.
1281
    """
1282
    x = ffi.new('int *')
1283
    y = ffi.new('int *')
1284
    lib.TCOD_path_get_destination(p.cdata, x, y)
1285
    return x[0], y[0]
1286
1287
def path_size(p):
1288
    """Return the current length of the computed path.
1289
1290
    Args:
1291
        p (AStar): An AStar instance.
1292
    Returns:
1293
        int: Length of the path.
1294
    """
1295
    return lib.TCOD_path_size(p.cdata)
1296
1297
def path_reverse(p):
1298
    """Reverse the direction of a path.
1299
1300
    This effectively swaps the origin and destination points.
1301
1302
    Args:
1303
        p (AStar): An AStar instance.
1304
    """
1305
    lib.TCOD_path_reverse(p.cdata)
1306
1307
def path_get(p, idx):
1308
    """Get a point on a path.
1309
1310
    Args:
1311
        p (AStar): An AStar instance.
1312
        idx (int): Should be in range: 0 <= inx < :any:`path_size`
1313
    """
1314
    x = ffi.new('int *')
1315
    y = ffi.new('int *')
1316
    lib.TCOD_path_get(p.cdata, idx, x, y)
1317
    return x[0], y[0]
1318
1319
def path_is_empty(p):
1320
    """Return True if a path is empty.
1321
1322
    Args:
1323
        p (AStar): An AStar instance.
1324
    Returns:
1325
        bool: True if a path is empty.  Otherwise False.
1326
    """
1327
    return lib.TCOD_path_is_empty(p.cdata)
1328
1329
def path_walk(p, recompute):
1330
    """Return the next (x, y) point in a path, or (None, None) if it's empty.
1331
1332
    When ``recompute`` is True and a previously valid path reaches a point
1333
    where it is now blocked, a new path will automatically be found.
1334
1335
    Args:
1336
        p (AStar): An AStar instance.
1337
        recompute (bool): Recompute the path automatically.
1338
    Returns:
1339
        Union[Tuple[int, int], Tuple[None, None]]:
1340
            A single (x, y) point, or (None, None)
1341
    """
1342
    x = ffi.new('int *')
1343
    y = ffi.new('int *')
1344
    if lib.TCOD_path_walk(p.cdata, x, y, recompute):
1345
        return x[0], y[0]
1346
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1347
1348
def path_delete(p):
0 ignored issues
show
Unused Code introduced by
The argument p seems to be unused.
Loading history...
1349
    """Does nothing."""
1350
    pass
1351
1352
def dijkstra_new(m, dcost=1.41):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1353
    return tcod.path.Dijkstra(m, dcost)
1354
1355
def dijkstra_new_using_function(w, h, func, userData=0, dcost=1.41):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1356
    return tcod.path.Dijkstra((func, userData), dcost, w, h)
1357
1358
def dijkstra_compute(p, ox, oy):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1359
    lib.TCOD_dijkstra_compute(p.cdata, ox, oy)
1360
1361
def dijkstra_path_set(p, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1362
    return lib.TCOD_dijkstra_path_set(p.cdata, x, y)
1363
1364
def dijkstra_get_distance(p, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1365
    return lib.TCOD_dijkstra_get_distance(p.cdata, x, y)
1366
1367
def dijkstra_size(p):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1368
    return lib.TCOD_dijkstra_size(p.cdata)
1369
1370
def dijkstra_reverse(p):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1371
    lib.TCOD_dijkstra_reverse(p.cdata)
1372
1373
def dijkstra_get(p, idx):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1374
    x = ffi.new('int *')
1375
    y = ffi.new('int *')
1376
    lib.TCOD_dijkstra_get(p.cdata, idx, x, y)
1377
    return x[0], y[0]
1378
1379
def dijkstra_is_empty(p):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1380
    return lib.TCOD_dijkstra_is_empty(p.cdata)
1381
1382
def dijkstra_path_walk(p):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1383
    x = ffi.new('int *')
1384
    y = ffi.new('int *')
1385
    if lib.TCOD_dijkstra_path_walk(p.cdata, x, y):
1386
        return x[0], y[0]
1387
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1388
1389
def dijkstra_delete(p):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The argument p seems to be unused.
Loading history...
1390
    pass
1391
1392
def _heightmap_cdata(array):
1393
    """Return a new TCOD_heightmap_t instance using an array.
1394
1395
    Formatting is verified during this function.
1396
    """
1397
    if not array.flags['C_CONTIGUOUS']:
1398
        raise ValueError('array must be a C-style contiguous segment.')
1399
    if array.dtype != _np.float32:
1400
        raise ValueError('array dtype must be float32, not %r' % array.dtype)
1401
    width, height = array.shape
1402
    pointer = ffi.cast('float *', array.ctypes.data)
1403
    return ffi.new('TCOD_heightmap_t *', (width, height, pointer))
1404
1405
def heightmap_new(w, h):
1406
    """Return a new numpy.ndarray formatted for use with heightmap functions.
1407
1408
    You can pass a numpy array to any heightmap function as long as all the
1409
    following are true::
1410
    * The array is 2 dimentional.
1411
    * The array has the C_CONTIGUOUS flag.
1412
    * The array's dtype is :any:`dtype.float32`.
1413
1414
    Args:
1415
        w (int): The width of the new HeightMap.
1416
        h (int): The height of the new HeightMap.
1417
1418
    Returns:
1419
        numpy.ndarray: A C-contiguous mapping of float32 values.
1420
    """
1421
    return _np.ndarray((h, w), _np.float32)
1422
1423
def heightmap_set_value(hm, x, y, value):
1424
    """Set the value of a point on a heightmap.
1425
1426
    Args:
1427
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1428
        x (int): The x position to change.
1429
        y (int): The y position to change.
1430
        value (float): The value to set.
1431
1432
    .. deprecated:: 2.0
1433
        Do ``hm[y, x] = value`` instead.
1434
    """
1435
    hm[y, x] = value
1436
1437
def heightmap_add(hm, value):
1438
    """Add value to all values on this heightmap.
1439
1440
    Args:
1441
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1442
        value (float): A number to add to this heightmap.
1443
1444
    .. deprecated:: 2.0
1445
        Do ``hm[:] += value`` instead.
1446
    """
1447
    hm[:] += value
1448
1449
def heightmap_scale(hm, value):
1450
    """Multiply all items on this heightmap by value.
1451
1452
    Args:
1453
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1454
        value (float): A number to scale this heightmap by.
1455
1456
    .. deprecated:: 2.0
1457
        Do ``hm[:] *= value`` instead.
1458
    """
1459
    hm[:] *= value
1460
1461
def heightmap_clear(hm):
1462
    """Add value to all values on this heightmap.
1463
1464
    Args:
1465
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1466
1467
    .. deprecated:: 2.0
1468
        Do ``hm.array[:] = 0`` instead.
1469
    """
1470
    hm[:] = 0
1471
1472
def heightmap_clamp(hm, mi, ma):
1473
    """Clamp all values on this heightmap between ``mi`` and ``ma``
1474
1475
    Args:
1476
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1477
        mi (float): The lower bound to clamp to.
1478
        ma (float): The upper bound to clamp to.
1479
1480
    .. deprecated:: 2.0
1481
        Do ``hm.clip(mi, ma)`` instead.
1482
    """
1483
    hm.clip(mi, ma)
1484
1485
def heightmap_copy(hm1, hm2):
1486
    """Copy the heightmap ``hm1`` to ``hm2``.
1487
1488
    Args:
1489
        hm1 (numpy.ndarray): The source heightmap.
1490
        hm2 (numpy.ndarray): The destination heightmap.
1491
1492
    .. deprecated:: 2.0
1493
        Do ``hm2[:] = hm1[:]`` instead.
1494
    """
1495
    hm2[:] = hm1[:]
1496
1497
def heightmap_normalize(hm,  mi=0.0, ma=1.0):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
def heightmap_normalize(hm, mi=0.0, ma=1.0):
^
Loading history...
1498
    """Normalize heightmap values between ``mi`` and ``ma``.
1499
1500
    Args:
1501
        mi (float): The lowest value after normalization.
1502
        ma (float): The highest value after normalization.
1503
    """
1504
    lib.TCOD_heightmap_normalize(_heightmap_cdata(hm), mi, ma)
1505
1506
def heightmap_lerp_hm(hm1, hm2, hm3, coef):
1507
    """Perform linear interpolation between two heightmaps storing the result
1508
    in ``hm3``.
1509
1510
    This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef``
1511
1512
    Args:
1513
        hm1 (numpy.ndarray): The first heightmap.
1514
        hm2 (numpy.ndarray): The second heightmap to add to the first.
1515
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1516
        coef (float): The linear interpolation coefficient.
1517
    """
1518
    lib.TCOD_heightmap_lerp_hm(_heightmap_cdata(hm1), _heightmap_cdata(hm2),
1519
                               _heightmap_cdata(hm3), coef)
1520
1521
def heightmap_add_hm(hm1, hm2, hm3):
1522
    """Add two heightmaps together and stores the result in ``hm3``.
1523
1524
    Args:
1525
        hm1 (numpy.ndarray): The first heightmap.
1526
        hm2 (numpy.ndarray): The second heightmap to add to the first.
1527
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1528
1529
    .. deprecated:: 2.0
1530
        Do ``hm3[:] = hm1[:] + hm2[:]`` instead.
1531
    """
1532
    hm3[:] = hm1[:] + hm2[:]
1533
1534
def heightmap_multiply_hm(hm1, hm2, hm3):
1535
    """Multiplies two heightmap's together and stores the result in ``hm3``.
1536
1537
    Args:
1538
        hm1 (numpy.ndarray): The first heightmap.
1539
        hm2 (numpy.ndarray): The second heightmap to multiply with the first.
1540
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1541
1542
    .. deprecated:: 2.0
1543
        Do ``hm3[:] = hm1[:] * hm2[:]`` instead.
1544
        Alternatively you can do ``HeightMap(hm1.array[:] * hm2.array[:])``.
1545
    """
1546
    hm3[:] = hm1[:] * hm2[:]
1547
1548
def heightmap_add_hill(hm, x, y, radius, height):
1549
    """Add a hill (a half spheroid) at given position.
1550
1551
    If height == radius or -radius, the hill is a half-sphere.
1552
1553
    Args:
1554
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1555
        x (float): The x position at the center of the new hill.
1556
        y (float): The y position at the center of the new hill.
1557
        radius (float): The size of the new hill.
1558
        height (float): The height or depth of the new hill.
1559
    """
1560
    lib.TCOD_heightmap_add_hill(_heightmap_cdata(hm), x, y, radius, height)
1561
1562
def heightmap_dig_hill(hm, x, y, radius, height):
1563
    """
1564
1565
    This function takes the highest value (if height > 0) or the lowest
1566
    (if height < 0) between the map and the hill.
1567
1568
    It's main goal is to carve things in maps (like rivers) by digging hills along a curve.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (91/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1569
1570
    Args:
1571
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1572
        x (float): The x position at the center of the new carving.
1573
        y (float): The y position at the center of the new carving.
1574
        radius (float): The size of the carving.
1575
        height (float): The height or depth of the hill to dig out.
1576
    """
1577
    lib.TCOD_heightmap_dig_hill(_heightmap_cdata(hm), x, y, radius, height)
1578
1579
def heightmap_rain_erosion(hm, nbDrops, erosionCoef, sedimentationCoef, rnd=None):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (82/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1580
    """Simulate the effect of rain drops on the terrain, resulting in erosion.
1581
1582
    ``nbDrops`` should be at least hm.size.
1583
1584
    Args:
1585
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1586
        nbDrops (int): Number of rain drops to simulate.
1587
        erosionCoef (float): Amount of ground eroded on the drop's path.
1588
        sedimentationCoef (float): Amount of ground deposited when the drops
1589
                                   stops to flow.
1590
        rnd (Optional[Random]): A tcod.Random instance, or None.
1591
    """
1592
    lib.TCOD_heightmap_rain_erosion(_heightmap_cdata(hm), nbDrops, erosionCoef,
1593
                                    sedimentationCoef, rnd.random_c if rnd else ffi.NULL)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (89/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1594
1595
def heightmap_kernel_transform(hm, kernelsize, dx, dy, weight, minLevel,
1596
                               maxLevel):
1597
    """Apply a generic transformation on the map, so that each resulting cell
1598
    value is the weighted sum of several neighbour cells.
1599
1600
    This can be used to smooth/sharpen the map.
1601
1602
    Args:
1603
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1604
        kernelsize (int): Should be set to the length of the parameters::
1605
                          dx, dy, and weight.
1606
        dx (Sequence[int]): A sequence of x coorinates.
1607
        dy (Sequence[int]): A sequence of y coorinates.
1608
        weight (Sequence[float]): A sequence of kernelSize cells weight.
1609
                                  The value of each neighbour cell is scaled by
1610
                                  its corresponding weight
1611
        minLevel (float): No transformation will apply to cells
1612
                          below this value.
1613
        maxLevel (float): No transformation will apply to cells
1614
                          above this value.
1615
1616
    See examples below for a simple horizontal smoothing kernel :
1617
    replace value(x,y) with
1618
    0.33*value(x-1,y) + 0.33*value(x,y) + 0.33*value(x+1,y).
1619
    To do this, you need a kernel of size 3
1620
    (the sum involves 3 surrounding cells).
1621
    The dx,dy array will contain
1622
    * dx=-1, dy=0 for cell (x-1, y)
1623
    * dx=1, dy=0 for cell (x+1, y)
1624
    * dx=0, dy=0 for cell (x, y)
1625
    * The weight array will contain 0.33 for each cell.
1626
1627
    Example:
1628
        >>> dx = [-1, 1, 0]
1629
        >>> dy = [0, 0, 0]
1630
        >>> weight = [0.33, 0.33, 0.33]
1631
        >>> tcod.heightMap_kernel_transform(heightmap,3,dx,dy,weight,0.0,1.0)
1632
    """
1633
    cdx = ffi.new('int[]', dx)
1634
    cdy = ffi.new('int[]', dy)
1635
    cweight = ffi.new('float[]', weight)
1636
    lib.TCOD_heightmap_kernel_transform(_heightmap_cdata(hm), kernelsize,
1637
                                        cdx, cdy, cweight, minLevel, maxLevel)
1638
1639
def heightmap_add_voronoi(hm, nbPoints, nbCoef, coef, rnd=None):
1640
    """Add values from a Voronoi diagram to the heightmap.
1641
1642
    Args:
1643
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1644
        nbPoints (Any): Number of Voronoi sites.
1645
        nbCoef (int): The diagram value is calculated from the nbCoef
1646
                      closest sites.
1647
        coef (Sequence[float]): The distance to each site is scaled by the
1648
                                corresponding coef.
1649
                                Closest site : coef[0],
1650
                                second closest site : coef[1], ...
1651
        rnd (Optional[Random]): A Random instance, or None.
1652
    """
1653
    nbPoints = len(coef)
1654
    ccoef = ffi.new('float[]', coef)
1655
    lib.TCOD_heightmap_add_voronoi(_heightmap_cdata(hm), nbPoints,
1656
                                   nbCoef, ccoef, rnd.random_c if rnd else ffi.NULL)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (84/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1657
1658
def heightmap_add_fbm(hm, noise, mulx, muly, addx, addy, octaves, delta, scale):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (80/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
1659
    """Add FBM noise to the heightmap.
1660
1661
    The noise coordinate for each map cell is
1662
    `((x + addx) * mulx / width, (y + addy) * muly / height)`.
1663
1664
    The value added to the heightmap is `delta + noise * scale`.
1665
1666
    Args:
1667
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1668
        noise (Noise): A Noise instance.
1669
        mulx (float): Scaling of each x coordinate.
1670
        muly (float): Scaling of each y coordinate.
1671
        addx (float): Translation of each x coordinate.
1672
        addy (float): Translation of each y coordinate.
1673
        octaves (float): Number of octaves in the FBM sum.
1674
        delta (float): The value added to all heightmap cells.
1675
        scale (float): The noise value is scaled with this parameter.
1676
    """
1677
    noise = noise.noise_c if noise is not None else ffi.NULL
1678
    lib.TCOD_heightmap_add_fbm(_heightmap_cdata(hm), noise,
1679
                               mulx, muly, addx, addy, octaves, delta, scale)
1680
1681
def heightmap_scale_fbm(hm, noise, mulx, muly, addx, addy, octaves, delta,
1682
                        scale):
1683
    """Multiply the heighmap values with FBM noise.
1684
1685
    Args:
1686
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1687
        noise (Noise): A Noise instance.
1688
        mulx (float): Scaling of each x coordinate.
1689
        muly (float): Scaling of each y coordinate.
1690
        addx (float): Translation of each x coordinate.
1691
        addy (float): Translation of each y coordinate.
1692
        octaves (float): Number of octaves in the FBM sum.
1693
        delta (float): The value added to all heightmap cells.
1694
        scale (float): The noise value is scaled with this parameter.
1695
    """
1696
    noise = noise.noise_c if noise is not None else ffi.NULL
1697
    lib.TCOD_heightmap_scale_fbm(_heightmap_cdata(hm), noise,
1698
                                 mulx, muly, addx, addy, octaves, delta, scale)
1699
1700
def heightmap_dig_bezier(hm, px, py, startRadius, startDepth, endRadius,
1701
                         endDepth):
1702
    """Carve a path along a cubic Bezier curve.
1703
1704
    Both radius and depth can vary linearly along the path.
1705
1706
    Args:
1707
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1708
        px (Sequence[int]): The 4 `x` coordinates of the Bezier curve.
1709
        py (Sequence[int]): The 4 `y` coordinates of the Bezier curve.
1710
        startRadius (float): The starting radius size.
1711
        startDepth (float): The starting depth.
1712
        endRadius (float): The ending radius size.
1713
        endDepth (float): The ending depth.
1714
    """
1715
    lib.TCOD_heightmap_dig_bezier(_heightmap_cdata(hm), px, py, startRadius,
1716
                                   startDepth, endRadius,
1717
                                   endDepth)
1718
1719
def heightmap_get_value(hm, x, y):
1720
    """Return the value at ``x``, ``y`` in a heightmap.
1721
1722
    Args:
1723
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1724
        x (int): The x position to pick.
1725
        y (int): The y position to pick.
1726
1727
    Returns:
1728
        float: The value at ``x``, ``y``.
1729
1730
    .. deprecated:: 2.0
1731
        Do ``value = hm[y, x]`` instead.
1732
    """
1733
    # explicit type conversion to pass test, (test should have been better.)
1734
    return float(hm[y, x])
1735
1736
def heightmap_get_interpolated_value(hm, x, y):
1737
    """Return the interpolated height at non integer coordinates.
1738
1739
    Args:
1740
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1741
        x (float): A floating point x coordinate.
1742
        y (float): A floating point y coordinate.
1743
1744
    Returns:
1745
        float: The value at ``x``, ``y``.
1746
    """
1747
    return lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm),
1748
                                                     x, y)
1749
1750
def heightmap_get_slope(hm, x, y):
1751
    """Return the slope between 0 and (pi / 2) at given coordinates.
1752
1753
    Args:
1754
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1755
        x (int): The x coordinate.
1756
        y (int): The y coordinate.
1757
1758
    Returns:
1759
        float: The steepness at ``x``, ``y``.  From 0 to (pi / 2)
1760
    """
1761
    return lib.TCOD_heightmap_get_slope(_heightmap_cdata(hm), x, y)
1762
1763
def heightmap_get_normal(hm, x, y, waterLevel):
1764
    """Return the map normal at given coordinates.
1765
1766
    Args:
1767
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1768
        x (float): The x coordinate.
1769
        y (float): The y coordinate.
1770
        waterLevel (float): The heightmap is considered flat below this value.
1771
1772
    Returns:
1773
        Tuple[float, float, float]: An (x, y, z) vector normal.
1774
    """
1775
    cn = ffi.new('float[3]')
1776
    lib.TCOD_heightmap_get_normal(_heightmap_cdata(hm), x, y, cn, waterLevel)
1777
    return tuple(cn)
1778
1779
def heightmap_count_cells(hm, mi, ma):
1780
    """Return the number of map cells which value is between ``mi`` and ``ma``.
1781
1782
    Args:
1783
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1784
        mi (float): The lower bound.
1785
        ma (float): The upper bound.
1786
1787
    Returns:
1788
        int: The count of values which fall between ``mi`` and ``ma``.
1789
    """
1790
    return lib.TCOD_heightmap_count_cells(_heightmap_cdata(hm), mi, ma)
1791
1792
def heightmap_has_land_on_border(hm, waterlevel):
1793
    """Returns True if the map edges are below ``waterlevel``, otherwise False.
1794
1795
    Args:
1796
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1797
        waterLevel (float): The water level to use.
1798
1799
    Returns:
1800
        bool: True if the map edges are below ``waterlevel``, otherwise False.
1801
    """
1802
    return lib.TCOD_heightmap_has_land_on_border(_heightmap_cdata(hm),
1803
                                                 waterlevel)
1804
1805
def heightmap_get_minmax(hm):
1806
    """Return the min and max values of this heightmap.
1807
1808
    Args:
1809
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1810
1811
    Returns:
1812
        Tuple[float, float]: The (min, max) values.
1813
1814
    .. deprecated:: 2.0
1815
        Do ``hm.min()`` or ``hm.max()`` instead.
1816
    """
1817
    mi = ffi.new('float *')
1818
    ma = ffi.new('float *')
1819
    lib.TCOD_heightmap_get_minmax(_heightmap_cdata(hm), mi, ma)
1820
    return mi[0], ma[0]
1821
1822
def heightmap_delete(hm):
0 ignored issues
show
Unused Code introduced by
The argument hm seems to be unused.
Loading history...
1823
    """Does nothing.
1824
1825
    .. deprecated:: 2.0
1826
        libtcod-cffi deletes heightmaps automatically.
1827
    """
1828
    pass
1829
1830
def image_new(width, height):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1831
    return tcod.image.Image(width, height)
1832
1833
def image_clear(image, col):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1834
    image.clear(col)
1835
1836
def image_invert(image):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1837
    image.invert()
1838
1839
def image_hflip(image):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1840
    image.hflip()
1841
1842
def image_rotate90(image, num=1):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1843
    image.rotate90(num)
1844
1845
def image_vflip(image):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1846
    image.vflip()
1847
1848
def image_scale(image, neww, newh):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1849
    image.scale(neww, newh)
1850
1851
def image_set_key_color(image, col):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1852
    image.set_key_color(col)
1853
1854
def image_get_alpha(image, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1855
    image.get_alpha(x, y)
1856
1857
def image_is_pixel_transparent(image, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1858
    lib.TCOD_image_is_pixel_transparent(image.image_c, x, y)
1859
1860
def image_load(filename):
1861
    """Load an image file into an Image instance and return it.
1862
1863
    Args:
1864
        filename (AnyStr): Path to a .bmp or .png image file.
1865
    """
1866
    return tcod.image.Image._from_cdata(
1867
        ffi.gc(lib.TCOD_image_load(_bytes(filename)),
1868
               lib.TCOD_image_delete)
1869
        )
1870
1871
def image_from_console(console):
1872
    """Return an Image with a Consoles pixel data.
1873
1874
    This effectively takes a screen-shot of the Console.
1875
1876
    Args:
1877
        console (Console): Any Console instance.
1878
    """
1879
    return tcod.image.Image._from_cdata(
1880
        ffi.gc(
1881
            lib.TCOD_image_from_console(
1882
                console.console_c if console else ffi.NULL
1883
                ),
1884
            lib.TCOD_image_delete,
1885
            )
1886
        )
1887
1888
def image_refresh_console(image, console):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1889
    image.refresh_console(console)
1890
1891
def image_get_size(image):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1892
    return image.width, image.height
1893
1894
def image_get_pixel(image, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1895
    return image.get_pixel(x, y)
1896
1897
def image_get_mipmap_pixel(image, x0, y0, x1, y1):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1898
    return image.get_mipmap_pixel(x0, y0, x1, y1)
1899
1900
def image_put_pixel(image, x, y, col):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1901
    image.put_pixel(x, y, col)
1902
1903
def image_blit(image, console, x, y, bkgnd_flag, scalex, scaley, angle):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1904
    image.blit(console, x, y, bkgnd_flag, scalex, scaley, angle)
1905
1906
def image_blit_rect(image, console, x, y, w, h, bkgnd_flag):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1907
    image.blit_rect(console, x, y, w, h, bkgnd_flag)
1908
1909
def image_blit_2x(image, console, dx, dy, sx=0, sy=0, w=-1, h=-1):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1910
    image.blit_2x(console, dx, dy, sx, sy, w, h)
1911
1912
def image_save(image, filename):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
1913
    image.save_as(filename)
1914
1915
def image_delete(image):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The argument image seems to be unused.
Loading history...
1916
    pass
1917
1918
def line_init(xo, yo, xd, yd):
1919
    """Initilize a line whose points will be returned by `line_step`.
1920
1921
    This function does not return anything on its own.
1922
1923
    Does not include the origin point.
1924
1925
    Args:
1926
        xo (int): X starting point.
1927
        yo (int): Y starting point.
1928
        xd (int): X destination point.
1929
        yd (int): Y destination point.
1930
1931
    .. deprecated:: 2.0
1932
       Use `line_iter` instead.
1933
    """
1934
    lib.TCOD_line_init(xo, yo, xd, yd)
1935
1936
def line_step():
1937
    """After calling line_init returns (x, y) points of the line.
1938
1939
    Once all points are exhausted this function will return (None, None)
1940
1941
    Returns:
1942
        Union[Tuple[int, int], Tuple[None, None]]:
1943
            The next (x, y) point of the line setup by line_init,
1944
            or (None, None) if there are no more points.
1945
1946
    .. deprecated:: 2.0
1947
       Use `line_iter` instead.
1948
    """
1949
    x = ffi.new('int *')
1950
    y = ffi.new('int *')
1951
    ret = lib.TCOD_line_step(x, y)
1952
    if not ret:
1953
        return x[0], y[0]
1954
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1955
1956
_line_listener_lock = _threading.Lock()
1957
1958
def line(xo, yo, xd, yd, py_callback):
1959
    """ Iterate over a line using a callback function.
1960
1961
    Your callback function will take x and y parameters and return True to
1962
    continue iteration or False to stop iteration and return.
1963
1964
    This function includes both the start and end points.
1965
1966
    Args:
1967
        xo (int): X starting point.
1968
        yo (int): Y starting point.
1969
        xd (int): X destination point.
1970
        yd (int): Y destination point.
1971
        py_callback (Callable[[int, int], bool]):
1972
            A callback which takes x and y parameters and returns bool.
1973
1974
    Returns:
1975
        bool: False if the callback cancels the line interation by
1976
              returning False or None, otherwise True.
1977
1978
    .. deprecated:: 2.0
1979
       Use `line_iter` instead.
1980
    """
1981
    with _PropagateException() as propagate:
1982
        with _line_listener_lock:
1983
            @ffi.def_extern(onerror=propagate)
1984
            def _pycall_line_listener(x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The variable _pycall_line_listener seems to be unused.
Loading history...
1985
                return py_callback(x, y)
1986
            return bool(lib.TCOD_line(xo, yo, xd, yd,
1987
                                       lib._pycall_line_listener))
1988
1989
def line_iter(xo, yo, xd, yd):
1990
    """ returns an iterator
1991
1992
    This iterator does not include the origin point.
1993
1994
    Args:
1995
        xo (int): X starting point.
1996
        yo (int): Y starting point.
1997
        xd (int): X destination point.
1998
        yd (int): Y destination point.
1999
2000
    Returns:
2001
        Iterator[Tuple[int,int]]: An iterator of (x,y) points.
2002
    """
2003
    data = ffi.new('TCOD_bresenham_data_t *')
2004
    lib.TCOD_line_init_mt(xo, yo, xd, yd, data)
2005
    x = ffi.new('int *')
2006
    y = ffi.new('int *')
2007
    yield xo, yo
2008
    while not lib.TCOD_line_step_mt(x, y, data):
2009
        yield (x[0], y[0])
2010
2011
FOV_BASIC = 0
2012
FOV_DIAMOND = 1
2013
FOV_SHADOW = 2
2014
FOV_PERMISSIVE_0 = 3
2015
FOV_PERMISSIVE_1 = 4
2016
FOV_PERMISSIVE_2 = 5
2017
FOV_PERMISSIVE_3 = 6
2018
FOV_PERMISSIVE_4 = 7
2019
FOV_PERMISSIVE_5 = 8
2020
FOV_PERMISSIVE_6 = 9
2021
FOV_PERMISSIVE_7 = 10
2022
FOV_PERMISSIVE_8 = 11
2023
FOV_RESTRICTIVE = 12
2024
NB_FOV_ALGORITHMS = 13
2025
2026
def map_new(w, h):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2027
    return tcod.map.Map(w, h)
2028
2029
def map_copy(source, dest):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2030
    return lib.TCOD_map_copy(source.map_c, dest.map_c)
2031
2032
def map_set_properties(m, x, y, isTrans, isWalk):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2033
    lib.TCOD_map_set_properties(m.map_c, x, y, isTrans, isWalk)
2034
2035
def map_clear(m,walkable=False,transparent=False):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
def map_clear(m,walkable=False,transparent=False):
^
Loading history...
Coding Style introduced by
Exactly one space required after comma
def map_clear(m,walkable=False,transparent=False):
^
Loading history...
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2036
    # walkable/transparent looks incorrectly ordered here.
2037
    # TODO: needs test.
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
2038
    lib.TCOD_map_clear(m.map_c, walkable, transparent)
2039
2040
def map_compute_fov(m, x, y, radius=0, light_walls=True, algo=FOV_RESTRICTIVE ):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (80/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Coding Style introduced by
No space allowed before bracket
def map_compute_fov(m, x, y, radius=0, light_walls=True, algo=FOV_RESTRICTIVE ):
^
Loading history...
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2041
    lib.TCOD_map_compute_fov(m.map_c, x, y, radius, light_walls, algo)
2042
2043
def map_is_in_fov(m, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2044
    return lib.TCOD_map_is_in_fov(m.map_c, x, y)
2045
2046
def map_is_transparent(m, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2047
    return lib.TCOD_map_is_transparent(m.map_c, x, y)
2048
2049
def map_is_walkable(m, x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2050
    return lib.TCOD_map_is_walkable(m.map_c, x, y)
2051
2052
def map_delete(m):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The argument m seems to be unused.
Loading history...
2053
    pass
2054
2055
def map_get_width(map):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in map.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2056
    return map.width
2057
2058
def map_get_height(map):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in map.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2059
    return map.height
2060
2061
def mouse_show_cursor(visible):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2062
    lib.TCOD_mouse_show_cursor(visible)
2063
2064
def mouse_is_cursor_visible():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2065
    return lib.TCOD_mouse_is_cursor_visible()
2066
2067
def mouse_move(x, y):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2068
    lib.TCOD_mouse_move(x, y)
2069
2070
def mouse_get_status():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2071
    return Mouse(lib.TCOD_mouse_get_status())
2072
2073
def namegen_parse(filename,random=None):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
def namegen_parse(filename,random=None):
^
Loading history...
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2074
    lib.TCOD_namegen_parse(_bytes(filename), random or ffi.NULL)
2075
2076
def namegen_generate(name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2077
    return _unpack_char_p(lib.TCOD_namegen_generate(_bytes(name), False))
2078
2079
def namegen_generate_custom(name, rule):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2080
    return _unpack_char_p(lib.TCOD_namegen_generate(_bytes(name),
2081
                                                     _bytes(rule), False))
2082
2083
def namegen_get_sets():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2084
    sets = lib.TCOD_namegen_get_sets()
2085
    try:
2086
        lst = []
2087
        while not lib.TCOD_list_is_empty(sets):
2088
            lst.append(_unpack_char_p(ffi.cast('char *', lib.TCOD_list_pop(sets))))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (83/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
2089
    finally:
2090
        lib.TCOD_list_delete(sets)
2091
    return lst
2092
2093
def namegen_destroy():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2094
    lib.TCOD_namegen_destroy()
2095
2096
def noise_new(dim, h=NOISE_DEFAULT_HURST, l=NOISE_DEFAULT_LACUNARITY,
2097
        random=None):
2098
    """Return a new Noise instance.
2099
2100
    Args:
2101
        dim (int): Number of dimensions.  From 1 to 4.
2102
        h (float): The hurst exponent.  Should be in the 0.0-1.0 range.
2103
        l (float): The noise lacunarity.
2104
        random (Optional[Random]): A Random instance, or None.
2105
2106
    Returns:
2107
        Noise: The new Noise instance.
2108
    """
2109
    return tcod.noise.Noise(dim, hurst=h, lacunarity=l, rand=random)
2110
2111
def noise_set_type(n, typ):
2112
    """Set a Noise objects default noise algorithm.
2113
2114
    Args:
2115
        typ (int): Any NOISE_* constant.
2116
    """
2117
    n.algorithm = typ
2118
2119
def noise_get(n, f, typ=NOISE_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'NOISE_DEFAULT'
Loading history...
2120
    """Return the noise value sampled from the ``f`` coordinate.
2121
2122
    ``f`` should be a tuple or list with a length matching
2123
    :any:`Noise.dimensions`.
2124
    If ``f`` is shoerter than :any:`Noise.dimensions` the missing coordinates
2125
    will be filled with zeros.
2126
2127
    Args:
2128
        n (Noise): A Noise instance.
2129
        f (Sequence[float]): The point to sample the noise from.
2130
        typ (int): The noise algorithm to use.
2131
2132
    Returns:
2133
        float: The sampled noise value.
2134
    """
2135
    return lib.TCOD_noise_get_ex(n.noise_c, ffi.new('float[4]', f), typ)
2136
2137
def noise_get_fbm(n, f, oc, typ=NOISE_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'NOISE_DEFAULT'
Loading history...
2138
    """Return the fractal Brownian motion sampled from the ``f`` coordinate.
2139
2140
    Args:
2141
        n (Noise): A Noise instance.
2142
        f (Sequence[float]): The point to sample the noise from.
2143
        typ (int): The noise algorithm to use.
2144
        octaves (float): The level of level.  Should be more than 1.
2145
2146
    Returns:
2147
        float: The sampled noise value.
2148
    """
2149
    return lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new('float[4]', f),
2150
                                     oc, typ)
2151
2152
def noise_get_turbulence(n, f, oc, typ=NOISE_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'NOISE_DEFAULT'
Loading history...
2153
    """Return the turbulence noise sampled from the ``f`` coordinate.
2154
2155
    Args:
2156
        n (Noise): A Noise instance.
2157
        f (Sequence[float]): The point to sample the noise from.
2158
        typ (int): The noise algorithm to use.
2159
        octaves (float): The level of level.  Should be more than 1.
2160
2161
    Returns:
2162
        float: The sampled noise value.
2163
    """
2164
    return lib.TCOD_noise_get_turbulence_ex(n.noise_c, ffi.new('float[4]', f),
2165
                                            oc, typ)
2166
2167
def noise_delete(n):
0 ignored issues
show
Unused Code introduced by
The argument n seems to be unused.
Loading history...
2168
    """Does nothing."""
2169
    pass
2170
2171
_chr = chr
2172
try:
2173
    _chr = unichr # Python 2
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'unichr'
Loading history...
2174
except NameError:
0 ignored issues
show
Unused Code introduced by
This except handler seems to be unused and could be removed.

Except handlers which only contain pass and do not have an else clause can usually simply be removed:

try:
    raises_exception()
except:  # Could be removed
    pass
Loading history...
2175
    pass
2176
2177
def _unpack_union(type, union):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in type.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2178
    '''
2179
        unpack items from parser new_property (value_converter)
2180
    '''
2181
    if type == lib.TCOD_TYPE_BOOL:
2182
        return bool(union.b)
2183
    elif type == lib.TCOD_TYPE_CHAR:
2184
        return _unicode(union.c)
2185
    elif type == lib.TCOD_TYPE_INT:
2186
        return union.i
2187
    elif type == lib.TCOD_TYPE_FLOAT:
2188
        return union.f
2189
    elif (type == lib.TCOD_TYPE_STRING or
2190
         lib.TCOD_TYPE_VALUELIST15 >= type >= lib.TCOD_TYPE_VALUELIST00):
2191
         return _unpack_char_p(union.s)
0 ignored issues
show
Coding Style introduced by
The indentation here looks off. 8 spaces were expected, but 9 were found.
Loading history...
2192
    elif type == lib.TCOD_TYPE_COLOR:
2193
        return Color._new_from_cdata(union.col)
2194
    elif type == lib.TCOD_TYPE_DICE:
2195
        return Dice(union.dice)
2196
    elif type & lib.TCOD_TYPE_LIST:
2197
        return _convert_TCODList(union.list, type & 0xFF)
2198
    else:
2199
        raise RuntimeError('Unknown libtcod type: %i' % type)
2200
2201
def _convert_TCODList(clist, type):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in type.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2202
    return [_unpack_union(type, lib.TDL_list_get_union(clist, i))
2203
            for i in range(lib.TCOD_list_size(clist))]
2204
2205
def parser_new():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2206
    return ffi.gc(lib.TCOD_parser_new(), lib.TCOD_parser_delete)
2207
2208
def parser_new_struct(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2209
    return lib.TCOD_parser_new_struct(parser, name)
2210
2211
# prevent multiple threads from messing with def_extern callbacks
2212
_parser_callback_lock = _threading.Lock()
2213
2214
def parser_run(parser, filename, listener=None):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2215
    if not listener:
2216
        lib.TCOD_parser_run(parser, _bytes(filename), ffi.NULL)
2217
        return
2218
2219
    propagate_manager = _PropagateException()
2220
    propagate = propagate_manager.propagate
2221
2222
    with _parser_callback_lock:
2223
        clistener = ffi.new('TCOD_parser_listener_t *')
2224
2225
        @ffi.def_extern(onerror=propagate)
2226
        def pycall_parser_new_struct(struct, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2227
            return listener.end_struct(struct, _unpack_char_p(name))
2228
2229
        @ffi.def_extern(onerror=propagate)
2230
        def pycall_parser_new_flag(name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2231
            return listener.new_flag(_unpack_char_p(name))
2232
2233
        @ffi.def_extern(onerror=propagate)
2234
        def pycall_parser_new_property(propname, type, value):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in type.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2235
            return listener.new_property(_unpack_char_p(propname), type,
2236
                                         _unpack_union(type, value))
2237
2238
        @ffi.def_extern(onerror=propagate)
2239
        def pycall_parser_end_struct(struct, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2240
            return listener.end_struct(struct, _unpack_char_p(name))
2241
2242
        @ffi.def_extern(onerror=propagate)
2243
        def pycall_parser_error(msg):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2244
            listener.error(_unpack_char_p(msg))
2245
2246
        clistener.new_struct = lib.pycall_parser_new_struct
2247
        clistener.new_flag = lib.pycall_parser_new_flag
2248
        clistener.new_property = lib.pycall_parser_new_property
2249
        clistener.end_struct = lib.pycall_parser_end_struct
2250
        clistener.error = lib.pycall_parser_error
2251
2252
        with propagate_manager:
2253
            lib.TCOD_parser_run(parser, _bytes(filename), clistener)
2254
2255
def parser_delete(parser):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The argument parser seems to be unused.
Loading history...
2256
    pass
2257
2258
def parser_get_bool_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2259
    return bool(lib.TCOD_parser_get_bool_property(parser, _bytes(name)))
2260
2261
def parser_get_int_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2262
    return lib.TCOD_parser_get_int_property(parser, _bytes(name))
2263
2264
def parser_get_char_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2265
    return _chr(lib.TCOD_parser_get_char_property(parser, _bytes(name)))
2266
2267
def parser_get_float_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2268
    return lib.TCOD_parser_get_float_property(parser, _bytes(name))
2269
2270
def parser_get_string_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2271
    return _unpack_char_p(
2272
        lib.TCOD_parser_get_string_property(parser, _bytes(name)))
2273
2274
def parser_get_color_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2275
    return Color._new_from_cdata(
2276
        lib.TCOD_parser_get_color_property(parser, _bytes(name)))
2277
2278
def parser_get_dice_property(parser, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2279
    d = ffi.new('TCOD_dice_t *')
2280
    lib.TCOD_parser_get_dice_property_py(parser, _bytes(name), d)
2281
    return Dice(d)
2282
2283
def parser_get_list_property(parser, name, type):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in type.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
2284
    clist = lib.TCOD_parser_get_list_property(parser, _bytes(name), type)
2285
    return _convert_TCODList(clist, type)
2286
2287
RNG_MT = 0
2288
RNG_CMWC = 1
2289
2290
DISTRIBUTION_LINEAR = 0
2291
DISTRIBUTION_GAUSSIAN = 1
2292
DISTRIBUTION_GAUSSIAN_RANGE = 2
2293
DISTRIBUTION_GAUSSIAN_INVERSE = 3
2294
DISTRIBUTION_GAUSSIAN_RANGE_INVERSE = 4
2295
2296
def random_get_instance():
2297
    """Return the default Random instance.
2298
2299
    Returns:
2300
        Random: A Random instance using the default random number generator.
2301
    """
2302
    return tcod.random.Random._new_from_cdata(
2303
        ffi.cast('mersenne_data_t*', lib.TCOD_random_get_instance()))
2304
2305
def random_new(algo=RNG_CMWC):
2306
    """Return a new Random instance.  Using ``algo``.
2307
2308
    Args:
2309
        algo (int): The random number algorithm to use.
2310
2311
    Returns:
2312
        Random: A new Random instance using the given algorithm.
2313
    """
2314
    return tcod.random.Random(algo)
2315
2316
def random_new_from_seed(seed, algo=RNG_CMWC):
2317
    """Return a new Random instance.  Using the given ``seed`` and ``algo``.
2318
2319
    Args:
2320
        seed (Hashable): The RNG seed.  Should be a 32-bit integer, but any
2321
                         hashable object is accepted.
2322
        algo (int): The random number algorithm to use.
2323
2324
    Returns:
2325
        Random: A new Random instance using the given algorithm.
2326
    """
2327
    return tcod.random.Random(algo, seed)
2328
2329
def random_set_distribution(rnd, dist):
2330
    """Change the distribution mode of a random number generator.
2331
2332
    Args:
2333
        rnd (Optional[Random]): A Random instance, or None to use the default.
2334
        dist (int): The distribution mode to use.  Should be DISTRIBUTION_*.
2335
    """
2336
    lib.TCOD_random_set_distribution(rnd.random_c if rnd else ffi.NULL, dist)
2337
2338
def random_get_int(rnd, mi, ma):
2339
    """Return a random integer in the range: ``mi`` <= n <= ``ma``.
2340
2341
    The result is affacted by calls to :any:`random_set_distribution`.
2342
2343
    Args:
2344
        rnd (Optional[Random]): A Random instance, or None to use the default.
2345
        low (int): The lower bound of the random range, inclusive.
2346
        high (int): The upper bound of the random range, inclusive.
2347
2348
    Returns:
2349
        int: A random integer in the range ``mi`` <= n <= ``ma``.
2350
    """
2351
    return lib.TCOD_random_get_int(rnd.random_c if rnd else ffi.NULL, mi, ma)
2352
2353
def random_get_float(rnd, mi, ma):
2354
    """Return a random float in the range: ``mi`` <= n <= ``ma``.
2355
2356
    The result is affacted by calls to :any:`random_set_distribution`.
2357
2358
    Args:
2359
        rnd (Optional[Random]): A Random instance, or None to use the default.
2360
        low (float): The lower bound of the random range, inclusive.
2361
        high (float): The upper bound of the random range, inclusive.
2362
2363
    Returns:
2364
        float: A random double precision float
2365
               in the range ``mi`` <= n <= ``ma``.
2366
    """
2367
    return lib.TCOD_random_get_double(
2368
        rnd.random_c if rnd else ffi.NULL, mi, ma)
2369
2370
def random_get_double(rnd, mi, ma):
2371
    """Return a random float in the range: ``mi`` <= n <= ``ma``.
2372
2373
    .. deprecated:: 2.0
2374
        Use :any:`random_get_float` instead.
2375
        Both funtions return a double precision float.
2376
    """
2377
    return lib.TCOD_random_get_double(
2378
        rnd.random_c if rnd else ffi.NULL, mi, ma)
2379
2380
def random_get_int_mean(rnd, mi, ma, mean):
2381
    """Return a random weighted integer in the range: ``mi`` <= n <= ``ma``.
2382
2383
    The result is affacted by calls to :any:`random_set_distribution`.
2384
2385
    Args:
2386
        rnd (Optional[Random]): A Random instance, or None to use the default.
2387
        low (int): The lower bound of the random range, inclusive.
2388
        high (int): The upper bound of the random range, inclusive.
2389
        mean (int): The mean return value.
2390
2391
    Returns:
2392
        int: A random weighted integer in the range ``mi`` <= n <= ``ma``.
2393
    """
2394
    return lib.TCOD_random_get_int_mean(
2395
        rnd.random_c if rnd else ffi.NULL, mi, ma, mean)
2396
2397
def random_get_float_mean(rnd, mi, ma, mean):
2398
    """Return a random weighted float in the range: ``mi`` <= n <= ``ma``.
2399
2400
    The result is affacted by calls to :any:`random_set_distribution`.
2401
2402
    Args:
2403
        rnd (Optional[Random]): A Random instance, or None to use the default.
2404
        low (float): The lower bound of the random range, inclusive.
2405
        high (float): The upper bound of the random range, inclusive.
2406
        mean (float): The mean return value.
2407
2408
    Returns:
2409
        float: A random weighted double precision float
2410
               in the range ``mi`` <= n <= ``ma``.
2411
    """
2412
    return lib.TCOD_random_get_double_mean(
2413
        rnd.random_c if rnd else ffi.NULL, mi, ma, mean)
2414
2415
def random_get_double_mean(rnd, mi, ma, mean):
2416
    """Return a random weighted float in the range: ``mi`` <= n <= ``ma``.
2417
2418
    .. deprecated:: 2.0
2419
        Use :any:`random_get_float_mean` instead.
2420
        Both funtions return a double precision float.
2421
    """
2422
    return lib.TCOD_random_get_double_mean(
2423
        rnd.random_c if rnd else ffi.NULL, mi, ma, mean)
2424
2425
def random_save(rnd):
2426
    """Return a copy of a random number generator.
2427
2428
    Args:
2429
        rnd (Optional[Random]): A Random instance, or None to use the default.
2430
2431
    Returns:
2432
        Random: A Random instance with a copy of the random generator.
2433
    """
2434
    return tcod.random.Random._new_from_cdata(
2435
        ffi.gc(
2436
            ffi.cast('mersenne_data_t*',
2437
                     lib.TCOD_random_save(rnd.random_c if rnd else ffi.NULL)),
2438
            lib.TCOD_random_delete),
2439
        )
2440
2441
def random_restore(rnd, backup):
2442
    """Restore a random number generator from a backed up copy.
2443
2444
    Args:
2445
        rnd (Optional[Random]): A Random instance, or None to use the default.
2446
        backup (Random): The Random instance which was used as a backup.
2447
    """
2448
    lib.TCOD_random_restore(rnd.random_c if rnd else ffi.NULL,
2449
                            backup.random_c)
2450
2451
def random_delete(rnd):
0 ignored issues
show
Unused Code introduced by
The argument rnd seems to be unused.
Loading history...
2452
    """Does nothing."""
2453
    pass
2454
2455
def struct_add_flag(struct, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2456
    lib.TCOD_struct_add_flag(struct, name)
2457
2458
def struct_add_property(struct, name, typ, mandatory):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2459
    lib.TCOD_struct_add_property(struct, name, typ, mandatory)
2460
2461
def struct_add_value_list(struct, name, value_list, mandatory):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2462
    CARRAY = c_char_p * (len(value_list) + 1)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'c_char_p'
Loading history...
2463
    cvalue_list = CARRAY()
2464
    for i in range(len(value_list)):
2465
        cvalue_list[i] = cast(value_list[i], c_char_p)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'cast'
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'c_char_p'
Loading history...
2466
    cvalue_list[len(value_list)] = 0
2467
    lib.TCOD_struct_add_value_list(struct, name, cvalue_list, mandatory)
2468
2469
def struct_add_list_property(struct, name, typ, mandatory):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2470
    lib.TCOD_struct_add_list_property(struct, name, typ, mandatory)
2471
2472
def struct_add_structure(struct, sub_struct):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2473
    lib.TCOD_struct_add_structure(struct, sub_struct)
2474
2475
def struct_get_name(struct):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2476
    return _unpack_char_p(lib.TCOD_struct_get_name(struct))
2477
2478
def struct_is_mandatory(struct, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2479
    return lib.TCOD_struct_is_mandatory(struct, name)
2480
2481
def struct_get_type(struct, name):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2482
    return lib.TCOD_struct_get_type(struct, name)
2483
2484
# high precision time functions
2485
def sys_set_fps(fps):
2486
    """Set the maximum frame rate.
2487
2488
    You can disable the frame limit again by setting fps to 0.
2489
2490
    Args:
2491
        fps (int): A frame rate limit (i.e. 60)
2492
    """
2493
    lib.TCOD_sys_set_fps(fps)
2494
2495
def sys_get_fps():
2496
    """Return the current frames per second.
2497
2498
    This the actual frame rate, not the frame limit set by
2499
    :any:`tcod.sys_set_fps`.
2500
2501
    This number is updated every second.
2502
2503
    Returns:
2504
        int: The currently measured frame rate.
2505
    """
2506
    return lib.TCOD_sys_get_fps()
2507
2508
def sys_get_last_frame_length():
2509
    """Return the delta time of the last rendered frame in seconds.
2510
2511
    Returns:
2512
        float: The delta time of the last rendered frame.
2513
    """
2514
    return lib.TCOD_sys_get_last_frame_length()
2515
2516
def sys_sleep_milli(val):
2517
    """Sleep for 'val' milliseconds.
2518
2519
    Args:
2520
        val (int): Time to sleep for in milliseconds.
2521
2522
    .. deprecated:: 2.0
2523
       Use :any:`time.sleep` instead.
2524
    """
2525
    lib.TCOD_sys_sleep_milli(val)
2526
2527
def sys_elapsed_milli():
2528
    """Get number of milliseconds since the start of the program.
2529
2530
    Returns:
2531
        int: Time since the progeam has started in milliseconds.
2532
2533
    .. deprecated:: 2.0
2534
       Use :any:`time.clock` instead.
2535
    """
2536
    return lib.TCOD_sys_elapsed_milli()
2537
2538
def sys_elapsed_seconds():
2539
    """Get number of seconds since the start of the program.
2540
2541
    Returns:
2542
        float: Time since the progeam has started in seconds.
2543
2544
    .. deprecated:: 2.0
2545
       Use :any:`time.clock` instead.
2546
    """
2547
    return lib.TCOD_sys_elapsed_seconds()
2548
2549
def sys_set_renderer(renderer):
2550
    """Change the current rendering mode to renderer.
2551
2552
    .. deprecated:: 2.0
2553
       RENDERER_GLSL and RENDERER_OPENGL are not currently available.
2554
    """
2555
    lib.TCOD_sys_set_renderer(renderer)
2556
2557
def sys_get_renderer():
2558
    """Return the current rendering mode.
2559
2560
    """
2561
    return lib.TCOD_sys_get_renderer()
2562
2563
# easy screenshots
2564
def sys_save_screenshot(name=None):
2565
    """Save a screenshot to a file.
2566
2567
    By default this will automatically save screenshots in the working
2568
    directory.
2569
2570
    The automatic names are formatted as screenshotNNN.png.  For example:
2571
    screenshot000.png, screenshot001.png, etc.  Whichever is available first.
2572
2573
    Args:
2574
        file Optional[AnyStr]: File path to save screenshot.
2575
    """
2576
    if name is not None:
2577
        name = _bytes(name)
2578
    lib.TCOD_sys_save_screenshot(name or ffi.NULL)
2579
2580
# custom fullscreen resolution
2581
def sys_force_fullscreen_resolution(width, height):
2582
    """Force a specific resolution in fullscreen.
2583
2584
    Will use the smallest available resolution so that:
2585
2586
    * resolution width >= width and
2587
      resolution width >= root console width * font char width
2588
    * resolution height >= height and
2589
      resolution height >= root console height * font char height
2590
2591
    Args:
2592
        width (int): The desired resolution width.
2593
        height (int): The desired resolution height.
2594
    """
2595
    lib.TCOD_sys_force_fullscreen_resolution(width, height)
2596
2597
def sys_get_current_resolution():
2598
    """Return the current resolution as (width, height)
2599
2600
    Returns:
2601
        Tuple[int,int]: The current resolution.
2602
    """
2603
    w = ffi.new('int *')
2604
    h = ffi.new('int *')
2605
    lib.TCOD_sys_get_current_resolution(w, h)
2606
    return w[0], h[0]
2607
2608
def sys_get_char_size():
2609
    """Return the current fonts character size as (width, height)
2610
2611
    Returns:
2612
        Tuple[int,int]: The current font glyph size in (width, height)
2613
    """
2614
    w = ffi.new('int *')
2615
    h = ffi.new('int *')
2616
    lib.TCOD_sys_get_char_size(w, h)
2617
    return w[0], h[0]
2618
2619
# update font bitmap
2620
def sys_update_char(asciiCode, fontx, fonty, img, x, y):
2621
    """Dynamically update the current frot with img.
2622
2623
    All cells using this asciiCode will be updated
2624
    at the next call to :any:`tcod.console_flush`.
2625
2626
    Args:
2627
        asciiCode (int): Ascii code corresponding to the character to update.
2628
        fontx (int): Left coordinate of the character
2629
                     in the bitmap font (in tiles)
2630
        fonty (int): Top coordinate of the character
2631
                     in the bitmap font (in tiles)
2632
        img (Image): An image containing the new character bitmap.
2633
        x (int): Left pixel of the character in the image.
2634
        y (int): Top pixel of the character in the image.
2635
    """
2636
    lib.TCOD_sys_update_char(_int(asciiCode), fontx, fonty, img, x, y)
2637
2638
def sys_register_SDL_renderer(callback):
2639
    """Register a custom randering function with libtcod.
2640
2641
    Note:
2642
        This callback will only be called by the SDL renderer.
2643
2644
    The callack will receive a :any:`CData <ffi-cdata>` void* to an
2645
    SDL_Surface* struct.
2646
2647
    The callback is called on every call to :any:`tcod.console_flush`.
2648
2649
    Args:
2650
        callback Callable[[CData], None]:
2651
            A function which takes a single argument.
2652
    """
2653
    with _PropagateException() as propagate:
2654
        @ffi.def_extern(onerror=propagate)
2655
        def _pycall_sdl_hook(sdl_surface):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The variable _pycall_sdl_hook seems to be unused.
Loading history...
2656
            callback(sdl_surface)
2657
        lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook)
2658
2659
def sys_check_for_event(mask, k, m):
2660
    """Check for and return an event.
2661
2662
    Args:
2663
        mask (int): :any:`Event types` to wait for.
2664
        k (Optional[Key]): A tcod.Key instance which might be updated with
2665
                           an event.  Can be None.
2666
        m (Optional[Mouse]): A tcod.Mouse instance which might be updated
2667
                             with an event.  Can be None.
2668
    """
2669
    return lib.TCOD_sys_check_for_event(
2670
        mask, k.cdata if k else ffi.NULL, m.cdata if m else ffi.NULL)
2671
2672
def sys_wait_for_event(mask, k, m, flush):
2673
    """Wait for an event then return.
2674
2675
    If flush is True then the buffer will be cleared before waiting. Otherwise
2676
    each available event will be returned in the order they're recieved.
2677
2678
    Args:
2679
        mask (int): :any:`Event types` to wait for.
2680
        k (Optional[Key]): A tcod.Key instance which might be updated with
2681
                           an event.  Can be None.
2682
        m (Optional[Mouse]): A tcod.Mouse instance which might be updated
2683
                             with an event.  Can be None.
2684
        flush (bool): Clear the event buffer before waiting.
2685
    """
2686
    return lib.TCOD_sys_wait_for_event(
2687
        mask, k.cdata if k else ffi.NULL, m.cdata if m else ffi.NULL, flush)
2688
2689
def sys_clipboard_set(text):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2690
    return lib.TCOD_sys_clipboard_set(text.encode('utf-8'))
2691
2692
def sys_clipboard_get():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2693
    return ffi.string(lib.TCOD_sys_clipboard_get()).decode('utf-8')
2694