Completed
Push — master ( 4e135b...a1a352 )
by Kyle
01:21
created

Console   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 315
Duplicated Lines 0 %

Importance

Changes 12
Bugs 0 Features 1
Metric Value
c 12
b 0
f 1
dl 0
loc 315
rs 8.8
wmc 36

27 Methods

Rating   Name   Duplication   Size   Complexity  
A blit() 0 21 1
A unpack_color() 0 6 1
A height() 0 4 1
A get_height_rect() 0 15 1
A _from_cdata() 0 8 2
A __init__() 0 4 1
A vline() 0 12 1
A put_char() 0 10 1
A __exit__() 0 6 1
A bg() 0 9 1
A print_rect() 0 23 2
A __enter__() 0 13 2
A rect() 0 15 1
A default_fg() 0 5 1
A hline() 0 12 1
A default_alignment() 0 4 1
A _init_setup_console_data() 0 22 3
A ch() 0 9 1
A clear() 0 4 1
A set_key_color() 0 7 1
A __bool__() 0 6 1
B print_frame() 0 24 1
A default_bg() 0 5 1
A default_bg_blend() 0 4 1
A fg() 0 9 1
A width() 0 4 1
A print_() 0 12 2
1
"""
2
libtcod works with a special 'root' console.  You create this console using
3
the :any:`tcod.console_init_root` function.  Usually after setting the font
4
with :any:`console_set_custom_font` first.
5
6
Example:
7
    # Make sure 'arial10x10.png' is in the same directory as this script.
8
    import time
9
10
    import tcod
11
12
    # Setup the font.
13
    tcod.console_set_custom_font(
14
        'arial10x10.png',
15
        tcod.FONT_LAYOUT_ASCII_INROW | tcod.FONT_LAYOUT_TCOD,
16
        )
17
    # Initialize the root console in a context.
18
    with tcod.console_init_root(80, 60, 'title') as root_console:
19
        root_console.print_(x=0, y=0, string='Hello World!')
20
        tcod.console_flush() # Show the console.
21
        time.sleep(3) # Wait 3 seconds.
22
    # The window is closed here, after the above context exits.
23
"""
24
25
from __future__ import absolute_import
26
27
import sys
28
29
import numpy as np
0 ignored issues
show
Configuration introduced by
The import numpy could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

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

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

2. Missing __init__.py files

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

Loading history...
30
31
from tcod.tcod import _cdata
32
from tcod.libtcod import ffi, lib
33
from tcod.libtcod import BKGND_DEFAULT, BKGND_SET
0 ignored issues
show
Bug introduced by
The name BKGND_DEFAULT does not seem to exist in module tcod.libtcod.
Loading history...
Bug introduced by
The name BKGND_SET does not seem to exist in module tcod.libtcod.
Loading history...
Unused Code introduced by
Unused BKGND_SET imported from tcod.libtcod
Loading history...
34
35
36
if sys.version_info[0] == 2: # Python 2
37
    def _fmt(string):
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...
38
        if not isinstance(string, unicode):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'unicode'
Loading history...
39
            string = string.decode('latin-1')
40
        return string.replace(u'%', u'%%')
41
else:
42
    def _fmt(string):
43
        """Return a string that escapes 'C printf' side effects."""
44
        return string.replace('%', '%%')
45
46
47
class _ChBufferArray(np.ndarray):
48
    """Numpy subclass designed to access libtcod's character buffer.
49
50
    This class needs to modify the char_t.cf attribute as a side effect so that
51
    libtcod will select the correct characters on flush.
52
    """
53
54
    def __new__(cls, ch_array, cf_array):
55
        self = ch_array.view(cls)
56
        self._cf_array = cf_array
57
        return self
58
59
    def __array_finalize__(self, obj):
60
        if obj is None:
61
            return
62
        self._cf_array = None
63
64
    def __repr__(self):
65
        return repr(self.view(np.ndarray))
0 ignored issues
show
Bug introduced by
The Instance of _ChBufferArray does not seem to have a member named view.

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...
66
67
    def __getitem__(self, index):
68
        """Slicing this array also slices its _cf_array attribute."""
69
        array = np.ndarray.__getitem__(self, index)
70
        if self._cf_array is None or array.size == 1:
71
            return array.view(np.ndarray)
72
        array._cf_array = self._cf_array[index]
73
        return array
74
75
    def _covert_ch_to_cf(self, index, ch_arr):
76
        """Apply a set of Unicode variables to libtcod's special format.
77
78
        _cf_array should be the same shape as ch_arr after being sliced by
79
        index.
80
        """
81
        if lib.TCOD_ctx.max_font_chars == 0:
82
            return # libtcod not initialized
83
        ch_table = ffi.buffer(
84
            lib.TCOD_ctx.ascii_to_tcod[0:lib.TCOD_ctx.max_font_chars])
85
        ch_table = np.frombuffer(ch_table, np.intc)
86
        self._cf_array[index] = ch_table[ch_arr.ravel()].reshape(ch_arr.shape)
87
88
    def __setitem__(self, index, value):
89
        """Properly set up the char_t.cf variables as a side effect."""
90
        np.ndarray.__setitem__(self, index, value)
91
        if self._cf_array is not None:
92
            self._covert_ch_to_cf(index, self[index])
93
94
95
class Console(object):
96
    """
97
    Args:
98
        width (int): Width of the new Console.
99
        height (int): Height of the new Console.
100
101
    .. versionadded:: 2.0
102
    """
103
104
    def __init__(self, width, height):
105
        self.cdata = ffi.gc(lib.TCOD_console_new(width, height),
106
                            lib.TCOD_console_delete)
107
        self._init_setup_console_data()
108
109
    @classmethod
110
    def _from_cdata(cls, cdata):
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...
111
        if isinstance(cdata, cls):
112
            return cdata
113
        self = object.__new__(cls)
114
        self.cdata = cdata
115
        self._init_setup_console_data()
116
        return self
117
118
    def _init_setup_console_data(self):
119
        """Setup numpy arrays over libtcod data buffers."""
120
        import numpy
0 ignored issues
show
Configuration introduced by
The import numpy could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

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

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

2. Missing __init__.py files

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

Loading history...
Unused Code introduced by
The variable numpy seems to be unused.
Loading history...
121
        if self.cdata == ffi.NULL:
122
            self._console_data = lib.TCOD_ctx.root
123
        else:
124
            self._console_data = ffi.cast('TCOD_console_data_t *', self.cdata)
125
126
        def unpack_color(image_cdata):
127
            """return a (height, width, 3) shaped array from an image struct"""
128
            color_data = lib.TCOD_image_get_colors(image_cdata)
129
            color_buffer = ffi.buffer(color_data[0:self.width * self.height])
130
            array = np.frombuffer(color_buffer, np.uint8)
131
            return array.reshape((self.height, self.width, 3))
132
133
        self._fg = unpack_color(self._console_data.fg_colors)
134
        self._bg = unpack_color(self._console_data.bg_colors)
135
136
        buf = self._console_data.ch_array
137
        buf = ffi.buffer(buf[0:self.width * self.height])
138
        self._ch = np.frombuffer(buf, np.intc).reshape((self.height,
139
                                                        self.width))
140
141
    @property
142
    def width(self):
143
        """int: The width of this Console. (read-only)"""
144
        return lib.TCOD_console_get_width(self.cdata)
145
146
    @property
147
    def height(self):
148
        """int: The height of this Console. (read-only)"""
149
        return lib.TCOD_console_get_height(self.cdata)
150
151
    @property
152
    def bg(self):
153
        """numpy.ndarray: A uint8 array with the shape: (height, width, 3).
154
155
        You can change the consoles background colors by using this array.
156
157
        Index this array with ``console.bg[y, x, channel]``
158
        """
159
        return self._bg
160
161
    @property
162
    def fg(self):
163
        """numpy.ndarray: A uint8 array with the shape: (height, width, 3).
164
165
        You can change the consoles foreground colors by using this array.
166
167
        Index this array with ``console.fg[y, x, channel]``
168
        """
169
        return self._fg
170
171
    @property
172
    def ch(self):
173
        """numpy.ndarray: An intc array with the shape: (height, width).
174
175
        You can change the consoles character codes by using this array.
176
177
        Index this array with ``console.ch[y, x]``
178
        """
179
        return self._ch
180
181
    @property
182
    def default_bg(self):
183
        """Tuple[int, int, int]: The default background color."""
184
        color = self._console_data.back
185
        return color.r, color.g, color.b
186
    @default_bg.setter
187
    def default_bg(self, color):
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...
188
        self._console_data.back = color
189
190
    @property
191
    def default_fg(self):
192
        """Tuple[int, int, int]: The default foreground color."""
193
        color = self._console_data.fore
194
        return color.r, color.g, color.b
195
    @default_fg.setter
196
    def default_fg(self, color):
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...
197
        self._console_data.fore = color
198
199
    @property
200
    def default_bg_blend(self):
201
        """int: The default blending mode."""
202
        return self._console_data.bkgnd_flag
203
    @default_bg_blend.setter
204
    def default_bg_blend(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...
205
        self._console_data.bkgnd_flag = value
206
207
    @property
208
    def default_alignment(self):
209
        """int: The default text alignment."""
210
        return self._console_data.alignment
211
    @default_alignment.setter
212
    def default_alignment(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...
213
        self._console_data.alignment = value
214
215
    def clear(self):
216
        """Reset this console to its default colors and the space character.
217
        """
218
        lib.TCOD_console_clear(self.cdata)
219
220
    def put_char(self, x, y, ch, bg_blend=BKGND_DEFAULT):
221
        """Draw the character c at x,y using the default colors and a blend mode.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (81/79).

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

Loading history...
222
223
        Args:
224
            x (int): The x coordinate from the left.
225
            y (int): The y coordinate from the top.
226
            ch (int): Character code to draw.  Must be in integer form.
227
            bg_blend (int): Blending mode to use, defaults to BKGND_DEFAULT.
228
        """
229
        lib.TCOD_console_put_char(self.cdata, x, y, ch, bg_blend)
230
231
    def print_(self, x, y, string, bg_blend=BKGND_DEFAULT, alignment=None):
232
        """Print a color formatted string on a console.
233
234
        Args:
235
            x (int): The x coordinate from the left.
236
            y (int): The y coordinate from the top.
237
            string (Text): A Unicode string optionaly using color codes.
238
        """
239
        alignment = self.default_alignment if alignment is None else alignment
240
241
        lib.TCOD_console_print_ex_utf(self.cdata, x, y,
242
                                      bg_blend, alignment, _fmt(string))
243
244
    def print_rect(self, x, y, width, height, string,
245
                   bg_blend=BKGND_DEFAULT, alignment=None):
246
        """Print a string constrained to a rectangle.
247
248
        If h > 0 and the bottom of the rectangle is reached,
249
        the string is truncated. If h = 0,
250
        the string is only truncated if it reaches the bottom of the console.
251
252
        Args:
253
            x (int): The x coordinate from the left.
254
            y (int): The y coordinate from the top.
255
            width (int): Maximum width to render the text.
256
            height (int): Maximum lines to render the text.
257
            string (Text): A Unicode string.
258
            bg_blend (int): Background blending flag.
259
            alignment (Optional[int]): Alignment flag.
260
261
        Returns:
262
            int: The number of lines of text once word-wrapped.
263
        """
264
        alignment = self.default_alignment if alignment is None else alignment
265
        return lib.TCOD_console_print_rect_ex_utf(self.cdata,
266
            x, y, width, height, bg_blend, alignment, _fmt(string))
267
268
    def get_height_rect(self, x, y, width, height, string):
269
        """Return the height of this text word-wrapped into this rectangle.
270
271
        Args:
272
            x (int): The x coordinate from the left.
273
            y (int): The y coordinate from the top.
274
            width (int): Maximum width to render the text.
275
            height (int): Maximum lines to render the text.
276
            string (Text): A Unicode string.
277
278
        Returns:
279
            int: The number of lines of text once word-wrapped.
280
        """
281
        return lib.TCOD_console_get_height_rect_utf(
282
            self.cdata, x, y, width, height, _fmt(string))
283
284
    def rect(self, x, y, width, height, clear, bg_blend=BKGND_DEFAULT):
285
        """Draw a the background color on a rect optionally clearing the text.
286
287
        If clr is True the affected tiles are changed to space character.
288
289
        Args:
290
            x (int): The x coordinate from the left.
291
            y (int): The y coordinate from the top.
292
            width (int): Maximum width to render the text.
293
            height (int): Maximum lines to render the text.
294
            clear (bool): If True all text in the affected area will be
295
                          removed.
296
            bg_blend (int): Background blending flag.
297
        """
298
        lib.TCOD_console_rect(self.cdata, x, y, width, height, clear, bg_blend)
299
300
    def hline(self, x, y, width, bg_blend=BKGND_DEFAULT):
301
        """Draw a horizontal line on the console.
302
303
        This always uses the character 196, the horizontal line character.
304
305
        Args:
306
            x (int): The x coordinate from the left.
307
            y (int): The y coordinate from the top.
308
            width (int): The horozontal length of this line.
309
            bg_blend (int): The background blending flag.
310
        """
311
        lib.TCOD_console_hline(self.cdata, x, y, width, bg_blend)
312
313
    def vline(self, x, y, height, bg_blend=BKGND_DEFAULT):
314
        """Draw a vertical line on the console.
315
316
        This always uses the character 179, the vertical line character.
317
318
        Args:
319
            x (int): The x coordinate from the left.
320
            y (int): The y coordinate from the top.
321
            height (int): The horozontal length of this line.
322
            bg_blend (int): The background blending flag.
323
        """
324
        lib.TCOD_console_vline(self.cdata, x, y, height, bg_blend)
325
326
    def print_frame(self, x, y, width, height, string='',
327
                    clear=True, bg_blend=BKGND_DEFAULT):
328
        """Draw a framed rectangle with optinal text.
329
330
        This uses the default background color and blend mode to fill the
331
        rectangle and the default foreground to draw the outline.
332
333
        string will be printed on the inside of the rectangle, word-wrapped.
334
335
        Args:
336
            x (int): The x coordinate from the left.
337
            y (int): The y coordinate from the top.
338
            width (int): The width if the frame.
339
            height (int): The height of the frame.
340
            string (Text): A Unicode string to print.
341
            clear (bool): If True all text in the affected area will be
342
                          removed.
343
            bg_blend (int): The background blending flag.
344
345
        Note:
346
            This method does not support Unicode outside of the 0-255 range.
347
        """
348
        lib.TCOD_console_print_frame(self.cdata, x, y, width, height,
349
                                     clear, bg_blend, string.encode('latin-1'))
350
351
    def blit(self, x, y, width, height,
352
             dest, dest_x, dest_y, fg_alpha=1.0, bg_alpha=1.0):
353
        """Blit from this console onto the ``dest`` console.
354
355
        Args:
356
            x (int): X coordinate of this console to blit, from the left.
357
            y (int): Y coordinate of this console to blit, from the top.
358
            width (int): The width of the region to blit.
359
360
                If this is 0 the maximum possible width will be used.
361
            height (int): The height of the region to blit.
362
363
                If this is 0 the maximum possible height will be used.
364
            dest (Console): The destintaion console to blit onto.
365
            dest_x (int): Leftmost coordinate of the destintaion console.
366
            dest_y (int): Topmost coordinate of the destintaion console.
367
            fg_alpha (float): Foreground color alpha vaule.
368
            bg_alpha (float): Background color alpha vaule.
369
        """
370
        lib.TCOD_console_blit(self.cdata, x, y, width, height,
371
                              _cdata(dest), dest_x, dest_y, fg_alpha, bg_alpha)
372
373
    def set_key_color(self, color):
374
        """Set a consoles blit transparent color.
375
376
        Args:
377
            color (Tuple[int, int, int]):
378
        """
379
        lib.TCOD_console_set_key_color(self.cdata, color)
380
381
    def __enter__(self):
382
        """Returns this console in a managed context.
383
384
        When the root console is used as a context, the graphical window will
385
        close once the context is left as if :any:`tcod.console_delete` was
386
        called on it.
387
388
        This is useful for some Python IDE's like IDLE, where the window would
389
        not be closed on its own otherwise.
390
        """
391
        if self.cdata != ffi.NULL:
392
            raise NotImplementedError('Only the root console has a context.')
393
        return self
394
395
    def __exit__(self, *args):
396
        """Closes the graphical window on exit.
397
398
        Some tcod functions may have undefined behavior after this point.
399
        """
400
        lib.TCOD_console_delete(self.cdata)
401
402
    def __bool__(self):
403
        """Returns False if this is the root console.
404
405
        This mimics libtcodpy behavior.
406
        """
407
        return self.cdata != ffi.NULL
408
409
    __nonzero__ = __bool__
410