/
libtcodpy.py
4852 lines (3876 loc) · 147 KB
/
libtcodpy.py
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
"""This module handles backward compatibility with the ctypes libtcodpy module."""
from __future__ import annotations
import atexit
import sys
import threading
import warnings
from os import PathLike
from pathlib import Path
from typing import Any, Callable, Hashable, Iterable, Iterator, Sequence
import numpy as np
from numpy.typing import NDArray
from typing_extensions import Literal
import tcod.bsp
import tcod.console
import tcod.image
import tcod.los
import tcod.map
import tcod.noise
import tcod.path
import tcod.random
from tcod._internal import (
_bytes,
_CDataWrapper,
_check,
_check_p,
_check_warn,
_console,
_fmt,
_int,
_PropagateException,
_unicode,
_unpack_char_p,
deprecate,
pending_deprecate,
)
from tcod.color import Color
from tcod.constants import * # noqa: F403
from tcod.constants import (
BKGND_ADDA,
BKGND_ALPH,
BKGND_DEFAULT,
BKGND_SET,
FONT_LAYOUT_ASCII_INCOL,
FOV_PERMISSIVE_0,
FOV_RESTRICTIVE,
KEY_RELEASED,
NOISE_DEFAULT,
)
from tcod.loader import ffi, lib
# ruff: noqa: ANN401 PLR0913 # Functions are too deprecated to make changes.
Bsp = tcod.bsp.BSP
NB_FOV_ALGORITHMS = 13
NOISE_DEFAULT_HURST = 0.5
NOISE_DEFAULT_LACUNARITY = 2.0
def FOV_PERMISSIVE(p: int) -> int:
return FOV_PERMISSIVE_0 + p
def BKGND_ALPHA(a: int) -> int:
return BKGND_ALPH | (int(a * 255) << 8)
def BKGND_ADDALPHA(a: int) -> int:
return BKGND_ADDA | (int(a * 255) << 8)
class ConsoleBuffer:
"""Simple console that allows direct (fast) access to cells. Simplifies use of the "fill" functions.
.. deprecated:: 6.0
Console array attributes perform better than this class.
Args:
width (int): Width of the new ConsoleBuffer.
height (int): Height of the new ConsoleBuffer.
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
def __init__(
self,
width: int,
height: int,
back_r: int = 0,
back_g: int = 0,
back_b: int = 0,
fore_r: int = 0,
fore_g: int = 0,
fore_b: int = 0,
char: str = " ",
) -> None:
"""Initialize with given width and height.
Values to fill the buffer are optional, defaults to black with no characters.
"""
warnings.warn(
"Console array attributes perform better than this class.",
DeprecationWarning,
stacklevel=2,
)
self.width = width
self.height = height
self.clear(back_r, back_g, back_b, fore_r, fore_g, fore_b, char)
def clear(
self,
back_r: int = 0,
back_g: int = 0,
back_b: int = 0,
fore_r: int = 0,
fore_g: int = 0,
fore_b: int = 0,
char: str = " ",
) -> None:
"""Clear the console.
Values to fill it with are optional, defaults to black with no characters.
Args:
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
n = self.width * self.height
self.back_r = [back_r] * n
self.back_g = [back_g] * n
self.back_b = [back_b] * n
self.fore_r = [fore_r] * n
self.fore_g = [fore_g] * n
self.fore_b = [fore_b] * n
self.char = [ord(char)] * n
def copy(self) -> ConsoleBuffer:
"""Return a copy of this ConsoleBuffer.
Returns:
ConsoleBuffer: A new ConsoleBuffer copy.
"""
other = ConsoleBuffer(0, 0)
other.width = self.width
other.height = self.height
other.back_r = list(self.back_r) # make explicit copies of all lists
other.back_g = list(self.back_g)
other.back_b = list(self.back_b)
other.fore_r = list(self.fore_r)
other.fore_g = list(self.fore_g)
other.fore_b = list(self.fore_b)
other.char = list(self.char)
return other
def set_fore(self, x: int, y: int, r: int, g: int, b: int, char: str) -> None:
"""Set the character and foreground color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red foreground color, from 0 to 255.
g (int): Green foreground color, from 0 to 255.
b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
i = self.width * y + x
self.fore_r[i] = r
self.fore_g[i] = g
self.fore_b[i] = b
self.char[i] = ord(char)
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:
"""Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, from 0 to 255.
b (int): Blue background color, from 0 to 255.
"""
i = self.width * y + x
self.back_r[i] = r
self.back_g[i] = g
self.back_b[i] = b
def set(
self,
x: int,
y: int,
back_r: int,
back_g: int,
back_b: int,
fore_r: int,
fore_g: int,
fore_b: int,
char: str,
) -> None:
"""Set the background color, foreground color and character of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
i = self.width * y + x
self.back_r[i] = back_r
self.back_g[i] = back_g
self.back_b[i] = back_b
self.fore_r[i] = fore_r
self.fore_g[i] = fore_g
self.fore_b[i] = fore_b
self.char[i] = ord(char)
def blit(
self,
dest: tcod.console.Console,
fill_fore: bool = True,
fill_back: bool = True,
) -> None:
"""Use libtcod's "fill" functions to write the buffer to a console.
Args:
dest (Console): Console object to modify.
fill_fore (bool):
If True, fill the foreground color and characters.
fill_back (bool):
If True, fill the background color.
"""
if not dest:
dest = tcod.console.Console._from_cdata(ffi.NULL)
if dest.width != self.width or dest.height != self.height:
msg = "ConsoleBuffer.blit: Destination console has an incorrect size."
raise ValueError(msg)
if fill_back:
bg = dest.bg.ravel()
bg[0::3] = self.back_r
bg[1::3] = self.back_g
bg[2::3] = self.back_b
if fill_fore:
fg = dest.fg.ravel()
fg[0::3] = self.fore_r
fg[1::3] = self.fore_g
fg[2::3] = self.fore_b
dest.ch.ravel()[:] = self.char
class Dice(_CDataWrapper):
"""A libtcod dice object.
Args:
nb_dices (int): Number of dice.
nb_faces (int): Number of sides on a die.
multiplier (float): Multiplier.
addsub (float): Addition.
.. deprecated:: 2.0
You should make your own dice functions instead of using this class
which is tied to a CData object.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
warnings.warn(
"Using this class is not recommended.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
if self.cdata == ffi.NULL:
self._init(*args, **kwargs)
def _init(
self,
nb_dices: int = 0,
nb_faces: int = 0,
multiplier: float = 0,
addsub: float = 0,
) -> None:
self.cdata = ffi.new("TCOD_dice_t*")
self.nb_dices = nb_dices
self.nb_faces = nb_faces
self.multiplier = multiplier
self.addsub = addsub
@property
def nb_dices(self) -> int:
return self.nb_rolls
@nb_dices.setter
def nb_dices(self, value: int) -> None:
self.nb_rolls = value
def __str__(self) -> str:
add = "+(%s)" % self.addsub if self.addsub != 0 else ""
return "%id%ix%s%s" % (
self.nb_dices,
self.nb_faces,
self.multiplier,
add,
)
def __repr__(self) -> str:
return "{}(nb_dices={!r},nb_faces={!r},multiplier={!r},addsub={!r})".format(
self.__class__.__name__,
self.nb_dices,
self.nb_faces,
self.multiplier,
self.addsub,
)
# reverse lookup table for KEY_X attributes, used by Key.__repr__
_LOOKUP_VK = {value: "KEY_%s" % key[6:] for key, value in lib.__dict__.items() if key.startswith("TCODK")}
class Key(_CDataWrapper):
r"""Key Event instance.
Attributes:
vk (int): TCOD_keycode_t key code
c (int): character if vk == TCODK_CHAR else 0
text (Text): text[TCOD_KEY_TEXT_SIZE];
text if vk == TCODK_TEXT else text[0] == '\0'
pressed (bool): does this correspond to a key press or key release
event?
lalt (bool): True when left alt is held.
lctrl (bool): True when left control is held.
lmeta (bool): True when left meta key is held.
ralt (bool): True when right alt is held.
rctrl (bool): True when right control is held.
rmeta (bool): True when right meta key is held.
shift (bool): True when any shift is held.
.. deprecated:: 9.3
Use events from the :any:`tcod.event` module instead.
"""
_BOOL_ATTRIBUTES = (
"lalt",
"lctrl",
"lmeta",
"ralt",
"rctrl",
"rmeta",
"pressed",
"shift",
)
def __init__(
self,
vk: int = 0,
c: int = 0,
text: str = "",
pressed: bool = False,
lalt: bool = False,
lctrl: bool = False,
lmeta: bool = False,
ralt: bool = False,
rctrl: bool = False,
rmeta: bool = False,
shift: bool = False,
) -> None:
if isinstance(vk, ffi.CData):
self.cdata = vk
return
self.cdata = ffi.new("TCOD_key_t*")
self.vk = vk
self.c = c
self.text = text
self.pressed = pressed
self.lalt = lalt
self.lctrl = lctrl
self.lmeta = lmeta
self.ralt = ralt
self.rctrl = rctrl
self.rmeta = rmeta
self.shift = shift
def __getattr__(self, attr: str) -> Any:
if attr in self._BOOL_ATTRIBUTES:
return bool(getattr(self.cdata, attr))
if attr == "c":
return ord(self.cdata.c)
if attr == "text":
return ffi.string(self.cdata.text).decode()
return super().__getattr__(attr)
def __setattr__(self, attr: str, value: Any) -> None:
if attr == "c":
self.cdata.c = chr(value).encode("latin-1")
elif attr == "text":
self.cdata.text = value.encode()
else:
super().__setattr__(attr, value)
def __repr__(self) -> str:
"""Return a representation of this Key object."""
params = []
params.append(f"pressed={self.pressed!r}, vk=tcod.{_LOOKUP_VK[self.vk]}")
if self.c:
params.append("c=ord(%r)" % chr(self.c))
if self.text:
params.append("text=%r" % self.text)
for attr in [
"shift",
"lalt",
"lctrl",
"lmeta",
"ralt",
"rctrl",
"rmeta",
]:
if getattr(self, attr):
params.append(f"{attr}={getattr(self, attr)!r}")
return "tcod.Key(%s)" % ", ".join(params)
@property
def key_p(self) -> Any:
return self.cdata
class Mouse(_CDataWrapper):
"""Mouse event instance.
Attributes:
x (int): Absolute mouse position at pixel x.
y (int):
dx (int): Movement since last update in pixels.
dy (int):
cx (int): Cell coordinates in the root console.
cy (int):
dcx (int): Movement since last update in console cells.
dcy (int):
lbutton (bool): Left button status.
rbutton (bool): Right button status.
mbutton (bool): Middle button status.
lbutton_pressed (bool): Left button pressed event.
rbutton_pressed (bool): Right button pressed event.
mbutton_pressed (bool): Middle button pressed event.
wheel_up (bool): Wheel up event.
wheel_down (bool): Wheel down event.
.. deprecated:: 9.3
Use events from the :any:`tcod.event` module instead.
"""
def __init__(
self,
x: int = 0,
y: int = 0,
dx: int = 0,
dy: int = 0,
cx: int = 0,
cy: int = 0,
dcx: int = 0,
dcy: int = 0,
**kwargs: Any,
) -> None:
if isinstance(x, ffi.CData):
self.cdata = x
return
self.cdata = ffi.new("TCOD_mouse_t*")
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.cx = cx
self.cy = cy
self.dcx = dcx
self.dcy = dcy
for attr, value in kwargs.items():
setattr(self, attr, value)
def __repr__(self) -> str:
"""Return a representation of this Mouse object."""
params = []
for attr in ["x", "y", "dx", "dy", "cx", "cy", "dcx", "dcy"]:
if getattr(self, attr) == 0:
continue
params.append(f"{attr}={getattr(self, attr)!r}")
for attr in [
"lbutton",
"rbutton",
"mbutton",
"lbutton_pressed",
"rbutton_pressed",
"mbutton_pressed",
"wheel_up",
"wheel_down",
]:
if getattr(self, attr):
params.append(f"{attr}={getattr(self, attr)!r}")
return "tcod.Mouse(%s)" % ", ".join(params)
@property
def mouse_p(self) -> Any:
return self.cdata
@deprecate("Call tcod.bsp.BSP(x, y, width, height) instead.", FutureWarning)
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:
"""Create a new BSP instance with the given rectangle.
Args:
x (int): Rectangle left coordinate.
y (int): Rectangle top coordinate.
w (int): Rectangle width.
h (int): Rectangle height.
Returns:
BSP: A new BSP instance.
.. deprecated:: 2.0
Call the :any:`BSP` class instead.
"""
return Bsp(x, y, w, h)
@deprecate("Call node.split_once instead.", FutureWarning)
def bsp_split_once(node: tcod.bsp.BSP, horizontal: bool, position: int) -> None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.split_once` instead.
"""
node.split_once(horizontal, position)
@deprecate("Call node.split_recursive instead.", FutureWarning)
def bsp_split_recursive(
node: tcod.bsp.BSP,
randomizer: tcod.random.Random | None,
nb: int,
minHSize: int,
minVSize: int,
maxHRatio: float,
maxVRatio: float,
) -> None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.split_recursive` instead.
"""
node.split_recursive(nb, minHSize, minVSize, maxHRatio, maxVRatio, randomizer)
@deprecate("Assign values via attribute instead.", FutureWarning)
def bsp_resize(node: tcod.bsp.BSP, x: int, y: int, w: int, h: int) -> None:
"""Deprecated function.
.. deprecated:: 2.0
Assign directly to :any:`BSP` attributes instead.
"""
node.x = x
node.y = y
node.width = w
node.height = h
@deprecate("Access children with 'node.children' instead.")
def bsp_left(node: tcod.bsp.BSP) -> tcod.bsp.BSP | None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.children` instead.
"""
return None if not node.children else node.children[0]
@deprecate("Access children with 'node.children' instead.")
def bsp_right(node: tcod.bsp.BSP) -> tcod.bsp.BSP | None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.children` instead.
"""
return None if not node.children else node.children[1]
@deprecate("Get the parent with 'node.parent' instead.", FutureWarning)
def bsp_father(node: tcod.bsp.BSP) -> tcod.bsp.BSP | None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.parent` instead.
"""
return node.parent
@deprecate("Check for children with 'bool(node.children)' instead.", FutureWarning)
def bsp_is_leaf(node: tcod.bsp.BSP) -> bool:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.children` instead.
"""
return not node.children
@deprecate("Use 'node.contains' instead.", FutureWarning)
def bsp_contains(node: tcod.bsp.BSP, cx: int, cy: int) -> bool:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.contains` instead.
"""
return node.contains(cx, cy)
@deprecate("Use 'node.find_node' instead.", FutureWarning)
def bsp_find_node(node: tcod.bsp.BSP, cx: int, cy: int) -> tcod.bsp.BSP | None:
"""Deprecated function.
.. deprecated:: 2.0
Use :any:`BSP.find_node` instead.
"""
return node.find_node(cx, cy)
def _bsp_traverse(
node_iter: Iterable[tcod.bsp.BSP],
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any,
) -> None:
"""Pack callback into a handle for use with the callback _pycall_bsp_callback."""
for node in node_iter:
callback(node, userData)
@deprecate("Iterate over nodes using 'for n in node.pre_order():' instead.")
def bsp_traverse_pre_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.pre_order` instead.
"""
_bsp_traverse(node.pre_order(), callback, userData)
@deprecate("Iterate over nodes using 'for n in node.in_order():' instead.")
def bsp_traverse_in_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.in_order` instead.
"""
_bsp_traverse(node.in_order(), callback, userData)
@deprecate("Iterate over nodes using 'for n in node.post_order():' instead.")
def bsp_traverse_post_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.post_order` instead.
"""
_bsp_traverse(node.post_order(), callback, userData)
@deprecate("Iterate over nodes using 'for n in node.level_order():' instead.")
def bsp_traverse_level_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.level_order` instead.
"""
_bsp_traverse(node.level_order(), callback, userData)
@deprecate("Iterate over nodes using " "'for n in node.inverted_level_order():' instead.")
def bsp_traverse_inverted_level_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.inverted_level_order` instead.
"""
_bsp_traverse(node.inverted_level_order(), callback, userData)
@deprecate("Delete bsp children using 'node.children = ()' instead.")
def bsp_remove_sons(node: tcod.bsp.BSP) -> None:
"""Delete all children of a given node. Not recommended.
.. note::
This function will add unnecessary complexity to your code.
Don't use it.
.. deprecated:: 2.0
BSP deletion is automatic.
"""
node.children = ()
@deprecate("libtcod objects are deleted automatically.", FutureWarning)
def bsp_delete(node: tcod.bsp.BSP) -> None:
"""Exists for backward compatibility. Does nothing.
BSP's created by this library are automatically garbage collected once
there are no references to the tree.
This function exists for backwards compatibility.
.. deprecated:: 2.0
BSP deletion is automatic.
"""
@pending_deprecate()
def color_lerp(c1: tuple[int, int, int], c2: tuple[int, int, int], a: float) -> Color:
"""Return the linear interpolation between two colors.
``a`` is the interpolation value, with 0 returning ``c1``,
1 returning ``c2``, and 0.5 returning a color halfway between both.
Args:
c1 (Union[Tuple[int, int, int], Sequence[int]]):
The first color. At a=0.
c2 (Union[Tuple[int, int, int], Sequence[int]]):
The second color. At a=1.
a (float): The interpolation value,
Returns:
Color: The interpolated Color.
"""
return Color._new_from_cdata(lib.TCOD_color_lerp(c1, c2, a))
@pending_deprecate()
def color_set_hsv(c: Color, h: float, s: float, v: float) -> None:
"""Set a color using: hue, saturation, and value parameters.
Does not return a new Color. ``c`` is modified in-place.
Args:
c (Union[Color, List[Any]]): A Color instance, or a list of any kind.
h (float): Hue, from 0 to 360.
s (float): Saturation, from 0 to 1.
v (float): Value, from 0 to 1.
"""
new_color = ffi.new("TCOD_color_t*")
lib.TCOD_color_set_HSV(new_color, h, s, v)
c[:] = new_color.r, new_color.g, new_color.b
@pending_deprecate()
def color_get_hsv(c: tuple[int, int, int]) -> tuple[float, float, float]:
"""Return the (hue, saturation, value) of a color.
Args:
c (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
Returns:
Tuple[float, float, float]:
A tuple with (hue, saturation, value) values, from 0 to 1.
"""
hsv = ffi.new("float [3]")
lib.TCOD_color_get_HSV(c, hsv, hsv + 1, hsv + 2)
return hsv[0], hsv[1], hsv[2]
@pending_deprecate()
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None:
"""Scale a color's saturation and value.
Does not return a new Color. ``c`` is modified in-place.
Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.
Use 1 to keep current saturation.
vcoef (float): Value multiplier, from 0 to 1.
Use 1 to keep current value.
"""
color_p = ffi.new("TCOD_color_t*")
color_p.r, color_p.g, color_p.b = c.r, c.g, c.b
lib.TCOD_color_scale_HSV(color_p, scoef, vcoef)
c[:] = color_p.r, color_p.g, color_p.b
@pending_deprecate()
def color_gen_map(colors: Iterable[tuple[int, int, int]], indexes: Iterable[int]) -> list[Color]:
"""Return a smoothly defined scale of colors.
If ``indexes`` is [0, 3, 9] for example, the first color from ``colors``
will be returned at 0, the 2nd will be at 3, and the 3rd will be at 9.
All in-betweens will be filled with a gradient.
Args:
colors (Iterable[Union[Tuple[int, int, int], Sequence[int]]]):
Array of colors to be sampled.
indexes (Iterable[int]): A list of indexes.
Returns:
List[Color]: A list of Color instances.
Example:
>>> tcod.color_gen_map([(0, 0, 0), (255, 128, 0)], [0, 5])
[Color(0, 0, 0), Color(51, 25, 0), Color(102, 51, 0), \
Color(153, 76, 0), Color(204, 102, 0), Color(255, 128, 0)]
"""
c_colors = ffi.new("TCOD_color_t[]", colors)
c_indexes = ffi.new("int[]", indexes)
c_out = ffi.new("TCOD_color_t[]", max(indexes) + 1)
lib.TCOD_color_gen_map(c_out, len(c_colors), c_colors, c_indexes)
return [Color._new_from_cdata(cdata) for cdata in c_out]
@deprecate(
"""console_init_root is deprecated in favor of using libtcod contexts.
See the Getting Started documentation:
https://python-tcod.readthedocs.io/en/latest/tcod/getting-started.html"""
)
def console_init_root(
w: int,
h: int,
title: str | None = None,
fullscreen: bool = False,
renderer: int | None = None,
order: Literal["C", "F"] = "C",
vsync: bool | None = None,
) -> tcod.console.Console:
"""Set up the primary display and return the root console.
`w` and `h` are the columns and rows of the new window (in tiles.)
`title` is an optional string to display on the windows title bar.
`fullscreen` determines if the window will start in fullscreen. Fullscreen
mode is unreliable unless the renderer is set to `tcod.RENDERER_SDL2` or
`tcod.RENDERER_OPENGL2`.
`renderer` is the rendering back-end that libtcod will use.
If you don't know which to pick, then use `tcod.RENDERER_SDL2`.
Options are:
* `tcod.RENDERER_SDL`:
Forces the SDL2 renderer into software mode.
* `tcod.RENDERER_OPENGL`:
An OpenGL 1 implementation.
* `tcod.RENDERER_GLSL`:
A deprecated SDL2/OpenGL2 renderer.
* `tcod.RENDERER_SDL2`:
The recommended SDL2 renderer. Rendering is decided by SDL2 and can be
changed by using an SDL2 hint.
* `tcod.RENDERER_OPENGL2`:
An SDL2/OPENGL2 renderer. Usually faster than regular SDL2.
Requires OpenGL 2.0 Core.
`order` will affect how the array attributes of the returned root console
are indexed. `order='C'` is the default, but `order='F'` is recommended.
If `vsync` is True then the frame-rate will be synchronized to the monitors
vertical refresh rate. This prevents screen tearing and avoids wasting
computing power on overdraw. If `vsync` is False then the frame-rate will
be uncapped. The default is False but will change to True in the future.
This option only works with the SDL2 or OPENGL2 renderers, any other
renderer will always have `vsync` disabled.
The returned object is the root console. You don't need to use this object
but you should at least close it when you're done with the libtcod window.
You can do this by calling :any:`Console.close` or by using this function
in a context, like in the following example:
.. code-block:: python
with tcod.console_init_root(80, 50, vsync=True) as root_console:
... # Put your game loop here.
... # Window closes at the end of the above block.
.. versionchanged:: 4.3
Added `order` parameter.
`title` parameter is now optional.
.. versionchanged:: 8.0
The default `renderer` is now automatic instead of always being
`RENDERER_SDL`.
.. versionchanged:: 10.1
Added the `vsync` parameter.
.. deprecated:: 11.13
Use :any:`tcod.context` for window management.
See :ref:`getting-started` for more info.
"""
if title is None:
# Use the scripts filename as the title.
title = Path(sys.argv[0]).name
if renderer is None:
renderer = tcod.constants.RENDERER_SDL2
elif renderer == tcod.constants.RENDERER_GLSL:
warnings.warn(
"The GLSL renderer is deprecated.",
DeprecationWarning,
stacklevel=2,
)
if vsync is None:
vsync = False
warnings.warn(
"vsync defaults to False, but the default will change to True in "
"the future. Provide a value for vsync to suppress this warning.",
DeprecationWarning,
stacklevel=2,
)
_check_warn(lib.TCOD_console_init_root_(w, h, _bytes(title), fullscreen, renderer, vsync))
console = tcod.console.Console._get_root(order)
console.clear()
return console
@deprecate(
"""console_set_custom_font is deprecated in favor of using contexts.
See the Getting Started documentation:
https://python-tcod.readthedocs.io/en/latest/tcod/getting-started.html"""
)
def console_set_custom_font(
fontFile: str | PathLike[str],
flags: int = FONT_LAYOUT_ASCII_INCOL,
nb_char_horiz: int = 0,
nb_char_vertic: int = 0,
) -> None:
"""Load the custom font file at `fontFile`.
Call this before function before calling :any:`tcod.console_init_root`.
Flags can be a mix of the following:
* tcod.FONT_LAYOUT_ASCII_INCOL:
Decode tileset raw in column-major order.
* tcod.FONT_LAYOUT_ASCII_INROW:
Decode tileset raw in row-major order.
* tcod.FONT_TYPE_GREYSCALE:
Force tileset to be read as greyscale.
* tcod.FONT_TYPE_GRAYSCALE
* tcod.FONT_LAYOUT_TCOD:
Unique layout used by libtcod.
* tcod.FONT_LAYOUT_CP437:
Decode a row-major Code Page 437 tileset into Unicode.
`nb_char_horiz` and `nb_char_vertic` are the columns and rows of the font
file respectfully.
.. deprecated:: 11.13
Load fonts using :any:`tcod.tileset.load_tilesheet` instead.
See :ref:`getting-started` for more info.
.. versionchanged:: 16.0
Added PathLike support. `fontFile` no longer takes bytes.
"""
fontFile = Path(fontFile).resolve(strict=True)
_check(lib.TCOD_console_set_custom_font(bytes(fontFile), flags, nb_char_horiz, nb_char_vertic))
@deprecate("Check `con.width` instead.")
def console_get_width(con: tcod.console.Console) -> int:
"""Return the width of a console.
Args:
con (Console): Any Console instance.