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

Console.rect()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 1
c 2
b 0
f 1
dl 0
loc 6
rs 9.4285
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
3
4
import sys
5
6
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...
7
8
from tcod.tcod import _CDataWrapper, _cdata
9
from tcod.libtcod import ffi, lib
10
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...
11
12
13
if sys.version_info[0] == 2: # Python 2
14
    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...
15
        if not isinstance(string, unicode):
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'unicode'
Loading history...
16
            string = string.decode('latin-1')
17
        return string.replace(u'%', u'%%')
18
else:
19
    def _fmt(string):
20
        """Return a string that escapes 'C printf' side effects."""
21
        return string.replace('%', '%%')
22
23
24
class _ChBufferArray(np.ndarray):
25
    """Numpy subclass designed to access libtcod's character buffer.
26
27
    This class needs to modify the char_t.cf attribute as a side effect so that
28
    libtcod will select the correct characters on flush.
29
    """
30
31
    def __new__(cls, ch_array, cf_array):
32
        self = ch_array.view(cls)
33
        self._cf_array = cf_array
34
        return self
35
36
    def __array_finalize__(self, obj):
37
        if obj is None:
38
            return
39
        self._cf_array = None
40
41
    def __repr__(self):
42
        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...
43
44
    def __getitem__(self, index):
45
        """Slicing this array also slices its _cf_array attribute."""
46
        array = np.ndarray.__getitem__(self, index)
47
        if self._cf_array is None or array.size == 1:
48
            return array.view(np.ndarray)
49
        array._cf_array = self._cf_array[index]
50
        return array
51
52
    def _covert_ch_to_cf(self, index, ch_arr):
53
        """Apply a set of Unicode variables to libtcod's special format.
54
55
        _cf_array should be the same shape as ch_arr after being sliced by
56
        index.
57
        """
58
        if lib.TCOD_ctx.max_font_chars == 0:
59
            return # libtcod not initialized
60
        ch_table = ffi.buffer(
61
            lib.TCOD_ctx.ascii_to_tcod[0:lib.TCOD_ctx.max_font_chars])
62
        ch_table = np.frombuffer(ch_table, np.intc)
63
        self._cf_array[index] = ch_table[ch_arr.ravel()].reshape(ch_arr.shape)
64
65
    def __setitem__(self, index, value):
66
        """Properly set up the char_t.cf variables as a side effect."""
67
        np.ndarray.__setitem__(self, index, value)
68
        if self._cf_array is not None:
69
            self._covert_ch_to_cf(index, self[index])
70
71
72
class Console(_CDataWrapper):
73
    """
74
    Args:
75
        width (int): Width of the new Console.
76
        height (int): Height of the new Console.
77
78
    .. versionadded:: 2.0
79
    """
80
81
    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...
82
        self.cdata = self._get_cdata_from_args(*args, **kargs)
83
        if self.cdata is None:
84
            self._init(*args, **kargs)
85
        self._init_setup_console_data()
86
87
    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...
88
        self.cdata = ffi.gc(lib.TCOD_console_new(width, height),
89
                            lib.TCOD_console_delete)
90
91
    def _init_setup_console_data(self):
92
        """Setup numpy arrays over libtcod data buffers."""
93
        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...
94
        if self.cdata == ffi.NULL:
95
            self._console_data = lib.TCOD_ctx.root
96
        else:
97
            self._console_data = ffi.cast('TCOD_console_data_t *', self.cdata)
98
99
        def unpack_color(image_cdata):
100
            """return a (height, width, 3) shaped array from an image struct"""
101
            color_data = lib.TCOD_image_get_colors(image_cdata)
102
            color_buffer = ffi.buffer(color_data[0:self.width * self.height])
103
            array = np.frombuffer(color_buffer, np.uint8)
104
            return array.reshape((self.height, self.width, 3))
105
106
        self._fg = unpack_color(self._console_data.state.fg_colors)
107
        self._bg = unpack_color(self._console_data.state.bg_colors)
108
109
        buf = self._console_data.state.buf
110
        buf = ffi.buffer(buf[0:self.width * self.height])
111
        if ffi.sizeof('char_t') != 12:
112
            # I'm expecting some compiler to have this at 9.
113
            raise RuntimeError("Expected ffi.sizeof('char_t') to be 12. "
114
                               "Got %i instead." % ffi.sizeof('char_t'))
115
        buf = np.frombuffer(buf, [('c', np.intc),
116
                                   ('cf', np.intc),
117
                                   ('dirty', np.intc)])
118
        self._buf = buf.reshape((self.height, self.width))
119
        self._ch = _ChBufferArray(self._buf['c'], self._buf['cf'])
120
121
    @property
122
    def width(self):
123
        """int: The width of this Console. (read-only)"""
124
        return lib.TCOD_console_get_width(self.cdata)
125
126
    @property
127
    def height(self):
128
        """int: The height of this Console. (read-only)"""
129
        return lib.TCOD_console_get_height(self.cdata)
130
131
    @property
132
    def bg(self):
133
        """A numpy uint8 array with the shape (height, width, 3).
134
135
        You can change the consoles background colors by using this array.
136
137
        Index this array with ``console.bg[y, x, channel]``
138
        """
139
        return self._bg
140
141
    @property
142
    def fg(self):
143
        """A numpy uint8 array with the shape (height, width, 3).
144
145
        You can change the consoles foreground colors by using this array.
146
147
        Index this array with ``console.fg[y, x, channel]``
148
        """
149
        return self._fg
150
151
    @property
152
    def ch(self):
153
        """A numpy int array with the shape (height, width).
154
155
        You can change the consoles character codes by using this array.
156
157
        Index this array with ``console.ch[y, x]``
158
        """
159
        return self._ch
160
161
    @property
162
    def default_bg(self):
163
        """Tuple[int, int, int]: The default background color."""
164
        color = self._console_data.back
165
        return color.r, color.g, color.b
166
    @default_bg.setter
167
    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...
168
        self._console_data.back = color
169
170
    @property
171
    def default_fg(self):
172
        """Tuple[int, int, int]: The default foreground color."""
173
        color = self._console_data.fore
174
        return color.r, color.g, color.b
175
    @default_fg.setter
176
    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...
177
        self._console_data.fore = color
178
179
    @property
180
    def default_bg_blend(self):
181
        """int: The default blending mode."""
182
        return self._console_data.bkgnd_flag
183
    @default_bg_blend.setter
184
    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...
185
        self._console_data.bkgnd_flag = value
186
187
    @property
188
    def default_alignment(self):
189
        """int: The default text alignment."""
190
        return self._console_data.alignment
191
    @default_alignment.setter
192
    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...
193
        self._console_data.alignment = value
194
195
    def clear(self):
196
        """Reset this console to its default colors and the space character.
197
        """
198
        lib.TCOD_console_clear(self.cdata)
199
200
    def put_char(self, x, y, ch, bg_blend=BKGND_DEFAULT):
201
        """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...
202
203
        Args:
204
            x (int): Character x position from the left.
205
            y (int): Character y position from the top.
206
            ch (int): Character code to draw.  Must be in integer form.
207
            bg_blend (int): Blending mode to use, defaults to BKGND_DEFAULT.
208
        """
209
        lib.TCOD_console_put_char(self.cdata, x, y, ch, bg_blend)
210
211
    def print_(self, x, y, string, bg_blend=BKGND_DEFAULT, alignment=None):
212
        """Print a color formatted string on a console.
213
214
        Args:
215
            x (int): Character x position from the left.
216
            y (int): Character y position from the top.
217
            string (Text): A unicode string optionaly using color codes.
218
        """
219
        alignment = self.default_alignment if alignment is None else alignment
220
221
        lib.TCOD_console_print_ex_utf(self.cdata, x, y,
222
                                      bg_blend, alignment, _fmt(string))
223
224
    def print_rect(self, x, y, width, height, string,
225
                   bg_blend=BKGND_DEFAULT, alignment=None):
226
        """Print a string constrained to a rectangle.
227
228
        If h > 0 and the bottom of the rectangle is reached,
229
        the string is truncated. If h = 0,
230
        the string is only truncated if it reaches the bottom of the console.
231
232
        Returns:
233
            int: The number of lines of text once word-wrapped.
234
        """
235
        alignment = self.default_alignment if alignment is None else alignment
236
        return lib.TCOD_console_print_rect_ex_utf(self.cdata,
237
            x, y, width, height, bg_blend, alignment, _fmt(string))
238
239
    def get_height_rect(self, x, y, width, height, string):
240
        """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...
241
242
        Returns:
243
            int: The number of lines of text once word-wrapped.
244
        """
245
        return lib.TCOD_console_get_height_rect_utf(
246
            self.cdata, x, y, width, height, _fmt(string))
247
248
    def rect(self, x, y, width, height, clear, bg_blend=BKGND_DEFAULT):
249
        """Draw a the background color on a rect optionally clearing the text.
250
251
        If clr is True the affected tiles are changed to space character.
252
        """
253
        lib.TCOD_console_rect(self.cdata, x, y, width, height, clear, bg_blend)
254
255
    def hline(self, x, y, width, bg_blend=BKGND_DEFAULT):
256
        """Draw a horizontal line on the console.
257
258
        This always uses the character 196, the horizontal line character.
259
        """
260
        lib.TCOD_console_hline(self.cdata, x, y, width, bg_blend)
261
262
    def vline(self, x, y, height, bg_blend=BKGND_DEFAULT):
263
        """Draw a vertical line on the console.
264
265
        This always uses the character 179, the vertical line character.
266
        """
267
        lib.TCOD_console_vline(self.cdata, x, y, height, bg_blend)
268
269
    def print_frame(self, x, y, width, height, string='',
270
                    clear=True, bg_blend=BKGND_DEFAULT):
271
        """Draw a framed rectangle with optinal text.
272
273
        This uses the default background color and blend mode to fill the
274
        rectangle and the default foreground to draw the outline.
275
276
        string will be printed on the inside of the rectangle, word-wrapped.
277
        """
278
        lib.TCOD_console_print_frame(self.cdata, x, y, width, height,
279
                                     clear, bg_blend, b'')
280
        self.print_rect(x + 1, y + 1, width - 2, height - 2, string, bg_blend)
281
282
    def blit(self, x, y, width, height,
283
             dest, dest_x, dest_y, fg_alpha=1.0, bg_alpha=1.0):
284
        """Blit this console from x,y,w,h to the console dst at xdst,ydst."""
285
        lib.TCOD_console_blit(self.cdata, x, y, width, height,
286
                              _cdata(dest), dest_x, dest_y, fg_alpha, bg_alpha)
287
288
    def set_key_color(self, color):
289
        """Set a consoles blit transparent color."""
290
        lib.TCOD_console_set_key_color(self.cdata, color)
291
292
    def __enter__(self):
293
        """Context manage the root console.
294
295
        When the root console is used in a context, the grapical window will
296
        close once the context is left as if :any:`tcod.console_delete` was
297
        called on it.
298
299
        This is useful for some Python IDE's, such as IDLE.
300
        """
301
        if self.cdata != ffi.NULL:
302
            raise NotImplementedError('Only the root console has a context.')
303
        return self
304
305
    def __exit__(self, *args):
306
        """Closes the graphical window on exit.
307
308
        Some tcod functions may have undefined behaviour after this point.
309
        """
310
        lib.TCOD_console_delete(self.cdata)
311