-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathconsole.py
More file actions
1359 lines (1121 loc) · 46.6 KB
/
console.py
File metadata and controls
1359 lines (1121 loc) · 46.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Libtcod consoles are a strictly tile-based representation of text and color.
To render a console you need a tileset and a window to render to.
See :ref:`getting-started` for info on how to set those up.
"""
from __future__ import annotations
import warnings
from os import PathLike
from pathlib import Path
from typing import Any, Iterable, Literal
import numpy as np
from numpy.typing import NDArray
import tcod._internal
import tcod.constants
from tcod._internal import _check, deprecate
from tcod.loader import ffi, lib
def _fmt(string: str) -> bytes:
"""Return a string that escapes 'C printf' side effects."""
return string.encode("utf-8").replace(b"%", b"%%")
_root_console = None
rgba_graphic = np.dtype([("ch", np.intc), ("fg", "4B"), ("bg", "4B")])
"""A NumPy :any:`dtype` compatible with :any:`Console.rgba`.
This dtype is: ``np.dtype([("ch", np.intc), ("fg", "4B"), ("bg", "4B")])``
.. versionadded:: 12.3
"""
rgb_graphic = np.dtype([("ch", np.intc), ("fg", "3B"), ("bg", "3B")])
"""A NumPy :any:`dtype` compatible with :any:`Console.rgb`.
This dtype is: ``np.dtype([("ch", np.intc), ("fg", "3B"), ("bg", "3B")])``
.. versionadded:: 12.3
"""
class Console:
"""A console object containing a grid of characters with foreground/background colors.
`width` and `height` are the size of the console (in tiles.)
`order` determines how the axes of NumPy array attributes are arranged.
With the default setting of `"C"` you use [y, x] to index a consoles
arrays such as :any:`Console.rgb`.
`order="F"` will swap the first two axes which allows for more intuitive
`[x, y]` indexing. To be consistent you may have to do this for every
NumPy array to create.
With `buffer` the console can be initialized from another array. The
`buffer` should be compatible with the `width`, `height`, and `order`
given; and should also have a dtype compatible with :any:`Console.DTYPE`.
.. versionchanged:: 4.3
Added `order` parameter.
.. versionchanged:: 8.5
Added `buffer`, `copy`, and default parameters.
Arrays are initialized as if the :any:`clear` method was called.
.. versionchanged:: 10.0
`DTYPE` changed, `buffer` now requires colors with an alpha channel.
Attributes:
console_c: A python-cffi "TCOD_Console*" object.
DTYPE:
A class attribute which provides a dtype compatible with this
class.
``[("ch", np.intc), ("fg", "(4,)u1"), ("bg", "(4,)u1")]``
Example::
>>> buffer = np.zeros(
... shape=(20, 3),
... dtype=tcod.console.Console.DTYPE,
... order="F",
... )
>>> buffer["ch"] = ord('_')
>>> buffer["ch"][:, 1] = ord('x')
>>> c = tcod.console.Console(20, 3, order="F", buffer=buffer)
>>> print(c)
<____________________
xxxxxxxxxxxxxxxxxxxx
____________________>
.. versionadded:: 8.5
.. versionchanged:: 10.0
Added an alpha channel to the color types.
"""
DTYPE = rgba_graphic
# A structured array type with the added "fg_rgb" and "bg_rgb" fields.
_DTYPE_RGB = np.dtype(
{
"names": ["ch", "fg", "bg"],
"formats": [np.int32, "3u1", "3u1"],
"offsets": [0, 4, 8],
"itemsize": 12,
}
)
def __init__(
self,
width: int,
height: int,
order: Literal["C", "F"] = "C",
buffer: NDArray[Any] | None = None,
) -> None:
self._key_color: tuple[int, int, int] | None = None
self._order = tcod._internal.verify_order(order)
if buffer is not None:
if self._order == "F":
buffer = buffer.transpose()
self._tiles: NDArray[Any] = np.ascontiguousarray(buffer, self.DTYPE)
else:
self._tiles = np.ndarray((height, width), dtype=self.DTYPE)
# libtcod uses the root console for defaults.
default_bg_blend = 0
default_alignment = 0
if lib.TCOD_ctx.root != ffi.NULL:
default_bg_blend = lib.TCOD_ctx.root.bkgnd_flag
default_alignment = lib.TCOD_ctx.root.alignment
self._console_data = self.console_c = ffi.new(
"struct TCOD_Console*",
{
"w": width,
"h": height,
"elements": width * height,
"tiles": ffi.from_buffer("struct TCOD_ConsoleTile*", self._tiles),
"bkgnd_flag": default_bg_blend,
"alignment": default_alignment,
"fore": (255, 255, 255),
"back": (0, 0, 0),
},
)
if buffer is None:
self.clear()
@classmethod
def _from_cdata(cls, cdata: Any, order: Literal["C", "F"] = "C") -> Console: # noqa: ANN401
"""Return a Console instance which wraps this `TCOD_Console*` object."""
if isinstance(cdata, cls):
return cdata
self: Console = object.__new__(cls)
self.console_c = cdata
self._init_setup_console_data(order)
return self
@classmethod
def _get_root(cls, order: Literal["C", "F"] | None = None) -> Console:
"""Return a root console singleton with valid buffers.
This function will also update an already active root console.
"""
global _root_console
if _root_console is None:
_root_console = object.__new__(cls)
self: Console = _root_console
if order is not None:
self._order = order
self.console_c = ffi.NULL
self._init_setup_console_data(self._order)
return self
def _init_setup_console_data(self, order: Literal["C", "F"] = "C") -> None:
"""Setup numpy arrays over libtcod data buffers."""
global _root_console
self._key_color = None
if self.console_c == ffi.NULL:
_root_console = self
self._console_data = lib.TCOD_ctx.root
else:
self._console_data = ffi.cast("struct TCOD_Console*", self.console_c)
self._tiles: NDArray[Any] = np.frombuffer( # type: ignore
ffi.buffer(self._console_data.tiles[0 : self.width * self.height]),
dtype=self.DTYPE,
).reshape((self.height, self.width))
self._order = tcod._internal.verify_order(order)
@property
def width(self) -> int:
"""The width of this Console."""
return lib.TCOD_console_get_width(self.console_c) # type: ignore
@property
def height(self) -> int:
"""The height of this Console."""
return lib.TCOD_console_get_height(self.console_c) # type: ignore
@property
def bg(self) -> NDArray[np.uint8]:
"""A uint8 array with the shape (height, width, 3).
You can change the consoles background colors by using this array.
Index this array with ``console.bg[i, j, channel] # order='C'`` or
``console.bg[x, y, channel] # order='F'``.
"""
bg: np.ndarray[Any, np.dtype[np.uint8]] = self._tiles["bg"][..., :3]
if self._order == "F":
bg = bg.transpose(1, 0, 2)
return bg
@property
def fg(self) -> NDArray[np.uint8]:
"""A uint8 array with the shape (height, width, 3).
You can change the consoles foreground colors by using this array.
Index this array with ``console.fg[i, j, channel] # order='C'`` or
``console.fg[x, y, channel] # order='F'``.
"""
fg: np.ndarray[Any, np.dtype[np.uint8]] = self._tiles["fg"][..., :3]
if self._order == "F":
fg = fg.transpose(1, 0, 2)
return fg
@property
def ch(self) -> NDArray[np.intc]:
"""An integer array with the shape (height, width).
You can change the consoles character codes by using this array.
Index this array with ``console.ch[i, j] # order='C'`` or
``console.ch[x, y] # order='F'``.
"""
return self._tiles["ch"].T if self._order == "F" else self._tiles["ch"]
@property
@deprecate("This attribute has been renamed to `rgba`.")
def tiles(self) -> NDArray[Any]:
"""An array of this consoles raw tile data.
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
Colors include an alpha channel but how alpha works is currently
undefined.
.. versionadded:: 10.0
.. deprecated:: 12.3
Use :any:`Console.rgba` instead.
"""
return self.rgba
@property
@deprecate("This attribute has been renamed to `rgba`.")
def buffer(self) -> NDArray[Any]:
"""An array of this consoles raw tile data.
.. versionadded:: 11.4
.. deprecated:: 11.8
Use :any:`Console.rgba` instead.
"""
return self.rgba
@property
@deprecate("This attribute has been renamed to `rgb`.")
def tiles_rgb(self) -> NDArray[Any]:
"""An array of this consoles data without the alpha channel.
.. versionadded:: 11.8
.. deprecated:: 12.3
Use :any:`Console.rgb` instead.
"""
return self.rgb
@property
@deprecate("This attribute has been renamed to `rgb`.")
def tiles2(self) -> NDArray[Any]:
"""This name is deprecated in favour of :any:`rgb`.
.. versionadded:: 11.3
.. deprecated:: 11.8
Use :any:`Console.rgb` instead.
"""
return self.rgb
@property
def rgba(self) -> NDArray[Any]:
"""An array of this consoles raw tile data.
The axes of this array is affected by the `order` parameter given to
initialize the console.
Example:
>>> con = tcod.console.Console(10, 2)
>>> con.rgba[0, 0] = (
... ord("X"),
... (*tcod.white, 255),
... (*tcod.black, 255),
... )
>>> con.rgba[0, 0]
(88, [255, 255, 255, 255], [ 0, 0, 0, 255])
.. versionadded:: 12.3
"""
return self._tiles.T if self._order == "F" else self._tiles
@property
def rgb(self) -> NDArray[Any]:
"""An array of this consoles data without the alpha channel.
The axes of this array is affected by the `order` parameter given to
initialize the console.
The :any:`rgb_graphic` dtype can be used to make arrays compatible
with this attribute that are independent of a :any:`Console`.
Example:
>>> con = tcod.console.Console(10, 2)
>>> con.rgb[0, 0] = ord("@"), tcod.yellow, tcod.black
>>> con.rgb[0, 0]
(64, [255, 255, 0], [0, 0, 0])
>>> con.rgb["bg"] = tcod.blue
>>> con.rgb[0, 0]
(64, [255, 255, 0], [ 0, 0, 255])
.. versionadded:: 12.3
"""
return self.rgba.view(self._DTYPE_RGB)
@property
def default_bg(self) -> tuple[int, int, int]:
"""Tuple[int, int, int]: The default background color."""
color = self._console_data.back
return color.r, color.g, color.b
@default_bg.setter
@deprecate("Console defaults have been deprecated.")
def default_bg(self, color: tuple[int, int, int]) -> None:
self._console_data.back = color
@property
def default_fg(self) -> tuple[int, int, int]:
"""Tuple[int, int, int]: The default foreground color."""
color = self._console_data.fore
return color.r, color.g, color.b
@default_fg.setter
@deprecate("Console defaults have been deprecated.")
def default_fg(self, color: tuple[int, int, int]) -> None:
self._console_data.fore = color
@property
def default_bg_blend(self) -> int:
"""int: The default blending mode."""
return self._console_data.bkgnd_flag # type: ignore
@default_bg_blend.setter
@deprecate("Console defaults have been deprecated.")
def default_bg_blend(self, value: int) -> None:
self._console_data.bkgnd_flag = value
@property
def default_alignment(self) -> int:
"""int: The default text alignment."""
return self._console_data.alignment # type: ignore
@default_alignment.setter
@deprecate("Console defaults have been deprecated.")
def default_alignment(self, value: int) -> None:
self._console_data.alignment = value
def __clear_warning(self, name: str, value: tuple[int, int, int]) -> None:
"""Raise a warning for bad default values during calls to clear."""
warnings.warn(
f"Clearing with the console default values is deprecated.\nAdd {name}={value!r} to this call.",
DeprecationWarning,
stacklevel=3,
)
def clear(
self,
ch: int = 0x20,
fg: tuple[int, int, int] = ..., # type: ignore
bg: tuple[int, int, int] = ..., # type: ignore
) -> None:
"""Reset all values in this console to a single value.
`ch` is the character to clear the console with. Defaults to the space
character.
`fg` and `bg` are the colors to clear the console with. Defaults to
white-on-black if the console defaults are untouched.
.. note::
If `fg`/`bg` are not set, they will default to
:any:`default_fg`/:any:`default_bg`.
However, default values other than white-on-back are deprecated.
.. versionchanged:: 8.5
Added the `ch`, `fg`, and `bg` parameters.
Non-white-on-black default values are deprecated.
"""
if fg is ...: # type: ignore
fg = self.default_fg
if fg != (255, 255, 255):
self.__clear_warning("fg", fg)
if bg is ...: # type: ignore
bg = self.default_bg
if bg != (0, 0, 0):
self.__clear_warning("bg", bg)
self._tiles[...] = ch, (*fg, 255), (*bg, 255)
def put_char(
self,
x: int,
y: int,
ch: int,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw the character c at x,y using the default colors and a blend mode.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
ch (int): Character code to draw. Must be in integer form.
bg_blend (int): Blending mode to use, defaults to BKGND_DEFAULT.
"""
lib.TCOD_console_put_char(self.console_c, x, y, ch, bg_blend)
__ALIGNMENT_LOOKUP = {0: "tcod.LEFT", 1: "tcod.RIGHT", 2: "tcod.CENTER"}
__BG_BLEND_LOOKUP = {
0: "tcod.BKGND_NONE",
1: "tcod.BKGND_SET",
2: "tcod.BKGND_MULTIPLY",
3: "tcod.BKGND_LIGHTEN",
4: "tcod.BKGND_DARKEN",
5: "tcod.BKGND_SCREEN",
6: "tcod.BKGND_COLOR_DODGE",
7: "tcod.BKGND_COLOR_BURN",
8: "tcod.BKGND_ADD",
9: "tcod.BKGND_ADDA",
10: "tcod.BKGND_BURN",
11: "tcod.BKGND_OVERLAY",
12: "tcod.BKGND_ALPH",
13: "tcod.BKGND_DEFAULT",
}
def __deprecate_defaults( # noqa: C901, PLR0912
self,
new_func: str,
bg_blend: Any, # noqa: ANN401
alignment: Any = ..., # noqa: ANN401
clear: Any = ..., # noqa: ANN401
) -> None:
"""Return the parameters needed to recreate the current default state."""
if not __debug__:
return
fg: tuple[int, int, int] | None = self.default_fg
bg: tuple[int, int, int] | None = self.default_bg
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
bg_blend = self.default_bg_blend if bg_blend == tcod.constants.BKGND_DEFAULT else None
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
bg_blend = None
if bg_blend == tcod.constants.BKGND_SET:
bg_blend = None
if alignment is None:
alignment = self.default_alignment
if alignment == tcod.constants.LEFT:
alignment = None
else:
alignment = None
if clear is not ...:
fg = None
params = []
if clear is True:
params.append('ch=ord(" ")')
if clear is False:
params.append("ch=0")
if fg is not None:
params.append(f"fg={fg}")
if bg is not None:
params.append(f"bg={bg}")
if bg_blend is not None:
params.append(f"bg_blend={self.__BG_BLEND_LOOKUP[bg_blend]}")
if alignment is not None:
params.append(f"alignment={self.__ALIGNMENT_LOOKUP[alignment]}")
param_str = ", ".join(params)
param_str = "." if not param_str else f" and add the following parameters:\n{param_str}"
warnings.warn(
"Console functions using default values have been deprecated.\n"
f"Replace this method with `Console.{new_func}`{param_str}",
FutureWarning,
stacklevel=3,
)
def print_(
self,
x: int,
y: int,
string: str,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
alignment: int | None = None,
) -> None:
"""Print a color formatted string on a console.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
string (str): A Unicode string optionally using color codes.
bg_blend (int): Blending mode to use, defaults to BKGND_DEFAULT.
alignment (Optional[int]): Text alignment.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.print` instead, calling this function will print
a warning detailing which default values need to be made explicit.
"""
self.__deprecate_defaults("print", bg_blend, alignment)
alignment = self.default_alignment if alignment is None else alignment
lib.TCOD_console_printf_ex(self.console_c, x, y, bg_blend, alignment, _fmt(string))
def print_rect(
self,
x: int,
y: int,
width: int,
height: int,
string: str,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
alignment: int | None = None,
) -> int:
"""Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the console.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
string (str): A Unicode string.
bg_blend (int): Background blending flag.
alignment (Optional[int]): Alignment flag.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.print_box` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("print_box", bg_blend, alignment)
alignment = self.default_alignment if alignment is None else alignment
return int(
lib.TCOD_console_printf_rect_ex(
self.console_c,
x,
y,
width,
height,
bg_blend,
alignment,
_fmt(string),
)
)
def get_height_rect(self, x: int, y: int, width: int, height: int, string: str) -> int:
"""Return the height of this text word-wrapped into this rectangle.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
string (str): A Unicode string.
Returns:
int: The number of lines of text once word-wrapped.
"""
string_ = string.encode("utf-8")
return int(lib.TCOD_console_get_height_rect_n(self.console_c, x, y, width, height, len(string_), string_))
def rect(
self,
x: int,
y: int,
width: int,
height: int,
clear: bool,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a the background color on a rect optionally clearing the text.
If `clear` is True the affected tiles are changed to space character.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
clear (bool): If True all text in the affected area will be
removed.
bg_blend (int): Background blending flag.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_rect` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_rect", bg_blend, clear=bool(clear))
lib.TCOD_console_rect(self.console_c, x, y, width, height, clear, bg_blend)
def hline(
self,
x: int,
y: int,
width: int,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a horizontal line on the console.
This always uses ord('─'), the horizontal line character.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): The horizontal length of this line.
bg_blend (int): The background blending flag.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_rect` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_rect", bg_blend)
lib.TCOD_console_hline(self.console_c, x, y, width, bg_blend)
def vline(
self,
x: int,
y: int,
height: int,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a vertical line on the console.
This always uses ord('│'), the vertical line character.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
height (int): The horizontal length of this line.
bg_blend (int): The background blending flag.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_rect` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_rect", bg_blend)
lib.TCOD_console_vline(self.console_c, x, y, height, bg_blend)
def print_frame(
self,
x: int,
y: int,
width: int,
height: int,
string: str = "",
clear: bool = True,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a framed rectangle with optional text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`string` will be printed on the inside of the rectangle, word-wrapped.
If `string` is empty then no title will be drawn.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): The width if the frame.
height (int): The height of the frame.
string (str): A Unicode string to print.
clear (bool): If True all text in the affected area will be
removed.
bg_blend (int): The background blending flag.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_frame` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_frame", bg_blend)
string = _fmt(string) if string else ffi.NULL
_check(lib.TCOD_console_printf_frame(self.console_c, x, y, width, height, clear, bg_blend, string))
def blit(
self,
dest: Console,
dest_x: int = 0,
dest_y: int = 0,
src_x: int = 0,
src_y: int = 0,
width: int = 0,
height: int = 0,
fg_alpha: float = 1.0,
bg_alpha: float = 1.0,
key_color: tuple[int, int, int] | None = None,
) -> None:
"""Blit from this console onto the ``dest`` console.
Args:
dest (Console): The destination console to blit onto.
dest_x (int): Leftmost coordinate of the destination console.
dest_y (int): Topmost coordinate of the destination console.
src_x (int): X coordinate from this console to blit, from the left.
src_y (int): Y coordinate from this console to blit, from the top.
width (int): The width of the region to blit.
If this is 0 the maximum possible width will be used.
height (int): The height of the region to blit.
If this is 0 the maximum possible height will be used.
fg_alpha (float): Foreground color alpha value.
bg_alpha (float): Background color alpha value.
key_color (Optional[Tuple[int, int, int]]):
None, or a (red, green, blue) tuple with values of 0-255.
.. versionchanged:: 4.0
Parameters were rearranged and made optional.
Previously they were:
`(x, y, width, height, dest, dest_x, dest_y, *)`
.. versionchanged:: 11.6
Now supports per-cell alpha transparency.
Use :any:`Console.buffer` to set tile alpha before blit.
"""
# The old syntax is easy to detect and correct.
if hasattr(src_y, "console_c"):
(src_x, src_y, width, height, dest, dest_x, dest_y) = (
dest, # type: ignore
dest_x,
dest_y,
src_x,
src_y, # type: ignore
width,
height,
)
warnings.warn(
"Parameter names have been moved around, see documentation.",
DeprecationWarning,
stacklevel=2,
)
key_color = key_color or self._key_color
if key_color:
key_color = ffi.new("TCOD_color_t*", key_color)
lib.TCOD_console_blit_key_color(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
key_color,
)
else:
lib.TCOD_console_blit(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
)
@deprecate("Pass the key color to Console.blit instead of calling this function.")
def set_key_color(self, color: tuple[int, int, int] | None) -> None:
"""Set a consoles blit transparent color.
`color` is the (r, g, b) color, or None to disable key color.
.. deprecated:: 8.5
Pass the key color to :any:`Console.blit` instead of calling this
function.
"""
self._key_color = color
def __enter__(self) -> Console:
"""Return this console in a managed context.
When the root console is used as a context, the graphical window will
close once the context is left as if :any:`tcod.console_delete` was
called on it.
This is useful for some Python IDE's like IDLE, where the window would
not be closed on its own otherwise.
.. seealso::
:any:`tcod.console_init_root`
"""
if self.console_c != ffi.NULL:
msg = "Only the root console has a context."
raise NotImplementedError(msg)
return self
def close(self) -> None:
"""Close the active window managed by libtcod.
This must only be called on the root console, which is returned from
:any:`tcod.console_init_root`.
.. versionadded:: 11.11
"""
if self.console_c != ffi.NULL:
msg = "Only the root console can be used to close libtcod's window."
raise NotImplementedError(msg)
lib.TCOD_console_delete(self.console_c)
def __exit__(self, *args: Any) -> None:
"""Close the graphical window on exit.
Some tcod functions may have undefined behavior after this point.
"""
self.close()
def __bool__(self) -> bool:
"""Return False if this is the root console.
This mimics libtcodpy behavior.
"""
return bool(self.console_c != ffi.NULL)
def __getstate__(self) -> dict[str, Any]:
state = self.__dict__.copy()
del state["console_c"]
state["_console_data"] = {
"w": self.width,
"h": self.height,
"bkgnd_flag": self.default_bg_blend,
"alignment": self.default_alignment,
"fore": self.default_fg,
"back": self.default_bg,
}
if self.console_c == ffi.NULL:
state["_tiles"] = np.array(self._tiles, copy=True)
return state
def __setstate__(self, state: dict[str, Any]) -> None:
self._key_color = None
if "_tiles" not in state:
tiles: NDArray[Any] = np.ndarray((self.height, self.width), dtype=self.DTYPE)
tiles["ch"] = state["_ch"]
tiles["fg"][..., :3] = state["_fg"]
tiles["fg"][..., 3] = 255
tiles["bg"][..., :3] = state["_bg"]
tiles["bg"][..., 3] = 255
state["_tiles"] = tiles
del state["_ch"]
del state["_fg"]
del state["_bg"]
self.__dict__.update(state)
self._console_data["tiles"] = ffi.from_buffer("struct TCOD_ConsoleTile*", self._tiles)
self._console_data = self.console_c = ffi.new("struct TCOD_Console*", self._console_data)
def __repr__(self) -> str:
"""Return a string representation of this console."""
return "tcod.console.Console(width=%i, height=%i, " "order=%r,buffer=\n%r)" % (
self.width,
self.height,
self._order,
self.tiles,
)
def __str__(self) -> str:
"""Return a simplified representation of this consoles contents."""
return "<%s>" % "\n ".join("".join(chr(c) for c in line) for line in self._tiles["ch"])
def print(
self,
x: int,
y: int,
string: str,
fg: tuple[int, int, int] | None = None,
bg: tuple[int, int, int] | None = None,
bg_blend: int = tcod.constants.BKGND_SET,
alignment: int = tcod.constants.LEFT,
) -> None:
r"""Print a string on a console with manual line breaks.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console.
`string` is a Unicode string which may include color control
characters. Strings which are too long will be truncated until the
next newline character ``"\n"``.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
`alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
.. versionchanged:: 13.0
`x` and `y` are now always used as an absolute position for negative values.
"""
string_ = string.encode("utf-8")
lib.TCOD_console_printn(
self.console_c,
x,
y,
len(string_),
string_,
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
alignment,
)
def print_box(
self,
x: int,
y: int,
width: int,
height: int,
string: str,
fg: tuple[int, int, int] | None = None,
bg: tuple[int, int, int] | None = None,
bg_blend: int = tcod.constants.BKGND_SET,
alignment: int = tcod.constants.LEFT,
) -> int:
"""Print a string constrained to a rectangle and return the height.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console.
`width` and `height` determine the bounds of the rectangle, the text
will automatically be word-wrapped to fit within these bounds.
`string` is a Unicode string which may include color control
characters.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.