Completed
Push — master ( 1e8986...4e135b )
by Kyle
01:58
created

Key   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 10
Bugs 0 Features 2
Metric Value
c 10
b 0
f 2
dl 0
loc 44
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 4 2
A __getattr__() 0 8 4
A __repr__() 0 10 3
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
9
10
from tcod.libtcod import *
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...
Unused Code introduced by
absolute_import was imported with wildcard, but is not used.
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=' '):
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)
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):
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):
209
        return self.nb_rolls
210
    def _set_nb_dices(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

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

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

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

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

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

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

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

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

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

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

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

param = 5

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