Completed
Push — master ( c04c86...3dd2cc )
by Kyle
01:12
created

Console.print_()   A

Complexity

Conditions 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
0 ignored issues
show
Coding Style introduced by
This module 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...
2
from __future__ import absolute_import as _
3
4
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...
5
6
from tcod.tcod import _CDataWrapper
7
from tcod.tcod import _int, _fmt_bytes, _fmt_unicode
8
from tcod.libtcod import ffi, lib
9
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...
10
11
class _ChBufferArray(np.ndarray):
12
    """Numpy subclass designed to access libtcod's character buffer.
13
14
    This class needs to modify the char_t.cf attribute as a side effect so that
15
    libtcod will select the correct characters on flush.
16
    """
17
18
    def __new__(cls, ch_array, cf_array):
19
        self = ch_array.view(cls)
20
        self._cf_array = cf_array
21
        return self
22
23
    def __array_finalize__(self, obj):
24
        if obj is None:
25
            return
26
        self._cf_array = None
27
28
    def __repr__(self):
29
        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...
30
31
    def __getitem__(self, index):
32
        """Slicing this array also slices its _cf_array attribute."""
33
        array = np.ndarray.__getitem__(self, index)
34
        if self._cf_array is None or array.size == 1:
35
            return array.view(np.ndarray)
36
        array._cf_array = self._cf_array[index]
37
        return array
38
39
    def _covert_ch_to_cf(self, index, ch_arr):
40
        """Apply a set of Unicode variables to libtcod's special format.
41
42
        _cf_array should be the same shape as ch_arr after being sliced by
43
        index.
44
        """
45
        if lib.TCOD_ctx.max_font_chars == 0:
46
            return # libtcod not initialized
47
        ch_table = ffi.buffer(
48
            lib.TCOD_ctx.ascii_to_tcod[0:lib.TCOD_ctx.max_font_chars])
49
        ch_table = np.frombuffer(ch_table, np.intc)
50
        self._cf_array[index] = ch_table[ch_arr.ravel()].reshape(ch_arr.shape)
51
52
    def __setitem__(self, index, value):
53
        """Properly set up the char_t.cf variables as a side effect."""
54
        np.ndarray.__setitem__(self, index, value)
55
        if self._cf_array is not None:
56
            self._covert_ch_to_cf(index, self[index])
57
58
class Console(_CDataWrapper):
59
    """
60
    Args:
61
        width (int): Width of the new Console.
62
        height (int): Height of the new Console.
63
64
    .. versionadded:: 2.0
65
    """
66
67
    def __init__(self, *args, **kargs):
0 ignored issues
show
Bug introduced by
The __init__ method of the super-class _CDataWrapper is not called.

It is generally advisable to initialize the super-class by calling its __init__ method:

class SomeParent:
    def __init__(self):
        self.x = 1

class SomeChild(SomeParent):
    def __init__(self):
        # Initialize the super class
        SomeParent.__init__(self)
Loading history...
68
        self.cdata = self._get_cdata_from_args(*args, **kargs)
69
        if self.cdata is None:
70
            self._init(*args, **kargs)
71
        self._init_setup_console_data()
72
73
    def _init(self, width, height):
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...
74
        self.cdata = ffi.gc(lib.TCOD_console_new(width, height),
75
                            lib.TCOD_console_delete)
76
77
    def _init_setup_console_data(self):
78
        """Setup numpy arrays over libtcod data buffers."""
79
        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...
80
        if self.cdata == ffi.NULL:
81
            self._console_data = lib.TCOD_ctx.root
82
        else:
83
            self._console_data = ffi.cast('TCOD_console_data_t *', self.cdata)
84
85
        def unpack_color(image_cdata):
86
            """return a (height, width, 3) shaped array from an image struct"""
87
            color_data = lib.TCOD_image_get_colors(image_cdata)
88
            color_buffer = ffi.buffer(color_data[0:self.width * self.height])
89
            array = np.frombuffer(color_buffer, np.uint8)
90
            return array.reshape((self.height, self.width, 3))
91
92
        self._fg = unpack_color(self._console_data.state.fg_colors)
93
        self._bg = unpack_color(self._console_data.state.bg_colors)
94
95
        buf = self._console_data.state.buf
96
        buf = ffi.buffer(buf[0:self.width * self.height])
97
        if ffi.sizeof('char_t') != 12:
98
            # I'm expecting some compiler to have this at 9.
99
            raise RuntimeError("Expected ffi.sizeof('char_t') to be 12. "
100
                               "Got %i instead." % ffi.sizeof('char_t'))
101
        buf = np.frombuffer(buf, [('c', np.intc),
102
                                   ('cf', np.intc),
103
                                   ('dirty', np.intc)])
104
        self._buf = buf.reshape((self.height, self.width))
105
        self._ch = _ChBufferArray(self._buf['c'], self._buf['cf'])
106
107
    @property
108
    def width(self):
109
        """int: The width of this Console. (read-only)"""
110
        return lib.TCOD_console_get_width(self.cdata)
111
112
    @property
113
    def height(self):
114
        """int: The height of this Console. (read-only)"""
115
        return lib.TCOD_console_get_height(self.cdata)
116
117
    @property
118
    def bg(self):
119
        """A numpy array with the shape (height, width, 3).
120
121
        You can change the background color by using this array.
122
123
        Index this array with ``console.bg[y, x, channel]``
124
        """
125
        return self._bg
126
127
    @property
128
    def fg(self):
129
        """A numpy array with the shape (height, width, 3).
130
131
        You can change the foreground color by using this array.
132
133
        Index this array with ``console.fg[y, x, channel]``
134
        """
135
        return self._fg
136
137
    @property
138
    def ch(self):
139
        """A numpy array with the shape (height, width).
140
141
        You can change the character tiles by using this array.
142
143
        Index this array with ``console.ch[y, x]``
144
        """
145
        return self._ch
146
147
    @property
148
    def default_bg(self):
149
        """Tuple[int, int, int]: The default background color."""
150
        color = self._console_data.back
151
        return color.r, color.g, color.b
152
    @default_bg.setter
153
    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...
154
        self._console_data.back = color
155
156
    @property
157
    def default_fg(self):
158
        """Tuple[int, int, int]: The default foreground color."""
159
        color = self._console_data.fore
160
        return color.r, color.g, color.b
161
    @default_fg.setter
162
    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...
163
        self._console_data.fore = color
164
165
    @property
166
    def default_blend(self):
167
        """int: The default blending mode."""
168
        return self._console_data.bkgnd_flag
169
    @default_blend.setter
170
    def default_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...
171
        self._console_data.bkgnd_flag = value
172
173
    @property
174
    def default_alignment(self):
175
        """int: The default text alignment."""
176
        return self._console_data.alignment
177
    @default_alignment.setter
178
    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...
179
        self._console_data.alignment = value
180
181
    def clear(self):
182
        """Reset this console to its default colors and the space character.
183
        """
184
        lib.TCOD_console_clear(self.cdata)
185
186
    def put_char(self, x, y, ch, flag=BKGND_DEFAULT):
187
        """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...
188
189
        Args:
190
            x (int): Character x position from the left.
191
            y (int): Character y position from the top.
192
            c (Union[int, AnyStr]): Character to draw, can be an integer or string.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (83/79).

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

Loading history...
193
            flag (int): Blending mode to use, defaults to BKGND_DEFAULT.
194
        """
195
        lib.TCOD_console_put_char(self.cdata, x, y, _int(ch), flag)
196
197
    def put_char_ex(self, x, y, ch, fore, back):
198
        """Draw the character c at x,y using the colors fore and back.
199
200
        Args:
201
            x (int): Character x position from the left.
202
            y (int): Character y position from the top.
203
            c (Union[int, AnyStr]): Character to draw, can be an integer or string.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (83/79).

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

Loading history...
204
            fore (Union[Tuple[int, int, int], Sequence[int]]):
205
                An (r, g, b) sequence or Color instance.
206
            back (Union[Tuple[int, int, int], Sequence[int]]):
207
                An (r, g, b) sequence or Color instance.
208
        """
209
        lib.TCOD_console_put_char_ex(self.cdata, x, y,
210
                                 _int(ch), fore, back)
211
212
    def set_char_bg(self, x, y, col, flag=BKGND_SET):
213
        """Change the background color of x,y to col using a blend mode.
214
215
        Args:
216
            x (int): Character x position from the left.
217
            y (int): Character y position from the top.
218
            col (Union[Tuple[int, int, int], Sequence[int]]):
219
                An (r, g, b) sequence or Color instance.
220
            flag (int): Blending mode to use, defaults to BKGND_SET.
221
        """
222
        lib.TCOD_console_set_char_background(self.cdata, x, y, col, flag)
223
224
    def set_char_fg(self, x, y, color):
0 ignored issues
show
Unused Code introduced by
The argument color seems to be unused.
Loading history...
225
        """Change the foreground color of x,y to col.
226
227
        Args:
228
            x (int): Character x position from the left.
229
            y (int): Character y position from the top.
230
            color (Union[Tuple[int, int, int], Sequence[int]]):
231
                An (r, g, b) sequence or Color instance.
232
        """
233
        lib.TCOD_console_set_char_foreground(self.cdata, x, y, col)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'col'
Loading history...
234
235
    def set_char(self, x, y, ch):
236
        """Change the character at x,y to c, keeping the current colors.
237
238
        Args:
239
            x (int): Character x position from the left.
240
            y (int): Character y position from the top.
241
            c (Union[int, AnyStr]): Character to draw, can be an integer or string.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (83/79).

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

Loading history...
242
        """
243
        lib.TCOD_console_set_char(self.cdata, x, y, _int(ch))
244
245
    def print_(self, x, y, fmt):
246
        """Print a color formatted string on a console.
247
248
        Args:
249
            x (int): Character x position from the left.
250
            y (int): Character y position from the top.
251
            fmt (AnyStr): A unicode or bytes string optionaly using color codes.
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...
252
        """
253
        lib.TCOD_console_print_utf(self.cdata, x, y, _fmt_unicode(fmt))
254
255
    def print_ex(self, x, y, flag, alignment, fmt):
256
        """Print a string on a console using a blend mode and alignment mode.
257
258
        Args:
259
            x (int): Character x position from the left.
260
            y (int): Character y position from the top.
261
        """
262
        lib.TCOD_console_print_ex_utf(self.cdata, x, y,
263
                                      flag, alignment, _fmt_unicode(fmt))
264
265
    def print_rect(self, x, y, w, h, fmt):
0 ignored issues
show
Unused Code introduced by
The argument h seems to be unused.
Loading history...
Unused Code introduced by
The argument w seems to be unused.
Loading history...
266
        """Print a string constrained to a rectangle.
267
268
        If h > 0 and the bottom of the rectangle is reached,
269
        the string is truncated. If h = 0,
270
        the string is only truncated if it reaches the bottom of the console.
271
272
273
274
        Returns:
275
            int: The number of lines of text once word-wrapped.
276
        """
277
        return lib.TCOD_console_print_rect_utf(
278
            self.cdata, x, y, width, height, _fmt_unicode(fmt))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'width'
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'height'
Loading history...
279
280
    def print_rect_ex(self, x, y, w, h, flag, alignment, fmt):
0 ignored issues
show
Unused Code introduced by
The argument w seems to be unused.
Loading history...
Unused Code introduced by
The argument h seems to be unused.
Loading history...
281
        """Print a string constrained to a rectangle with blend and alignment.
282
283
        Returns:
284
            int: The number of lines of text once word-wrapped.
285
        """
286
        return lib.TCOD_console_print_rect_ex_utf(self.cdata,
287
            x, y, width, height, flag, alignment, _fmt_unicode(fmt))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'width'
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'height'
Loading history...
288
289
    def get_height_rect(self, x, y, width, height, fmt):
290
        """Return the height of this text once word-wrapped into this rectangle.
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...
291
292
        Returns:
293
            int: The number of lines of text once word-wrapped.
294
        """
295
        return lib.TCOD_console_get_height_rect_utf(
296
            self.cdata, x, y, width, height, _fmt_unicode(fmt))
297
298
    def rect(self, x, y, w, h, clr, flag=BKGND_DEFAULT):
299
        """Draw a the background color on a rect optionally clearing the text.
300
301
        If clr is True the affected tiles are changed to space character.
302
        """
303
        lib.TCOD_console_rect(self.cdata, x, y, w, h, clr, flag)
304
305
    def hline(self, x, y, width, flag=BKGND_DEFAULT):
306
        """Draw a horizontal line on the console.
307
308
        This always uses the character 196, the horizontal line character.
309
        """
310
        lib.TCOD_console_hline(self.cdata, x, y, width, flag)
311
312
    def vline(self, x, y, height, flag=BKGND_DEFAULT):
313
        """Draw a vertical line on the console.
314
315
        This always uses the character 179, the vertical line character.
316
        """
317
        lib.TCOD_console_vline(self.cdata, x, y, height, flag)
318
319
    def print_frame(self, x, y, w, h, clear=True, flag=BKGND_DEFAULT, fmt=b''):
320
        """Draw a framed rectangle with optinal text.
321
322
        This uses the default background color and blend mode to fill the
323
        rectangle and the default foreground to draw the outline.
324
325
        fmt will be printed on the inside of the rectangle, word-wrapped.
326
        """
327
        lib.TCOD_console_print_frame(self.cdata, x, y, w, h, clear, flag,
328
                                  _fmt_bytes(fmt))
329
330
    def blit(self, x, y, w, h,
331
             dest, dest_x, dest_y, fg_alpha=1, bg_alpha=1):
0 ignored issues
show
Unused Code introduced by
The argument dest seems to be unused.
Loading history...
332
        """Blit this console from x,y,w,h to the console dst at xdst,ydst."""
333
        lib.TCOD_console_blit(self.cdata, x, y, w, h,
334
                              _cdata(dst), dest_x, dest_y, fg_alpha, bg_alpha)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'dst'
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable '_cdata'
Loading history...
335
336
    def set_key_color(self, color):
337
        """Set a consoles blit transparent color."""
338
        lib.TCOD_console_set_key_color(self.cdata, color)
339