Completed
Push — master ( a9b743...52bb54 )
by Kyle
01:16
created

sys_clipboard_get()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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...
543
        except ImportError:
544
            _numpy = False
545
    return _numpy
546
547
# initializing the console
548
def console_init_root(w, h, title, fullscreen=False,
549
                      renderer=RENDERER_SDL):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'RENDERER_SDL'
Loading history...
550
    """Set up the primary display and return the root console.
551
552
    Note:
553
        Currently only the SDL renderer is supported at the moment.
554
        Do not attempt to change it.
555
556
    Args:
557
        w (int): Width in character tiles for the root console.
558
        h (int): Height in character tiles for the root console.
559
        title (AnyStr):
560
            This string will be displayed on the created windows title bar.
561
        renderer: Rendering mode for libtcod to use.
562
563
    Returns:
564
        Console:
565
            Returns a special Console instance representing the root console.
566
    """
567
    lib.TCOD_console_init_root(w, h, _bytes(title), fullscreen, renderer)
568
    return tcod.console.Console(ffi.NULL) # root console is null
569
570
571
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...
572
                            nb_char_horiz=0, nb_char_vertic=0):
573
    """Load a custom font file.
574
575
    Call this before function before calling :any:`tcod.console_init_root`.
576
577
    Flags can be a mix of the following:
578
579
    * tcod.FONT_LAYOUT_ASCII_INCOL
580
    * tcod.FONT_LAYOUT_ASCII_INROW
581
    * tcod.FONT_TYPE_GREYSCALE
582
    * tcod.FONT_TYPE_GRAYSCALE
583
    * tcod.FONT_LAYOUT_TCOD
584
585
    Args:
586
        fontFile (AnyStr): Path to a font file.
587
        flags (int):
588
        nb_char_horiz (int):
589
        nb_char_vertic (int):
590
    """
591
    lib.TCOD_console_set_custom_font(_bytes(fontFile), flags,
592
                                     nb_char_horiz, nb_char_vertic)
593
594
595
def console_get_width(con):
596
    """Return the width of a console.
597
598
    Args:
599
        con (Console): Any Console instance.
600
601
    Returns:
602
        int: The width of a Console.
603
604
    .. deprecated:: 2.0
605
        Use `Console.get_width` instead.
606
    """
607
    return lib.TCOD_console_get_width(_cdata(con))
608
609
def console_get_height(con):
610
    """Return the height of a console.
611
612
    Args:
613
        con (Console): Any Console instance.
614
615
    Returns:
616
        int: The height of a Console.
617
618
    .. deprecated:: 2.0
619
        Use `Console.get_hright` instead.
620
    """
621
    return lib.TCOD_console_get_height(_cdata(con))
622
623
def console_map_ascii_code_to_font(asciiCode, fontCharX, fontCharY):
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...
624
    lib.TCOD_console_map_ascii_code_to_font(_int(asciiCode), fontCharX,
625
                                                              fontCharY)
626
627
def console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, fontCharX,
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...
628
                                    fontCharY):
629
    lib.TCOD_console_map_ascii_codes_to_font(_int(firstAsciiCode), nbCodes,
630
                                              fontCharX, fontCharY)
631
632
def console_map_string_to_font(s, fontCharX, fontCharY):
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...
633
    lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
634
635
def console_is_fullscreen():
636
    """Returns True if the display is fullscreen.
637
638
    Returns:
639
        bool: True if the display is fullscreen, otherwise False.
640
    """
641
    return bool(lib.TCOD_console_is_fullscreen())
642
643
def console_set_fullscreen(fullscreen):
644
    """Change the display to be fullscreen or windowed.
645
646
    Args:
647
        fullscreen (bool): Use True to change to fullscreen.
648
                           Use False to change to windowed.
649
    """
650
    lib.TCOD_console_set_fullscreen(fullscreen)
651
652
def console_is_window_closed():
653
    """Returns True if the window has received and exit event."""
654
    return lib.TCOD_console_is_window_closed()
655
656
def console_set_window_title(title):
657
    """Change the current title bar string.
658
659
    Args:
660
        title (AnyStr): A string to change the title bar to.
661
    """
662
    lib.TCOD_console_set_window_title(_bytes(title))
663
664
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...
665
    lib.TCOD_console_credits()
666
667
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...
668
    lib.TCOD_console_credits_reset()
669
670
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...
671
    return lib.TCOD_console_credits_render(x, y, alpha)
672
673
def console_flush():
674
    """Update the display to represent the root consoles current state."""
675
    lib.TCOD_console_flush()
676
677
# drawing on a console
678
def console_set_default_background(con, col):
679
    """Change the default background color for a console.
680
681
    Args:
682
        con (Console): Any Console instance.
683
        col (Union[Tuple[int, int, int], Sequence[int]]):
684
            An (r, g, b) sequence or Color instance.
685
    """
686
    lib.TCOD_console_set_default_background(_cdata(con), col)
687
688
def console_set_default_foreground(con, col):
689
    """Change the default foreground color for a console.
690
691
    Args:
692
        con (Console): Any Console instance.
693
        col (Union[Tuple[int, int, int], Sequence[int]]):
694
            An (r, g, b) sequence or Color instance.
695
    """
696
    lib.TCOD_console_set_default_foreground(_cdata(con), col)
697
698
def console_clear(con):
699
    """Reset a console to its default colors and the space character.
700
701
    Args:
702
        con (Console): Any Console instance.
703
704
    .. seealso::
705
       :any:`console_set_default_background`
706
       :any:`console_set_default_foreground`
707
    """
708
    return lib.TCOD_console_clear(_cdata(con))
709
710
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...
711
    """Draw the character c at x,y using the default colors and a blend mode.
712
713
    Args:
714
        con (Console): Any Console instance.
715
        x (int): Character x position from the left.
716
        y (int): Character y position from the top.
717
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
718
        flag (int): Blending mode to use, defaults to BKGND_DEFAULT.
719
    """
720
    lib.TCOD_console_put_char(_cdata(con), x, y, _int(c), flag)
721
722
def console_put_char_ex(con, x, y, c, fore, back):
723
    """Draw the character c at x,y using the colors fore and back.
724
725
    Args:
726
        con (Console): Any Console instance.
727
        x (int): Character x position from the left.
728
        y (int): Character y position from the top.
729
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
730
        fore (Union[Tuple[int, int, int], Sequence[int]]):
731
            An (r, g, b) sequence or Color instance.
732
        back (Union[Tuple[int, int, int], Sequence[int]]):
733
            An (r, g, b) sequence or Color instance.
734
    """
735
    lib.TCOD_console_put_char_ex(_cdata(con), x, y,
736
                                 _int(c), fore, back)
737
738
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...
739
    """Change the background color of x,y to col using a blend mode.
740
741
    Args:
742
        con (Console): Any Console instance.
743
        x (int): Character x position from the left.
744
        y (int): Character y position from the top.
745
        col (Union[Tuple[int, int, int], Sequence[int]]):
746
            An (r, g, b) sequence or Color instance.
747
        flag (int): Blending mode to use, defaults to BKGND_SET.
748
    """
749
    lib.TCOD_console_set_char_background(_cdata(con), x, y, col, flag)
750
751
def console_set_char_foreground(con, x, y, col):
752
    """Change the foreground color of x,y to col.
753
754
    Args:
755
        con (Console): Any Console instance.
756
        x (int): Character x position from the left.
757
        y (int): Character y position from the top.
758
        col (Union[Tuple[int, int, int], Sequence[int]]):
759
            An (r, g, b) sequence or Color instance.
760
    """
761
    lib.TCOD_console_set_char_foreground(_cdata(con), x, y, col)
762
763
def console_set_char(con, x, y, c):
764
    """Change the character at x,y to c, keeping the current colors.
765
766
    Args:
767
        con (Console): Any Console instance.
768
        x (int): Character x position from the left.
769
        y (int): Character y position from the top.
770
        c (Union[int, AnyStr]): Character to draw, can be an integer or string.
771
    """
772
    lib.TCOD_console_set_char(_cdata(con), x, y, _int(c))
773
774
def console_set_background_flag(con, flag):
775
    """Change the default blend mode for this console.
776
777
    Args:
778
        con (Console): Any Console instance.
779
        flag (int): Blend mode to use by default.
780
    """
781
    lib.TCOD_console_set_background_flag(_cdata(con), flag)
782
783
def console_get_background_flag(con):
784
    """Return this consoles current blend mode.
785
786
    Args:
787
        con (Console): Any Console instance.
788
    """
789
    return lib.TCOD_console_get_background_flag(_cdata(con))
790
791
def console_set_alignment(con, alignment):
792
    """Change this consoles current alignment mode.
793
794
    * tcod.LEFT
795
    * tcod.CENTER
796
    * tcod.RIGHT
797
798
    Args:
799
        con (Console): Any Console instance.
800
        alignment (int):
801
    """
802
    lib.TCOD_console_set_alignment(_cdata(con), alignment)
803
804
def console_get_alignment(con):
805
    """Return this consoles current alignment mode.
806
807
    Args:
808
        con (Console): Any Console instance.
809
    """
810
    return lib.TCOD_console_get_alignment(_cdata(con))
811
812
def console_print(con, x, y, fmt):
813
    """Print a color formatted string on a console.
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
        fmt (AnyStr): A unicode or bytes string optionaly using color codes.
820
    """
821
    lib.TCOD_console_print_utf(_cdata(con), x, y, _fmt_unicode(fmt))
822
823
def console_print_ex(con, x, y, flag, alignment, fmt):
824
    """Print a string on a console using a blend mode and alignment mode.
825
826
    Args:
827
        con (Console): Any Console instance.
828
        x (int): Character x position from the left.
829
        y (int): Character y position from the top.
830
    """
831
    lib.TCOD_console_print_ex_utf(_cdata(con), x, y,
832
                                   flag, alignment, _fmt_unicode(fmt))
833
834
def console_print_rect(con, x, y, w, h, fmt):
835
    """Print a string constrained to a rectangle.
836
837
    If h > 0 and the bottom of the rectangle is reached,
838
    the string is truncated. If h = 0,
839
    the string is only truncated if it reaches the bottom of the console.
840
841
842
843
    Returns:
844
        int: The number of lines of text once word-wrapped.
845
    """
846
    return lib.TCOD_console_print_rect_utf(_cdata(con), x, y, w, h,
847
                                            _fmt_unicode(fmt))
848
849
def console_print_rect_ex(con, x, y, w, h, flag, alignment, fmt):
850
    """Print a string constrained to a rectangle with blend and alignment.
851
852
    Returns:
853
        int: The number of lines of text once word-wrapped.
854
    """
855
    return lib.TCOD_console_print_rect_ex_utf(_cdata(con), x, y, w, h,
856
                                              flag, alignment,
857
                                              _fmt_unicode(fmt))
858
859
def console_get_height_rect(con, x, y, w, h, fmt):
860
    """Return the height of this text once word-wrapped into this rectangle.
861
862
    Returns:
863
        int: The number of lines of text once word-wrapped.
864
    """
865
    return lib.TCOD_console_get_height_rect_utf(_cdata(con), x, y, w, h,
866
                                                 _fmt_unicode(fmt))
867
868
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...
869
    """Draw a the background color on a rect optionally clearing the text.
870
871
    If clr is True the affected tiles are changed to space character.
872
    """
873
    lib.TCOD_console_rect(_cdata(con), x, y, w, h, clr, flag)
874
875
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...
876
    """Draw a horizontal line on the console.
877
878
    This always uses the character 196, the horizontal line character.
879
    """
880
    lib.TCOD_console_hline(_cdata(con), x, y, l, flag)
881
882
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...
883
    """Draw a vertical line on the console.
884
885
    This always uses the character 179, the vertical line character.
886
    """
887
    lib.TCOD_console_vline(_cdata(con), x, y, l, flag)
888
889
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...
890
    """Draw a framed rectangle with optinal text.
891
892
    This uses the default background color and blend mode to fill the
893
    rectangle and the default foreground to draw the outline.
894
895
    fmt will be printed on the inside of the rectangle, word-wrapped.
896
    """
897
    lib.TCOD_console_print_frame(_cdata(con), x, y, w, h, clear, flag,
898
                                  _fmt_bytes(fmt))
899
900
def console_set_color_control(con, fore, back):
901
    """Configure :any:`color controls`.
902
903
    Args:
904
        con (int): :any:`Color control` constant to modify.
905
        fore (Union[Tuple[int, int, int], Sequence[int]]):
906
            An (r, g, b) sequence or Color instance.
907
        back (Union[Tuple[int, int, int], Sequence[int]]):
908
            An (r, g, b) sequence or Color instance.
909
    """
910
    lib.TCOD_console_set_color_control(_cdata(con), fore, back)
911
912
def console_get_default_background(con):
913
    """Return this consoles default background color."""
914
    return Color._new_from_cdata(
915 View Code Duplication
        lib.TCOD_console_get_default_background(_cdata(con)))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
916
917
def console_get_default_foreground(con):
918
    """Return this consoles default foreground color."""
919
    return Color._new_from_cdata(
920
        lib.TCOD_console_get_default_foreground(_cdata(con)))
921
922
def console_get_char_background(con, x, y):
923
    """Return the background color at the x,y of this console."""
924
    return Color._new_from_cdata(
925
        lib.TCOD_console_get_char_background(_cdata(con), x, y))
926
927
def console_get_char_foreground(con, x, y):
928
    """Return the foreground color at the x,y of this console."""
929
    return Color._new_from_cdata(
930
        lib.TCOD_console_get_char_foreground(_cdata(con), x, y))
931
932
def console_get_char(con, x, y):
933
    """Return the character at the x,y of this console."""
934
    return lib.TCOD_console_get_char(_cdata(con), x, y)
935
936
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...
937
    lib.TCOD_console_set_fade(fade, fadingColor)
938
939
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...
940
    return lib.TCOD_console_get_fade()
941
942
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...
943 View Code Duplication
    return Color._new_from_cdata(lib.TCOD_console_get_fading_color())
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
944
945
# handling keyboard input
946
def console_wait_for_keypress(flush):
947
    """Block until the user presses a key, then returns a new Key.
948
949
    Args:
950
        flush bool: If True then the event queue is cleared before waiting
951
                    for the next event.
952
953
    Returns:
954
        Key: A new Key instance.
955
    """
956
    k=Key()
0 ignored issues
show
Coding Style introduced by
Exactly one space required around assignment
k=Key()
^
Loading history...
957
    lib.TCOD_console_wait_for_keypress_wrapper(k.cdata, flush)
958
    return k
959
960
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...
961
    k=Key()
0 ignored issues
show
Coding Style introduced by
Exactly one space required around assignment
k=Key()
^
Loading history...
962
    lib.TCOD_console_check_for_keypress_wrapper(k.cdata, flags)
963
    return k
964
965
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...
966
    return lib.TCOD_console_is_key_pressed(key)
967
968
# using offscreen consoles
969
def console_new(w, h):
970
    """Return an offscreen console of size: w,h."""
971
    return tcod.console.Console(w, h)
972
def console_from_file(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...
973
    return tcod.console.Console(lib.TCOD_console_from_file(_bytes(filename)))
974
975
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...
976
    """Blit the console src from x,y,w,h to console dst at xdst,ydst."""
977
    lib.TCOD_console_blit(_cdata(src), x, y, w, h,
978
                          _cdata(dst), xdst, ydst, ffade, bfade)
979
980
def console_set_key_color(con, col):
981
    """Set a consoles blit transparent color."""
982
    lib.TCOD_console_set_key_color(_cdata(con), col)
983
984
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...
985
    con = _cdata(con)
986
    if con == ffi.NULL:
987
        lib.TCOD_console_delete(con)
988
989
# fast color filling
990
def console_fill_foreground(con, r, g, b):
991
    """Fill the foregound of a console with r,g,b.
992
993
    Args:
994
        con (Console): Any Console instance.
995
        r (Sequence[int]): An array of integers with a length of width*height.
996
        g (Sequence[int]): An array of integers with a length of width*height.
997
        b (Sequence[int]): An array of integers with a length of width*height.
998
    """
999
    if len(r) != len(g) or len(r) != len(b):
1000
        raise TypeError('R, G and B must all have the same size.')
1001 View Code Duplication
    if (_numpy_available() and isinstance(r, _numpy.ndarray) and
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
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...
1002
        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...
1003
        #numpy arrays, use numpy's ctypes functions
1004
        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...
1005
        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...
1006
        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...
1007
        cr = ffi.cast('int *', r.ctypes.data)
1008
        cg = ffi.cast('int *', g.ctypes.data)
1009
        cb = ffi.cast('int *', b.ctypes.data)
1010
    else:
1011
        # otherwise convert using ffi arrays
1012
        cr = ffi.new('int[]', r)
1013
        cg = ffi.new('int[]', g)
1014
        cb = ffi.new('int[]', b)
1015
1016
    lib.TCOD_console_fill_foreground(_cdata(con), cr, cg, cb)
1017
1018
def console_fill_background(con, r, g, b):
1019
    """Fill the backgound of a console with r,g,b.
1020
1021
    Args:
1022
        con (Console): Any Console instance.
1023
        r (Sequence[int]): An array of integers with a length of width*height.
1024
        g (Sequence[int]): An array of integers with a length of width*height.
1025
        b (Sequence[int]): An array of integers with a length of width*height.
1026
    """
1027
    if len(r) != len(g) or len(r) != len(b):
1028
        raise TypeError('R, G and B must all have the same size.')
1029 View Code Duplication
    if (_numpy_available() and isinstance(r, _numpy.ndarray) and
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
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...
1030
        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...
1031
        #numpy arrays, use numpy's ctypes functions
1032
        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...
1033
        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...
1034
        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...
1035
        cr = ffi.cast('int *', r.ctypes.data)
1036
        cg = ffi.cast('int *', g.ctypes.data)
1037
        cb = ffi.cast('int *', b.ctypes.data)
1038
    else:
1039
        # otherwise convert using ffi arrays
1040
        cr = ffi.new('int[]', r)
1041
        cg = ffi.new('int[]', g)
1042
        cb = ffi.new('int[]', b)
1043
1044
    lib.TCOD_console_fill_background(_cdata(con), cr, cg, cb)
1045
1046
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...
1047
    """Fill the character tiles of a console with an array.
1048
1049
    Args:
1050
        con (Console): Any Console instance.
1051
        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...
1052
    """
1053
    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...
1054
        #numpy arrays, use numpy's ctypes functions
1055
        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...
1056
        carr = ffi.cast('int *', arr.ctypes.data)
1057
    else:
1058
        #otherwise convert using the ffi module
1059
        carr = ffi.new('int[]', arr)
1060
1061
    lib.TCOD_console_fill_char(_cdata(con), carr)
1062
1063
def console_load_asc(con, 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...
1064
    return lib.TCOD_console_load_asc(_cdata(con), _bytes(filename))
1065
1066
def console_save_asc(con, 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...
1067
    lib.TCOD_console_save_asc(_cdata(con),_bytes(filename))
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
lib.TCOD_console_save_asc(_cdata(con),_bytes(filename))
^
Loading history...
1068
1069
def console_load_apf(con, 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...
1070
    return lib.TCOD_console_load_apf(_cdata(con),_bytes(filename))
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return lib.TCOD_console_load_apf(_cdata(con),_bytes(filename))
^
Loading history...
1071
1072
def console_save_apf(con, 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...
1073
    lib.TCOD_console_save_apf(_cdata(con),_bytes(filename))
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
lib.TCOD_console_save_apf(_cdata(con),_bytes(filename))
^
Loading history...
1074
1075
def path_new_using_map(m, dcost=1.41):
1076
    """Return a new AStar using the given Map.
1077
1078
    Args:
1079
        m (Map): A Map instance.
1080
        dcost (float): The path-finding cost of diagonal movement.
1081
                       Can be set to 0 to disable diagonal movement.
1082
    Returns:
1083
        AStar: A new AStar instance.
1084
    """
1085
    return tcod.path.AStar(m, dcost)
1086
1087
def path_new_using_function(w, h, func, userData=0, dcost=1.41):
1088
    """Return a new AStar using the given callable function.
1089
1090
    Args:
1091
        w (int): Clipping width.
1092
        h (int): Clipping height.
1093
        func (Callable[[int, int, int, int, Any], float]):
1094
        userData (Any):
1095
        dcost (float): A multiplier for the cost of diagonal movement.
1096
                       Can be set to 0 to disable diagonal movement.
1097
    Returns:
1098
        AStar: A new AStar instance.
1099
    """
1100
    return tcod.path.AStar((func, userData), dcost, w, h)
1101
1102
def path_compute(p, ox, oy, dx, dy):
1103
    """Find a path from (ox, oy) to (dx, dy).  Return True if path is found.
1104
1105
    Args:
1106
        p (AStar): An AStar instance.
1107
        ox (int): Starting x position.
1108
        oy (int): Starting y position.
1109
        dx (int): Destination x position.
1110
        dy (int): Destination y position.
1111
    Returns:
1112
        bool: True if a valid path was found.  Otherwise False.
1113
    """
1114
    return lib.TCOD_path_compute(p.cdata, ox, oy, dx, dy)
1115
1116
def path_get_origin(p):
1117
    """Get the current origin position.
1118
1119
    This point moves when :any:`path_walk` returns the next x,y step.
1120
1121
    Args:
1122
        p (AStar): An AStar instance.
1123
    Returns:
1124
        Tuple[int, int]: An (x, y) point.
1125
    """
1126
    x = ffi.new('int *')
1127
    y = ffi.new('int *')
1128
    lib.TCOD_path_get_origin(p.cdata, x, y)
1129
    return x[0], y[0]
1130
1131
def path_get_destination(p):
1132
    """Get the current destination position.
1133
1134
    Args:
1135
        p (AStar): An AStar instance.
1136
    Returns:
1137
        Tuple[int, int]: An (x, y) point.
1138
    """
1139
    x = ffi.new('int *')
1140
    y = ffi.new('int *')
1141
    lib.TCOD_path_get_destination(p.cdata, x, y)
1142
    return x[0], y[0]
1143
1144
def path_size(p):
1145
    """Return the current length of the computed path.
1146
1147
    Args:
1148
        p (AStar): An AStar instance.
1149
    Returns:
1150
        int: Length of the path.
1151
    """
1152
    return lib.TCOD_path_size(p.cdata)
1153
1154
def path_reverse(p):
1155
    """Reverse the direction of a path.
1156
1157
    This effectively swaps the origin and destination points.
1158
1159
    Args:
1160
        p (AStar): An AStar instance.
1161
    """
1162
    lib.TCOD_path_reverse(p.cdata)
1163
1164
def path_get(p, idx):
1165
    """Get a point on a path.
1166
1167
    Args:
1168
        p (AStar): An AStar instance.
1169
        idx (int): Should be in range: 0 <= inx < :any:`path_size`
1170
    """
1171
    x = ffi.new('int *')
1172
    y = ffi.new('int *')
1173
    lib.TCOD_path_get(p.cdata, idx, x, y)
1174
    return x[0], y[0]
1175
1176
def path_is_empty(p):
1177
    """Return True if a path is empty.
1178
1179
    Args:
1180
        p (AStar): An AStar instance.
1181
    Returns:
1182
        bool: True if a path is empty.  Otherwise False.
1183
    """
1184
    return lib.TCOD_path_is_empty(p.cdata)
1185
1186
def path_walk(p, recompute):
1187
    """Return the next (x, y) point in a path, or (None, None) if it's empty.
1188
1189
    When ``recompute`` is True and a previously valid path reaches a point
1190
    where it is now blocked, a new path will automatically be found.
1191
1192
    Args:
1193
        p (AStar): An AStar instance.
1194
        recompute (bool): Recompute the path automatically.
1195
    Returns:
1196
        Union[Tuple[int, int], Tuple[None, None]]:
1197
            A single (x, y) point, or (None, None)
1198
    """
1199
    x = ffi.new('int *')
1200
    y = ffi.new('int *')
1201
    if lib.TCOD_path_walk(p.cdata, x, y, recompute):
1202
        return x[0], y[0]
1203
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1204
1205
def path_delete(p):
0 ignored issues
show
Unused Code introduced by
The argument p seems to be unused.
Loading history...
1206
    """Does nothing."""
1207
    pass
1208
1209
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...
1210
    return tcod.path.Dijkstra(m, dcost)
1211
1212
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...
1213
    return tcod.path.Dijkstra((func, userData), dcost, w, h)
1214
1215
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...
1216
    lib.TCOD_dijkstra_compute(p.cdata, ox, oy)
1217
1218
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...
1219
    return lib.TCOD_dijkstra_path_set(p.cdata, x, y)
1220
1221
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...
1222
    return lib.TCOD_dijkstra_get_distance(p.cdata, x, y)
1223
1224
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...
1225
    return lib.TCOD_dijkstra_size(p.cdata)
1226
1227
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...
1228
    lib.TCOD_dijkstra_reverse(p.cdata)
1229
1230
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...
1231
    x = ffi.new('int *')
1232
    y = ffi.new('int *')
1233
    lib.TCOD_dijkstra_get(p.cdata, idx, x, y)
1234
    return x[0], y[0]
1235
1236
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...
1237
    return lib.TCOD_dijkstra_is_empty(p.cdata)
1238
1239
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...
1240
    x = ffi.new('int *')
1241
    y = ffi.new('int *')
1242
    if lib.TCOD_dijkstra_path_walk(p.cdata, x, y):
1243
        return x[0], y[0]
1244
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1245
1246
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...
1247
    pass
1248
1249
def _heightmap_cdata(array):
1250
    """Return a new TCOD_heightmap_t instance using an array.
1251
1252
    Formatting is verified during this function.
1253
    """
1254
    if not array.flags['C_CONTIGUOUS']:
1255
        raise ValueError('array must be a C-style contiguous segment.')
1256
    if array.dtype != _np.float32:
1257
        raise ValueError('array dtype must be float32, not %r' % array.dtype)
1258
    width, height = array.shape
1259
    pointer = ffi.cast('float *', array.ctypes.data)
1260
    return ffi.new('TCOD_heightmap_t *', (width, height, pointer))
1261
1262
def heightmap_new(w, h):
1263
    """Return a new numpy.ndarray formatted for use with heightmap functions.
1264
1265
    You can pass a numpy array to any heightmap function as long as all the
1266
    following are true::
1267
    * The array is 2 dimentional.
1268
    * The array has the C_CONTIGUOUS flag.
1269
    * The array's dtype is :any:`dtype.float32`.
1270
1271
    Args:
1272
        w (int): The width of the new HeightMap.
1273
        h (int): The height of the new HeightMap.
1274
1275
    Returns:
1276
        numpy.ndarray: A C-contiguous mapping of float32 values.
1277
    """
1278
    return _np.ndarray((h, w), _np.float32)
1279
1280
def heightmap_set_value(hm, x, y, value):
1281
    """Set the value of a point on a heightmap.
1282
1283
    Args:
1284
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1285
        x (int): The x position to change.
1286
        y (int): The y position to change.
1287
        value (float): The value to set.
1288
1289
    .. deprecated:: 2.0
1290
        Do ``hm[y, x] = value`` instead.
1291
    """
1292
    hm[y, x] = value
1293
1294
def heightmap_add(hm, value):
1295
    """Add value to all values on this heightmap.
1296
1297
    Args:
1298
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1299
        value (float): A number to add to this heightmap.
1300
1301
    .. deprecated:: 2.0
1302
        Do ``hm[:] += value`` instead.
1303
    """
1304
    hm[:] += value
1305
1306
def heightmap_scale(hm, value):
1307
    """Multiply all items on this heightmap by value.
1308
1309
    Args:
1310
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1311
        value (float): A number to scale this heightmap by.
1312
1313
    .. deprecated:: 2.0
1314
        Do ``hm[:] *= value`` instead.
1315
    """
1316
    hm[:] *= value
1317
1318
def heightmap_clear(hm):
1319
    """Add value to all values on this heightmap.
1320
1321
    Args:
1322
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1323
1324
    .. deprecated:: 2.0
1325
        Do ``hm.array[:] = 0`` instead.
1326
    """
1327
    hm[:] = 0
1328
1329
def heightmap_clamp(hm, mi, ma):
1330
    """Clamp all values on this heightmap between ``mi`` and ``ma``
1331
1332
    Args:
1333
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1334
        mi (float): The lower bound to clamp to.
1335
        ma (float): The upper bound to clamp to.
1336
1337
    .. deprecated:: 2.0
1338
        Do ``hm.clip(mi, ma)`` instead.
1339
    """
1340
    hm.clip(mi, ma)
1341
1342
def heightmap_copy(hm1, hm2):
1343
    """Copy the heightmap ``hm1`` to ``hm2``.
1344
1345
    Args:
1346
        hm1 (numpy.ndarray): The source heightmap.
1347
        hm2 (numpy.ndarray): The destination heightmap.
1348
1349
    .. deprecated:: 2.0
1350
        Do ``hm2[:] = hm1[:]`` instead.
1351
    """
1352
    hm2[:] = hm1[:]
1353
1354
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...
1355
    """Normalize heightmap values between ``mi`` and ``ma``.
1356
1357
    Args:
1358
        mi (float): The lowest value after normalization.
1359
        ma (float): The highest value after normalization.
1360
    """
1361
    lib.TCOD_heightmap_normalize(_heightmap_cdata(hm), mi, ma)
1362
1363
def heightmap_lerp_hm(hm1, hm2, hm3, coef):
1364
    """Perform linear interpolation between two heightmaps storing the result
1365
    in ``hm3``.
1366
1367
    This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef``
1368
1369
    Args:
1370
        hm1 (numpy.ndarray): The first heightmap.
1371
        hm2 (numpy.ndarray): The second heightmap to add to the first.
1372
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1373
        coef (float): The linear interpolation coefficient.
1374
    """
1375
    lib.TCOD_heightmap_lerp_hm(_heightmap_cdata(hm1), _heightmap_cdata(hm2),
1376
                               _heightmap_cdata(hm3), coef)
1377
1378
def heightmap_add_hm(hm1, hm2, hm3):
1379
    """Add two heightmaps together and stores the result in ``hm3``.
1380
1381
    Args:
1382
        hm1 (numpy.ndarray): The first heightmap.
1383
        hm2 (numpy.ndarray): The second heightmap to add to the first.
1384
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1385
1386
    .. deprecated:: 2.0
1387
        Do ``hm3[:] = hm1[:] + hm2[:]`` instead.
1388
    """
1389
    hm3[:] = hm1[:] + hm2[:]
1390
1391
def heightmap_multiply_hm(hm1, hm2, hm3):
1392
    """Multiplies two heightmap's together and stores the result in ``hm3``.
1393
1394
    Args:
1395
        hm1 (numpy.ndarray): The first heightmap.
1396
        hm2 (numpy.ndarray): The second heightmap to multiply with the first.
1397
        hm3 (numpy.ndarray): A destination heightmap to store the result.
1398
1399
    .. deprecated:: 2.0
1400
        Do ``hm3[:] = hm1[:] * hm2[:]`` instead.
1401
        Alternatively you can do ``HeightMap(hm1.array[:] * hm2.array[:])``.
1402
    """
1403
    hm3[:] = hm1[:] * hm2[:]
1404
1405
def heightmap_add_hill(hm, x, y, radius, height):
1406
    """Add a hill (a half spheroid) at given position.
1407
1408
    If height == radius or -radius, the hill is a half-sphere.
1409
1410
    Args:
1411
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1412
        x (float): The x position at the center of the new hill.
1413
        y (float): The y position at the center of the new hill.
1414
        radius (float): The size of the new hill.
1415
        height (float): The height or depth of the new hill.
1416
    """
1417
    lib.TCOD_heightmap_add_hill(_heightmap_cdata(hm), x, y, radius, height)
1418
1419
def heightmap_dig_hill(hm, x, y, radius, height):
1420
    """
1421
1422
    This function takes the highest value (if height > 0) or the lowest
1423
    (if height < 0) between the map and the hill.
1424
1425
    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...
1426
1427
    Args:
1428
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1429
        x (float): The x position at the center of the new carving.
1430
        y (float): The y position at the center of the new carving.
1431
        radius (float): The size of the carving.
1432
        height (float): The height or depth of the hill to dig out.
1433
    """
1434
    lib.TCOD_heightmap_dig_hill(_heightmap_cdata(hm), x, y, radius, height)
1435
1436
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...
1437
    """Simulate the effect of rain drops on the terrain, resulting in erosion.
1438
1439
    ``nbDrops`` should be at least hm.size.
1440
1441
    Args:
1442
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1443
        nbDrops (int): Number of rain drops to simulate.
1444
        erosionCoef (float): Amount of ground eroded on the drop's path.
1445
        sedimentationCoef (float): Amount of ground deposited when the drops
1446
                                   stops to flow.
1447
        rnd (Optional[Random]): A tcod.Random instance, or None.
1448
    """
1449
    lib.TCOD_heightmap_rain_erosion(_heightmap_cdata(hm), nbDrops, erosionCoef,
1450
                                    sedimentationCoef, _cdata(rnd))
1451
1452
def heightmap_kernel_transform(hm, kernelsize, dx, dy, weight, minLevel,
1453
                               maxLevel):
1454
    """Apply a generic transformation on the map, so that each resulting cell
1455
    value is the weighted sum of several neighbour cells.
1456
1457
    This can be used to smooth/sharpen the map.
1458
1459
    Args:
1460
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1461
        kernelsize (int): Should be set to the length of the parameters::
1462
                          dx, dy, and weight.
1463
        dx (Sequence[int]): A sequence of x coorinates.
1464
        dy (Sequence[int]): A sequence of y coorinates.
1465
        weight (Sequence[float]): A sequence of kernelSize cells weight.
1466
                                  The value of each neighbour cell is scaled by
1467
                                  its corresponding weight
1468
        minLevel (float): No transformation will apply to cells
1469
                          below this value.
1470
        maxLevel (float): No transformation will apply to cells
1471
                          above this value.
1472
1473
    See examples below for a simple horizontal smoothing kernel :
1474
    replace value(x,y) with
1475
    0.33*value(x-1,y) + 0.33*value(x,y) + 0.33*value(x+1,y).
1476
    To do this, you need a kernel of size 3
1477
    (the sum involves 3 surrounding cells).
1478
    The dx,dy array will contain
1479
    * dx=-1, dy=0 for cell (x-1, y)
1480
    * dx=1, dy=0 for cell (x+1, y)
1481
    * dx=0, dy=0 for cell (x, y)
1482
    * The weight array will contain 0.33 for each cell.
1483
1484
    Example:
1485
        >>> dx = [-1, 1, 0]
1486
        >>> dy = [0, 0, 0]
1487
        >>> weight = [0.33, 0.33, 0.33]
1488
        >>> tcod.heightMap_kernel_transform(heightmap,3,dx,dy,weight,0.0,1.0)
1489
    """
1490
    cdx = ffi.new('int[]', dx)
1491
    cdy = ffi.new('int[]', dy)
1492
    cweight = ffi.new('float[]', weight)
1493
    lib.TCOD_heightmap_kernel_transform(_heightmap_cdata(hm), kernelsize,
1494
                                        cdx, cdy, cweight, minLevel, maxLevel)
1495
1496
def heightmap_add_voronoi(hm, nbPoints, nbCoef, coef, rnd=None):
1497
    """Add values from a Voronoi diagram to the heightmap.
1498
1499
    Args:
1500
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1501
        nbPoints (Any): Number of Voronoi sites.
1502
        nbCoef (int): The diagram value is calculated from the nbCoef
1503
                      closest sites.
1504
        coef (Sequence[float]): The distance to each site is scaled by the
1505
                                corresponding coef.
1506
                                Closest site : coef[0],
1507
                                second closest site : coef[1], ...
1508
        rnd (Optional[Random]): A Random instance, or None.
1509
    """
1510
    nbPoints = len(coef)
1511
    ccoef = ffi.new('float[]', coef)
1512
    lib.TCOD_heightmap_add_voronoi(_heightmap_cdata(hm), nbPoints,
1513
                                   nbCoef, ccoef, _cdata(rnd))
1514
1515
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...
1516
    """Add FBM noise to the heightmap.
1517
1518
    The noise coordinate for each map cell is
1519
    `((x + addx) * mulx / width, (y + addy) * muly / height)`.
1520
1521
    The value added to the heightmap is `delta + noise * scale`.
1522
1523
    Args:
1524
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1525
        noise (Noise): A Noise instance.
1526
        mulx (float): Scaling of each x coordinate.
1527
        muly (float): Scaling of each y coordinate.
1528
        addx (float): Translation of each x coordinate.
1529
        addy (float): Translation of each y coordinate.
1530
        octaves (float): Number of octaves in the FBM sum.
1531
        delta (float): The value added to all heightmap cells.
1532
        scale (float): The noise value is scaled with this parameter.
1533
    """
1534
    lib.TCOD_heightmap_add_fbm(_heightmap_cdata(hm), _cdata(noise),
1535
                               mulx, muly, addx, addy, octaves, delta, scale)
1536
1537
def heightmap_scale_fbm(hm, noise, mulx, muly, addx, addy, octaves, delta,
1538
                        scale):
1539
    """Multiply the heighmap values with FBM noise.
1540
1541
    Args:
1542
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1543
        noise (Noise): A Noise instance.
1544
        mulx (float): Scaling of each x coordinate.
1545
        muly (float): Scaling of each y coordinate.
1546
        addx (float): Translation of each x coordinate.
1547
        addy (float): Translation of each y coordinate.
1548
        octaves (float): Number of octaves in the FBM sum.
1549
        delta (float): The value added to all heightmap cells.
1550
        scale (float): The noise value is scaled with this parameter.
1551
    """
1552
    lib.TCOD_heightmap_scale_fbm(_heightmap_cdata(hm), _cdata(noise),
1553
                                 mulx, muly, addx, addy, octaves, delta, scale)
1554
1555
def heightmap_dig_bezier(hm, px, py, startRadius, startDepth, endRadius,
1556
                         endDepth):
1557
    """Carve a path along a cubic Bezier curve.
1558
1559
    Both radius and depth can vary linearly along the path.
1560
1561
    Args:
1562
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1563
        px (Sequence[int]): The 4 `x` coordinates of the Bezier curve.
1564
        py (Sequence[int]): The 4 `y` coordinates of the Bezier curve.
1565
        startRadius (float): The starting radius size.
1566
        startDepth (float): The starting depth.
1567
        endRadius (float): The ending radius size.
1568
        endDepth (float): The ending depth.
1569
    """
1570
    lib.TCOD_heightmap_dig_bezier(_heightmap_cdata(hm), px, py, startRadius,
1571
                                   startDepth, endRadius,
1572
                                   endDepth)
1573
1574
def heightmap_get_value(hm, x, y):
1575
    """Return the value at ``x``, ``y`` in a heightmap.
1576
1577
    Args:
1578
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1579
        x (int): The x position to pick.
1580
        y (int): The y position to pick.
1581
1582
    Returns:
1583
        float: The value at ``x``, ``y``.
1584
1585
    .. deprecated:: 2.0
1586
        Do ``value = hm[y, x]`` instead.
1587
    """
1588
    # explicit type conversion to pass test, (test should have been better.)
1589
    return float(hm[y, x])
1590
1591
def heightmap_get_interpolated_value(hm, x, y):
1592
    """Return the interpolated height at non integer coordinates.
1593
1594
    Args:
1595
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1596
        x (float): A floating point x coordinate.
1597
        y (float): A floating point y coordinate.
1598
1599
    Returns:
1600
        float: The value at ``x``, ``y``.
1601
    """
1602
    return lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm),
1603
                                                     x, y)
1604
1605
def heightmap_get_slope(hm, x, y):
1606
    """Return the slope between 0 and (pi / 2) at given coordinates.
1607
1608
    Args:
1609
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1610
        x (int): The x coordinate.
1611
        y (int): The y coordinate.
1612
1613
    Returns:
1614
        float: The steepness at ``x``, ``y``.  From 0 to (pi / 2)
1615
    """
1616
    return lib.TCOD_heightmap_get_slope(_heightmap_cdata(hm), x, y)
1617
1618
def heightmap_get_normal(hm, x, y, waterLevel):
1619
    """Return the map normal at given coordinates.
1620
1621
    Args:
1622
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1623
        x (float): The x coordinate.
1624
        y (float): The y coordinate.
1625
        waterLevel (float): The heightmap is considered flat below this value.
1626
1627
    Returns:
1628
        Tuple[float, float, float]: An (x, y, z) vector normal.
1629
    """
1630
    cn = ffi.new('float[3]')
1631
    lib.TCOD_heightmap_get_normal(_heightmap_cdata(hm), x, y, cn, waterLevel)
1632
    return tuple(cn)
1633
1634
def heightmap_count_cells(hm, mi, ma):
1635
    """Return the number of map cells which value is between ``mi`` and ``ma``.
1636
1637
    Args:
1638
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1639
        mi (float): The lower bound.
1640
        ma (float): The upper bound.
1641
1642
    Returns:
1643
        int: The count of values which fall between ``mi`` and ``ma``.
1644
    """
1645
    return lib.TCOD_heightmap_count_cells(_heightmap_cdata(hm), mi, ma)
1646
1647
def heightmap_has_land_on_border(hm, waterlevel):
1648
    """Returns True if the map edges are below ``waterlevel``, otherwise False.
1649
1650
    Args:
1651
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1652
        waterLevel (float): The water level to use.
1653
1654
    Returns:
1655
        bool: True if the map edges are below ``waterlevel``, otherwise False.
1656
    """
1657
    return lib.TCOD_heightmap_has_land_on_border(_heightmap_cdata(hm),
1658
                                                 waterlevel)
1659
1660
def heightmap_get_minmax(hm):
1661
    """Return the min and max values of this heightmap.
1662
1663
    Args:
1664
        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
1665
1666
    Returns:
1667
        Tuple[float, float]: The (min, max) values.
1668
1669
    .. deprecated:: 2.0
1670
        Do ``hm.min()`` or ``hm.max()`` instead.
1671
    """
1672
    mi = ffi.new('float *')
1673
    ma = ffi.new('float *')
1674
    lib.TCOD_heightmap_get_minmax(_heightmap_cdata(hm), mi, ma)
1675
    return mi[0], ma[0]
1676
1677
def heightmap_delete(hm):
0 ignored issues
show
Unused Code introduced by
The argument hm seems to be unused.
Loading history...
1678
    """Does nothing.
1679
1680
    .. deprecated:: 2.0
1681
        libtcod-cffi deletes heightmaps automatically.
1682
    """
1683
    pass
1684
1685
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...
1686
    return tcod.image.Image(width, height)
1687
1688
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...
1689
    image.clear(col)
1690
1691
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...
1692
    image.invert()
1693
1694
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...
1695
    image.hflip()
1696
1697
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...
1698
    image.rotate90(num)
1699
1700
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...
1701
    image.vflip()
1702
1703
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...
1704
    image.scale(neww, newh)
1705
1706
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...
1707
    image.set_key_color(col)
1708
1709
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...
1710
    image.get_alpha(x, y)
1711
1712
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...
1713
    lib.TCOD_image_is_pixel_transparent(image.image_c, x, y)
1714
1715
def image_load(filename):
1716
    """Load an image file into an Image instance and return it.
1717
1718
    Args:
1719
        filename (AnyStr): Path to a .bmp or .png image file.
1720
    """
1721
    return tcod.image.Image._from_cdata(
1722
        ffi.gc(lib.TCOD_image_load(_bytes(filename)),
1723
               lib.TCOD_image_delete)
1724
        )
1725
1726
def image_from_console(console):
1727
    """Return an Image with a Consoles pixel data.
1728
1729
    This effectively takes a screen-shot of the Console.
1730
1731
    Args:
1732
        console (Console): Any Console instance.
1733
    """
1734
    return tcod.image.Image._from_cdata(
1735
        ffi.gc(lib.TCOD_image_from_console(_cdata(console)),
1736
               lib.TCOD_image_delete)
1737
        )
1738
1739
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...
1740
    image.refresh_console(console)
1741
1742
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...
1743
    return image.width, image.height
1744
1745
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...
1746
    return image.get_pixel(x, y)
1747
1748
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...
1749
    return image.get_mipmap_pixel(x0, y0, x1, y1)
1750
1751
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...
1752
    image.put_pixel(x, y, col)
1753
1754
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...
1755
    image.blit(console, x, y, bkgnd_flag, scalex, scaley, angle)
1756
1757
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...
1758
    image.blit_rect(console, x, y, w, h, bkgnd_flag)
1759
1760
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...
1761
    image.blit_2x(console, dx, dy, sx, sy, w, h)
1762
1763
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...
1764
    image.save_as(filename)
1765
1766
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...
1767
    pass
1768
1769
def line_init(xo, yo, xd, yd):
1770
    """Initilize a line whose points will be returned by `line_step`.
1771
1772
    This function does not return anything on its own.
1773
1774
    Does not include the origin point.
1775
1776
    Args:
1777
        xo (int): X starting point.
1778
        yo (int): Y starting point.
1779
        xd (int): X destination point.
1780
        yd (int): Y destination point.
1781
1782
    .. deprecated:: 2.0
1783
       Use `line_iter` instead.
1784
    """
1785
    lib.TCOD_line_init(xo, yo, xd, yd)
1786
1787
def line_step():
1788
    """After calling line_init returns (x, y) points of the line.
1789
1790
    Once all points are exhausted this function will return (None, None)
1791
1792
    Returns:
1793
        Union[Tuple[int, int], Tuple[None, None]]:
1794
            The next (x, y) point of the line setup by line_init,
1795
            or (None, None) if there are no more points.
1796
1797
    .. deprecated:: 2.0
1798
       Use `line_iter` instead.
1799
    """
1800
    x = ffi.new('int *')
1801
    y = ffi.new('int *')
1802
    ret = lib.TCOD_line_step(x, y)
1803
    if not ret:
1804
        return x[0], y[0]
1805
    return None,None
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
return None,None
^
Loading history...
1806
1807
_line_listener_lock = _threading.Lock()
1808
1809
def line(xo, yo, xd, yd, py_callback):
1810
    """ Iterate over a line using a callback function.
1811
1812
    Your callback function will take x and y parameters and return True to
1813
    continue iteration or False to stop iteration and return.
1814
1815
    This function includes both the start and end points.
1816
1817
    Args:
1818
        xo (int): X starting point.
1819
        yo (int): Y starting point.
1820
        xd (int): X destination point.
1821
        yd (int): Y destination point.
1822
        py_callback (Callable[[int, int], bool]):
1823
            A callback which takes x and y parameters and returns bool.
1824
1825
    Returns:
1826
        bool: False if the callback cancels the line interation by
1827
              returning False or None, otherwise True.
1828
1829
    .. deprecated:: 2.0
1830
       Use `line_iter` instead.
1831
    """
1832
    with _PropagateException() as propagate:
1833
        with _line_listener_lock:
1834
            @ffi.def_extern(onerror=propagate)
1835
            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...
1836
                return py_callback(x, y)
1837
            return bool(lib.TCOD_line(xo, yo, xd, yd,
1838
                                       lib._pycall_line_listener))
1839
1840
def line_iter(xo, yo, xd, yd):
1841
    """ returns an iterator
1842
1843
    This iterator does not include the origin point.
1844
1845
    Args:
1846
        xo (int): X starting point.
1847
        yo (int): Y starting point.
1848
        xd (int): X destination point.
1849
        yd (int): Y destination point.
1850
1851
    Returns:
1852
        Iterator[Tuple[int,int]]: An iterator of (x,y) points.
1853
    """
1854
    data = ffi.new('TCOD_bresenham_data_t *')
1855
    lib.TCOD_line_init_mt(xo, yo, xd, yd, data)
1856
    x = ffi.new('int *')
1857
    y = ffi.new('int *')
1858
    done = False
0 ignored issues
show
Unused Code introduced by
The variable done seems to be unused.
Loading history...
1859
    while not lib.TCOD_line_step_mt(x, y, data):
1860
        yield (x[0], y[0])
1861
1862
FOV_BASIC = 0
1863
FOV_DIAMOND = 1
1864
FOV_SHADOW = 2
1865
FOV_PERMISSIVE_0 = 3
1866
FOV_PERMISSIVE_1 = 4
1867
FOV_PERMISSIVE_2 = 5
1868
FOV_PERMISSIVE_3 = 6
1869
FOV_PERMISSIVE_4 = 7
1870
FOV_PERMISSIVE_5 = 8
1871
FOV_PERMISSIVE_6 = 9
1872
FOV_PERMISSIVE_7 = 10
1873
FOV_PERMISSIVE_8 = 11
1874
FOV_RESTRICTIVE = 12
1875
NB_FOV_ALGORITHMS = 13
1876
1877
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...
1878
    return tcod.map.Map(w, h)
1879
1880
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...
1881
    return lib.TCOD_map_copy(source.cdata, dest.cdata)
1882
1883
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...
1884
    lib.TCOD_map_set_properties(m.cdata, x, y, isTrans, isWalk)
1885
1886
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...
1887
    # walkable/transparent looks incorrectly ordered here.
1888
    # TODO: needs test.
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
1889
    lib.TCOD_map_clear(m.cdata, walkable, transparent)
1890
1891
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...
1892
    lib.TCOD_map_compute_fov(m.cdata, x, y, radius, light_walls, algo)
1893
1894
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...
1895
    return lib.TCOD_map_is_in_fov(m.cdata, x, y)
1896
1897
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...
1898
    return lib.TCOD_map_is_transparent(m.cdata, x, y)
1899
1900
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...
1901
    return lib.TCOD_map_is_walkable(m.cdata, x, y)
1902
1903
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...
1904
    pass
1905
1906
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...
1907
    return map.width
1908
1909
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...
1910
    return map.height
1911
1912
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...
1913
    lib.TCOD_mouse_show_cursor(visible)
1914
1915
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...
1916
    return lib.TCOD_mouse_is_cursor_visible()
1917
1918
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...
1919
    lib.TCOD_mouse_move(x, y)
1920
1921
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...
1922
    return Mouse(lib.TCOD_mouse_get_status())
1923
1924
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...
1925
    lib.TCOD_namegen_parse(_bytes(filename), random or ffi.NULL)
1926
1927
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...
1928
    return _unpack_char_p(lib.TCOD_namegen_generate(_bytes(name), False))
1929
1930
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...
1931
    return _unpack_char_p(lib.TCOD_namegen_generate(_bytes(name),
1932
                                                     _bytes(rule), False))
1933
1934
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...
1935
    sets = lib.TCOD_namegen_get_sets()
1936
    try:
1937
        lst = []
1938
        while not lib.TCOD_list_is_empty(sets):
1939
            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...
1940
    finally:
1941
        lib.TCOD_list_delete(sets)
1942
    return lst
1943
1944
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...
1945
    lib.TCOD_namegen_destroy()
1946
1947
def noise_new(dim, h=NOISE_DEFAULT_HURST, l=NOISE_DEFAULT_LACUNARITY,
1948
        random=None):
1949
    """Return a new Noise instance.
1950
1951
    Args:
1952
        dim (int): Number of dimentions.  From 1 to 4.
1953
        h (float): The hurst exponent.  Should be in the 0.0-1.0 range.
1954
        l (float): The noise lacunarity.
1955
        random (Optional[Random]): A Random instance, or None.
1956
1957
    Returns:
1958
        Noise: The new Noise instance.
1959
    """
1960
    return tcod.noise.Noise(dim, hurst=h, lacunarity=l, rand=random)
1961
1962
def noise_set_type(n, typ):
1963
    """Set a Noise objects default noise algorithm.
1964
1965
    Args:
1966
        typ (int): Any NOISE_* constant.
1967
    """
1968
    n.algorithm = typ
1969
1970
def noise_get(n, f, typ=NOISE_DEFAULT):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'NOISE_DEFAULT'
Loading history...
1971
    """Return the noise value sampled from the ``f`` coordinate.
1972
1973
    ``f`` should be a tuple or list with a length matching
1974
    :any:`Noise.dimentions`.
1975
    If ``f`` is shoerter than :any:`Noise.dimentions` the missing coordinates
1976
    will be filled with zeros.
1977
1978
    Args:
1979
        n (Noise): A Noise instance.
1980
        f (Sequence[float]): The point to sample the noise from.
1981
        typ (int): The noise algorithm to use.
1982
1983
    Returns:
1984
        float: The sampled noise value.
1985
    """
1986
    return lib.TCOD_noise_get_ex(n.cdata, ffi.new('float[4]', f), typ)
1987
1988
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...
1989
    """Return the fractal Brownian motion sampled from the ``f`` coordinate.
1990
1991
    Args:
1992
        n (Noise): A Noise instance.
1993
        f (Sequence[float]): The point to sample the noise from.
1994
        typ (int): The noise algorithm to use.
1995
        octaves (float): The level of level.  Should be more than 1.
1996
1997
    Returns:
1998
        float: The sampled noise value.
1999
    """
2000
    return lib.TCOD_noise_get_fbm_ex(n.cdata, ffi.new('float[4]', f),
2001
                                     oc, typ)
2002
2003
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...
2004
    """Return the turbulence noise sampled from the ``f`` coordinate.
2005
2006
    Args:
2007
        n (Noise): A Noise instance.
2008
        f (Sequence[float]): The point to sample the noise from.
2009
        typ (int): The noise algorithm to use.
2010
        octaves (float): The level of level.  Should be more than 1.
2011
2012
    Returns:
2013
        float: The sampled noise value.
2014
    """
2015
    return lib.TCOD_noise_get_turbulence_ex(n.cdata, ffi.new('float[4]', f),
2016
                                            oc, typ)
2017
2018
def noise_delete(n):
0 ignored issues
show
Unused Code introduced by
The argument n seems to be unused.
Loading history...
2019
    """Does nothing."""
2020
    pass
2021
2022
_chr = chr
2023
try:
2024
    _chr = unichr # Python 2
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'unichr'
Loading history...
2025
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...
2026
    pass
2027
2028
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...
2029
    '''
2030
        unpack items from parser new_property (value_converter)
2031
    '''
2032
    if type == lib.TCOD_TYPE_BOOL:
2033
        return bool(union.b)
2034
    elif type == lib.TCOD_TYPE_CHAR:
2035
        return _unicode(union.c)
2036
    elif type == lib.TCOD_TYPE_INT:
2037
        return union.i
2038
    elif type == lib.TCOD_TYPE_FLOAT:
2039
        return union.f
2040
    elif (type == lib.TCOD_TYPE_STRING or
2041
         lib.TCOD_TYPE_VALUELIST15 >= type >= lib.TCOD_TYPE_VALUELIST00):
2042
         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...
2043
    elif type == lib.TCOD_TYPE_COLOR:
2044
        return Color._new_from_cdata(union.col)
2045
    elif type == lib.TCOD_TYPE_DICE:
2046
        return Dice(union.dice)
2047
    elif type & lib.TCOD_TYPE_LIST:
2048
        return _convert_TCODList(union.list, type & 0xFF)
2049
    else:
2050
        raise RuntimeError('Unknown libtcod type: %i' % type)
2051
2052
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...
2053
    return [_unpack_union(type, lib.TDL_list_get_union(clist, i))
2054
            for i in range(lib.TCOD_list_size(clist))]
2055
2056
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...
2057
    return ffi.gc(lib.TCOD_parser_new(), lib.TCOD_parser_delete)
2058
2059
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...
2060
    return lib.TCOD_parser_new_struct(parser, name)
2061
2062
# prevent multiple threads from messing with def_extern callbacks
2063
_parser_callback_lock = _threading.Lock()
2064
2065
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...
2066
    if not listener:
2067
        lib.TCOD_parser_run(parser, _bytes(filename), ffi.NULL)
2068
        return
2069
2070
    propagate_manager = _PropagateException()
2071
    propagate = propagate_manager.propagate
2072
2073
    with _parser_callback_lock:
2074
        clistener = ffi.new('TCOD_parser_listener_t *')
2075
2076
        @ffi.def_extern(onerror=propagate)
2077
        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...
2078
            return listener.end_struct(struct, _unpack_char_p(name))
2079
2080
        @ffi.def_extern(onerror=propagate)
2081
        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...
2082
            return listener.new_flag(_unpack_char_p(name))
2083
2084
        @ffi.def_extern(onerror=propagate)
2085
        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...
2086
            return listener.new_property(_unpack_char_p(propname), type,
2087
                                         _unpack_union(type, value))
2088
2089
        @ffi.def_extern(onerror=propagate)
2090
        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...
2091
            return listener.end_struct(struct, _unpack_char_p(name))
2092
2093
        @ffi.def_extern(onerror=propagate)
2094
        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...
2095
            listener.error(_unpack_char_p(msg))
2096
2097
        clistener.new_struct = lib.pycall_parser_new_struct
2098
        clistener.new_flag = lib.pycall_parser_new_flag
2099
        clistener.new_property = lib.pycall_parser_new_property
2100
        clistener.end_struct = lib.pycall_parser_end_struct
2101
        clistener.error = lib.pycall_parser_error
2102
2103
        with propagate_manager:
2104
            lib.TCOD_parser_run(parser, _bytes(filename), clistener)
2105
2106
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...
2107
    pass
2108
2109
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...
2110
    return bool(lib.TCOD_parser_get_bool_property(parser, _bytes(name)))
2111
2112
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...
2113
    return lib.TCOD_parser_get_int_property(parser, _bytes(name))
2114
2115
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...
2116
    return _chr(lib.TCOD_parser_get_char_property(parser, _bytes(name)))
2117
2118
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...
2119
    return lib.TCOD_parser_get_float_property(parser, _bytes(name))
2120
2121
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...
2122
    return _unpack_char_p(
2123
        lib.TCOD_parser_get_string_property(parser, _bytes(name)))
2124
2125
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...
2126
    return Color._new_from_cdata(
2127
        lib.TCOD_parser_get_color_property(parser, _bytes(name)))
2128
2129
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...
2130
    d = ffi.new('TCOD_dice_t *')
2131
    lib.TCOD_parser_get_dice_property_py(parser, _bytes(name), d)
2132
    return Dice(d)
2133
2134
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...
2135
    clist = lib.TCOD_parser_get_list_property(parser, _bytes(name), type)
2136
    return _convert_TCODList(clist, type)
2137
2138
RNG_MT = 0
2139
RNG_CMWC = 1
2140
2141
DISTRIBUTION_LINEAR = 0
2142
DISTRIBUTION_GAUSSIAN = 1
2143
DISTRIBUTION_GAUSSIAN_RANGE = 2
2144
DISTRIBUTION_GAUSSIAN_INVERSE = 3
2145
DISTRIBUTION_GAUSSIAN_RANGE_INVERSE = 4
2146
2147
def random_get_instance():
2148
    """Return the default Random instance.
2149
2150
    Returns:
2151
        Random: A Random instance using the default random number generator.
2152
    """
2153
    return tcod.random.Random._new_from_cdata(
2154
        ffi.cast('mersenne_data_t*', lib.TCOD_random_get_instance()))
2155
2156
def random_new(algo=RNG_CMWC):
2157
    """Return a new Random instance.  Using ``algo``.
2158
2159
    Args:
2160
        algo (int): The random number algorithm to use.
2161
2162
    Returns:
2163
        Random: A new Random instance using the given algorithm.
2164
    """
2165
    return tcod.random.Random(algo)
2166
2167
def random_new_from_seed(seed, algo=RNG_CMWC):
2168
    """Return a new Random instance.  Using the given ``seed`` and ``algo``.
2169
2170
    Args:
2171
        seed (Hashable): The RNG seed.  Should be a 32-bit integer, but any
2172
                         hashable object is accepted.
2173
        algo (int): The random number algorithm to use.
2174
2175
    Returns:
2176
        Random: A new Random instance using the given algorithm.
2177
    """
2178
    return tcod.random.Random(algo, seed)
2179
2180
def random_set_distribution(rnd, dist):
2181
    """Change the distribution mode of a random number generator.
2182
2183
    Args:
2184
        rnd (Optional[Random]): A Random instance, or None to use the default.
2185
        dist (int): The distribution mode to use.  Should be DISTRIBUTION_*.
2186
    """
2187
    lib.TCOD_random_set_distribution(_cdata(rnd), dist)
2188
2189
def random_get_int(rnd, mi, ma):
2190
    """Return a random integer in the range: ``mi`` <= n <= ``ma``.
2191
2192
    The result is affacted by calls to :any:`random_set_distribution`.
2193
2194
    Args:
2195
        rnd (Optional[Random]): A Random instance, or None to use the default.
2196
        low (int): The lower bound of the random range, inclusive.
2197
        high (int): The upper bound of the random range, inclusive.
2198
2199
    Returns:
2200
        int: A random integer in the range ``mi`` <= n <= ``ma``.
2201
    """
2202
    return lib.TCOD_random_get_int(_cdata(rnd), mi, ma)
2203
2204
def random_get_float(rnd, mi, ma):
2205
    """Return a random float in the range: ``mi`` <= n <= ``ma``.
2206
2207
    The result is affacted by calls to :any:`random_set_distribution`.
2208
2209
    Args:
2210
        rnd (Optional[Random]): A Random instance, or None to use the default.
2211
        low (float): The lower bound of the random range, inclusive.
2212
        high (float): The upper bound of the random range, inclusive.
2213
2214
    Returns:
2215
        float: A random double precision float
2216
               in the range ``mi`` <= n <= ``ma``.
2217
    """
2218
    return lib.TCOD_random_get_double(_cdata(rnd), mi, ma)
2219
2220
def random_get_double(rnd, mi, ma):
2221
    """Return a random float in the range: ``mi`` <= n <= ``ma``.
2222
2223
    .. deprecated:: 2.0
2224
        Use :any:`random_get_float` instead.
2225
        Both funtions return a double precision float.
2226
    """
2227
    return lib.TCOD_random_get_double(_cdata(rnd), mi, ma)
2228
2229
def random_get_int_mean(rnd, mi, ma, mean):
2230
    """Return a random weighted integer in the range: ``mi`` <= n <= ``ma``.
2231
2232
    The result is affacted by calls to :any:`random_set_distribution`.
2233
2234
    Args:
2235
        rnd (Optional[Random]): A Random instance, or None to use the default.
2236
        low (int): The lower bound of the random range, inclusive.
2237
        high (int): The upper bound of the random range, inclusive.
2238
        mean (int): The mean return value.
2239
2240
    Returns:
2241
        int: A random weighted integer in the range ``mi`` <= n <= ``ma``.
2242
    """
2243
    return lib.TCOD_random_get_int_mean(_cdata(rnd), mi, ma, mean)
2244
2245
def random_get_float_mean(rnd, mi, ma, mean):
2246
    """Return a random weighted float in the range: ``mi`` <= n <= ``ma``.
2247
2248
    The result is affacted by calls to :any:`random_set_distribution`.
2249
2250
    Args:
2251
        rnd (Optional[Random]): A Random instance, or None to use the default.
2252
        low (float): The lower bound of the random range, inclusive.
2253
        high (float): The upper bound of the random range, inclusive.
2254
        mean (float): The mean return value.
2255
2256
    Returns:
2257
        float: A random weighted double precision float
2258
               in the range ``mi`` <= n <= ``ma``.
2259
    """
2260
    return lib.TCOD_random_get_double_mean(_cdata(rnd), mi, ma, mean)
2261
2262
def random_get_double_mean(rnd, mi, ma, mean):
2263
    """Return a random weighted float in the range: ``mi`` <= n <= ``ma``.
2264
2265
    .. deprecated:: 2.0
2266
        Use :any:`random_get_float_mean` instead.
2267
        Both funtions return a double precision float.
2268
    """
2269
    return lib.TCOD_random_get_double_mean(_cdata(rnd), mi, ma, mean)
2270
2271
def random_save(rnd):
2272
    """Return a copy of a random number generator.
2273
2274
    Args:
2275
        rnd (Optional[Random]): A Random instance, or None to use the default.
2276
2277
    Returns:
2278
        Random: A Random instance with a copy of the random generator.
2279
    """
2280
    return tcod.random.Random._new_from_cdata(
2281
        ffi.gc(ffi.cast('mersenne_data_t*', lib.TCOD_random_save(rnd.cdata)),
2282
               lib.TCOD_random_delete))
2283
2284
def random_restore(rnd, backup):
2285
    """Restore a random number generator from a backed up copy.
2286
2287
    Args:
2288
        rnd (Optional[Random]): A Random instance, or None to use the default.
2289
        backup (Random): The Random instance which was used as a backup.
2290
    """
2291
    lib.TCOD_random_restore(_cdata(rnd), backup.cdata)
2292
2293
def random_delete(rnd):
0 ignored issues
show
Unused Code introduced by
The argument rnd seems to be unused.
Loading history...
2294
    """Does nothing."""
2295
    pass
2296
2297
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...
2298
    lib.TCOD_struct_add_flag(struct, name)
2299
2300
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...
2301
    lib.TCOD_struct_add_property(struct, name, typ, mandatory)
2302
2303
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...
2304
    CARRAY = c_char_p * (len(value_list) + 1)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'c_char_p'
Loading history...
2305
    cvalue_list = CARRAY()
2306
    for i in range(len(value_list)):
2307
        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...
2308
    cvalue_list[len(value_list)] = 0
2309
    lib.TCOD_struct_add_value_list(struct, name, cvalue_list, mandatory)
2310
2311
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...
2312
    lib.TCOD_struct_add_list_property(struct, name, typ, mandatory)
2313
2314
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...
2315
    lib.TCOD_struct_add_structure(struct, sub_struct)
2316
2317
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...
2318
    return _unpack_char_p(lib.TCOD_struct_get_name(struct))
2319
2320
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...
2321
    return lib.TCOD_struct_is_mandatory(struct, name)
2322
2323
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...
2324
    return lib.TCOD_struct_get_type(struct, name)
2325
2326
# high precision time functions
2327
def sys_set_fps(fps):
2328
    """Set the maximum frame rate.
2329
2330
    You can disable the frame limit again by setting fps to 0.
2331
2332
    Args:
2333
        fps (int): A frame rate limit (i.e. 60)
2334
    """
2335
    lib.TCOD_sys_set_fps(fps)
2336
2337
def sys_get_fps():
2338
    """Return the current frames per second.
2339
2340
    This the actual frame rate, not the frame limit set by
2341
    :any:`tcod.sys_set_fps`.
2342
2343
    This number is updated every second.
2344
2345
    Returns:
2346
        int: The currently measured frame rate.
2347
    """
2348
    return lib.TCOD_sys_get_fps()
2349
2350
def sys_get_last_frame_length():
2351
    """Return the delta time of the last rendered frame in seconds.
2352
2353
    Returns:
2354
        float: The delta time of the last rendered frame.
2355
    """
2356
    return lib.TCOD_sys_get_last_frame_length()
2357
2358
def sys_sleep_milli(val):
2359
    """Sleep for 'val' milliseconds.
2360
2361
    Args:
2362
        val (int): Time to sleep for in milliseconds.
2363
2364
    .. deprecated:: 2.0
2365
       Use :any:`time.sleep` instead.
2366
    """
2367
    lib.TCOD_sys_sleep_milli(val)
2368
2369
def sys_elapsed_milli():
2370
    """Get number of milliseconds since the start of the program.
2371
2372
    Returns:
2373
        int: Time since the progeam has started in milliseconds.
2374
2375
    .. deprecated:: 2.0
2376
       Use :any:`time.clock` instead.
2377
    """
2378
    return lib.TCOD_sys_elapsed_milli()
2379
2380
def sys_elapsed_seconds():
2381
    """Get number of seconds since the start of the program.
2382
2383
    Returns:
2384
        float: Time since the progeam has started in seconds.
2385
2386
    .. deprecated:: 2.0
2387
       Use :any:`time.clock` instead.
2388
    """
2389
    return lib.TCOD_sys_elapsed_seconds()
2390
2391
def sys_set_renderer(renderer):
2392
    """Change the current rendering mode to renderer.
2393
2394
    .. deprecated:: 2.0
2395
       RENDERER_GLSL and RENDERER_OPENGL are not currently available.
2396
    """
2397
    lib.TCOD_sys_set_renderer(renderer)
2398
2399
def sys_get_renderer():
2400
    """Return the current rendering mode.
2401
2402
    """
2403
    return lib.TCOD_sys_get_renderer()
2404
2405
# easy screenshots
2406
def sys_save_screenshot(name=None):
2407
    """Save a screenshot to a file.
2408
2409
    By default this will automatically save screenshots in the working
2410
    directory.
2411
2412
    The automatic names are formatted as screenshotNNN.png.  For example:
2413
    screenshot000.png, screenshot001.png, etc.  Whichever is available first.
2414
2415
    Args:
2416
        file Optional[AnyStr]: File path to save screenshot.
2417
    """
2418
    if name is not None:
2419
        name = _bytes(name)
2420
    lib.TCOD_sys_save_screenshot(name or ffi.NULL)
2421
2422
# custom fullscreen resolution
2423
def sys_force_fullscreen_resolution(width, height):
2424
    """Force a specific resolution in fullscreen.
2425
2426
    Will use the smallest available resolution so that:
2427
2428
    * resolution width >= width and
2429
      resolution width >= root console width * font char width
2430
    * resolution height >= height and
2431
      resolution height >= root console height * font char height
2432
2433
    Args:
2434
        width (int): The desired resolution width.
2435
        height (int): The desired resolution height.
2436
    """
2437
    lib.TCOD_sys_force_fullscreen_resolution(width, height)
2438
2439
def sys_get_current_resolution():
2440
    """Return the current resolution as (width, height)
2441
2442
    Returns:
2443
        Tuple[int,int]: The current resolution.
2444
    """
2445
    w = ffi.new('int *')
2446
    h = ffi.new('int *')
2447
    lib.TCOD_sys_get_current_resolution(w, h)
2448
    return w[0], h[0]
2449
2450
def sys_get_char_size():
2451
    """Return the current fonts character size as (width, height)
2452
2453
    Returns:
2454
        Tuple[int,int]: The current font glyph size in (width, height)
2455
    """
2456
    w = ffi.new('int *')
2457
    h = ffi.new('int *')
2458
    lib.TCOD_sys_get_char_size(w, h)
2459
    return w[0], h[0]
2460
2461
# update font bitmap
2462
def sys_update_char(asciiCode, fontx, fonty, img, x, y):
2463
    """Dynamically update the current frot with img.
2464
2465
    All cells using this asciiCode will be updated
2466
    at the next call to :any:`tcod.console_flush`.
2467
2468
    Args:
2469
        asciiCode (int): Ascii code corresponding to the character to update.
2470
        fontx (int): Left coordinate of the character
2471
                     in the bitmap font (in tiles)
2472
        fonty (int): Top coordinate of the character
2473
                     in the bitmap font (in tiles)
2474
        img (Image): An image containing the new character bitmap.
2475
        x (int): Left pixel of the character in the image.
2476
        y (int): Top pixel of the character in the image.
2477
    """
2478
    lib.TCOD_sys_update_char(_int(asciiCode), fontx, fonty, img, x, y)
2479
2480
def sys_register_SDL_renderer(callback):
2481
    """Register a custom randering function with libtcod.
2482
2483
    The callack will receive a :any:`CData <ffi-cdata>` void* to an
2484
    SDL_Surface* struct.
2485
2486
    The callback is called on every call to :any:`tcod.console_flush`.
2487
2488
    Args:
2489
        callback Callable[[CData], None]:
2490
            A function which takes a single argument.
2491
    """
2492
    with _PropagateException() as propagate:
2493
        @ffi.def_extern(onerror=propagate)
2494
        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...
2495
            callback(sdl_surface)
2496
        lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook)
2497
2498
def sys_check_for_event(mask, k, m):
2499
    """Check for and return an event.
2500
2501
    Args:
2502
        mask (int): :any:`Event types` to wait for.
2503
        k (Optional[Key]): A tcod.Key instance which might be updated with
2504
                           an event.  Can be None.
2505
        m (Optional[Mouse]): A tcod.Mouse instance which might be updated
2506
                             with an event.  Can be None.
2507
    """
2508
    return lib.TCOD_sys_check_for_event(mask, _cdata(k), _cdata(m))
2509
2510
def sys_wait_for_event(mask, k, m, flush):
2511
    """Wait for an event then return.
2512
2513
    If flush is True then the buffer will be cleared before waiting. Otherwise
2514
    each available event will be returned in the order they're recieved.
2515
2516
    Args:
2517
        mask (int): :any:`Event types` to wait for.
2518
        k (Optional[Key]): A tcod.Key instance which might be updated with
2519
                           an event.  Can be None.
2520
        m (Optional[Mouse]): A tcod.Mouse instance which might be updated
2521
                             with an event.  Can be None.
2522
        flush (bool): Clear the event buffer before waiting.
2523
    """
2524
    return lib.TCOD_sys_wait_for_event(mask, _cdata(k), _cdata(m), flush)
2525
2526
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...
2527
    return lib.TCOD_sys_clipboard_set(text.encode('utf-8'))
2528
2529
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...
2530
    return ffi.string(lib.TCOD_sys_clipboard_get()).decode('utf-8')
2531