-
Notifications
You must be signed in to change notification settings - Fork 0
/
samples_tcod.py
executable file
·1614 lines (1451 loc) · 53.9 KB
/
samples_tcod.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
#!/usr/bin/env python3
"""
This code demonstrates various usages of python-tcod.
"""
# To the extent possible under law, the libtcod maintainers have waived all
# copyright and related or neighboring rights to these samples.
# https://creativecommons.org/publicdomain/zero/1.0/
import os
import copy
import math
import random
import time
import numpy as np
import tcod
import tcod.event
SAMPLE_SCREEN_WIDTH = 46
SAMPLE_SCREEN_HEIGHT = 20
SAMPLE_SCREEN_X = 20
SAMPLE_SCREEN_Y = 10
FONT = "data/fonts/consolas10x10_gs_tc.png"
root_console = None
sample_console = tcod.console.Console(
SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT, order="F"
)
class Sample(tcod.event.EventDispatch):
def __init__(self, name: str = ""):
self.name = name
def on_enter(self):
pass
def on_draw(self):
pass
def ev_keydown(self, event: tcod.event.KeyDown):
global cur_sample
if event.sym == tcod.event.K_DOWN:
cur_sample = (cur_sample + 1) % len(SAMPLES)
SAMPLES[cur_sample].on_enter()
draw_samples_menu()
elif event.sym == tcod.event.K_UP:
cur_sample = (cur_sample - 1) % len(SAMPLES)
SAMPLES[cur_sample].on_enter()
draw_samples_menu()
elif (
event.sym == tcod.event.K_RETURN
and event.mod & tcod.event.KMOD_LALT
):
tcod.console_set_fullscreen(not tcod.console_is_fullscreen())
elif event.sym == tcod.event.K_PRINTSCREEN or event.sym == ord("p"):
print("screenshot")
if event.mod & tcod.event.KMOD_LALT:
tcod.console_save_apf(None, "samples.apf")
print("apf")
else:
tcod.sys_save_screenshot()
print("png")
elif event.sym == tcod.event.K_ESCAPE:
raise SystemExit()
elif event.sym in RENDERER_KEYS:
tcod.sys_set_renderer(RENDERER_KEYS[event.sym])
draw_renderer_menu()
def ev_quit(self, event: tcod.event.Quit):
raise SystemExit()
class TrueColorSample(Sample):
def __init__(self):
self.name = "True colors"
# corner colors
self.colors = np.array(
[(50, 40, 150), (240, 85, 5), (50, 35, 240), (10, 200, 130)],
dtype=np.int16,
)
# color shift direction
self.slide_dir = np.array(
[[1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1]], dtype=np.int16
)
# corner indexes
self.corners = np.array([0, 1, 2, 3])
# sample screen interpolation mesh-grid
self.interp_x, self.interp_y = np.mgrid[
0 : 1 : SAMPLE_SCREEN_WIDTH * 1j, 0 : 1 : SAMPLE_SCREEN_HEIGHT * 1j
]
def on_enter(self):
tcod.sys_set_fps(0)
def on_draw(self):
self.slide_corner_colors()
self.interpolate_corner_colors()
self.darken_background_characters()
self.randomize_sample_conole()
self.print_banner()
def slide_corner_colors(self):
# pick random RGB channels for each corner
rand_channels = np.random.randint(low=0, high=3, size=4)
# shift picked color channels in the direction of slide_dir
self.colors[self.corners, rand_channels] += (
self.slide_dir[self.corners, rand_channels] * 5
)
# reverse slide_dir values when limits are reached
self.slide_dir[self.colors[:] == 255] = -1
self.slide_dir[self.colors[:] == 0] = 1
def interpolate_corner_colors(self):
# interpolate corner colors across the sample console
for i in range(3): # for each color channel
left = (
self.colors[2, i] - self.colors[0, i]
) * self.interp_y + self.colors[0, i]
right = (
self.colors[3, i] - self.colors[1, i]
) * self.interp_y + self.colors[1, i]
sample_console.bg[:, :, i] = (right - left) * self.interp_x + left
def darken_background_characters(self):
# darken background characters
sample_console.fg[:] = sample_console.bg[:]
sample_console.fg[:] //= 2
def randomize_sample_conole(self):
# randomize sample console characters
sample_console.ch[:] = np.random.randint(
low=ord("a"),
high=ord("z") + 1,
size=sample_console.ch.size,
dtype=np.intc,
).reshape(sample_console.ch.shape)
def print_banner(self):
# print text on top of samples
sample_console.print_box(
x=1,
y=5,
width=sample_console.width - 2,
height=sample_console.height - 1,
string="The Doryen library uses 24 bits colors, for both "
"background and foreground.",
fg=tcod.white,
bg=tcod.grey,
bg_blend=tcod.BKGND_MULTIPLY,
alignment=tcod.CENTER,
)
class OffscreenConsoleSample(Sample):
def __init__(self):
self.name = "Offscreen console"
self.secondary = tcod.console.Console(
sample_console.width // 2, sample_console.height // 2
)
self.screenshot = tcod.console.Console(
sample_console.width, sample_console.height
)
self.counter = 0
self.x = 0
self.y = 0
self.xdir = 1
self.ydir = 1
self.secondary.draw_frame(
0,
0,
sample_console.width // 2,
sample_console.height // 2,
"Offscreen console",
False,
fg=tcod.white,
bg=tcod.black,
)
self.secondary.print_box(
1,
2,
sample_console.width // 2 - 2,
sample_console.height // 2,
"You can render to an offscreen console and blit in on another "
"one, simulating alpha transparency.",
fg=tcod.white,
bg=None,
alignment=tcod.CENTER,
)
def on_enter(self):
self.counter = time.perf_counter()
tcod.sys_set_fps(0)
# get a "screenshot" of the current sample screen
sample_console.blit(dest=self.screenshot)
def on_draw(self):
if time.perf_counter() - self.counter >= 1:
self.counter = time.perf_counter()
self.x += self.xdir
self.y += self.ydir
if self.x == sample_console.width / 2 + 5:
self.xdir = -1
elif self.x == -5:
self.xdir = 1
if self.y == sample_console.height / 2 + 5:
self.ydir = -1
elif self.y == -5:
self.ydir = 1
self.screenshot.blit(sample_console)
self.secondary.blit(
sample_console,
self.x,
self.y,
0,
0,
sample_console.width // 2,
sample_console.height // 2,
1.0,
0.75,
)
class LineDrawingSample(Sample):
FLAG_NAMES = [
"BKGND_NONE",
"BKGND_SET",
"BKGND_MULTIPLY",
"BKGND_LIGHTEN",
"BKGND_DARKEN",
"BKGND_SCREEN",
"BKGND_COLOR_DODGE",
"BKGND_COLOR_BURN",
"BKGND_ADD",
"BKGND_ADDALPHA",
"BKGND_BURN",
"BKGND_OVERLAY",
"BKGND_ALPHA",
]
def __init__(self):
self.name = "Line drawing"
self.mk_flag = tcod.BKGND_SET
self.bk_flag = tcod.BKGND_SET
self.bk = tcod.console.Console(
sample_console.width, sample_console.height, order="F"
)
# initialize the colored background
self.bk.bg[:, :, 0] = np.linspace(0, 255, self.bk.width)[:, np.newaxis]
self.bk.bg[:, :, 2] = np.linspace(0, 255, self.bk.height)
self.bk.bg[:, :, 1] = (
self.bk.bg[:, :, 0].astype(int) + self.bk.bg[:, :, 2]
) / 2
self.bk.ch[:] = ord(" ")
def ev_keydown(self, event: tcod.event.KeyDown):
if event.sym in (tcod.event.K_RETURN, tcod.event.K_KP_ENTER):
self.bk_flag += 1
if (self.bk_flag & 0xFF) > tcod.BKGND_ALPH:
self.bk_flag = tcod.BKGND_NONE
else:
super().ev_keydown(event)
def on_enter(self):
tcod.sys_set_fps(0)
def on_draw(self):
alpha = 0.0
if (self.bk_flag & 0xFF) == tcod.BKGND_ALPH:
# for the alpha mode, update alpha every frame
alpha = (1.0 + math.cos(time.time() * 2)) / 2.0
self.bk_flag = tcod.BKGND_ALPHA(alpha)
elif (self.bk_flag & 0xFF) == tcod.BKGND_ADDA:
# for the add alpha mode, update alpha every frame
alpha = (1.0 + math.cos(time.time() * 2)) / 2.0
self.bk_flag = tcod.BKGND_ADDALPHA(alpha)
self.bk.blit(sample_console)
recty = int(
(sample_console.height - 2) * ((1.0 + math.cos(time.time())) / 2.0)
)
for x in range(sample_console.width):
col = [x * 255 // sample_console.width] * 3
tcod.console_set_char_background(
sample_console, x, recty, col, self.bk_flag
)
tcod.console_set_char_background(
sample_console, x, recty + 1, col, self.bk_flag
)
tcod.console_set_char_background(
sample_console, x, recty + 2, col, self.bk_flag
)
angle = time.time() * 2.0
cos_angle = math.cos(angle)
sin_angle = math.sin(angle)
xo = int(sample_console.width // 2 * (1 + cos_angle))
yo = int(
sample_console.height // 2 + sin_angle * sample_console.width // 2
)
xd = int(sample_console.width // 2 * (1 - cos_angle))
yd = int(
sample_console.height // 2 - sin_angle * sample_console.width // 2
)
# draw the line
# in python the easiest way is to use the line iterator
for x, y in tcod.line_iter(xo, yo, xd, yd):
if (
0 <= x < sample_console.width
and 0 <= y < sample_console.height
):
tcod.console_set_char_background(
sample_console, x, y, tcod.light_blue, self.bk_flag
)
sample_console.print(
2,
2,
"%s (ENTER to change)" % self.FLAG_NAMES[self.bk_flag & 0xFF],
fg=tcod.white,
bg=None,
)
class NoiseSample(Sample):
NOISE_OPTIONS = [ # [name, algorithm, implementation],
["perlin noise", tcod.NOISE_PERLIN, tcod.noise.SIMPLE],
["simplex noise", tcod.NOISE_SIMPLEX, tcod.noise.SIMPLE],
["wavelet noise", tcod.NOISE_WAVELET, tcod.noise.SIMPLE],
["perlin fbm", tcod.NOISE_PERLIN, tcod.noise.FBM],
["perlin turbulence", tcod.NOISE_PERLIN, tcod.noise.TURBULENCE],
["simplex fbm", tcod.NOISE_SIMPLEX, tcod.noise.FBM],
["simplex turbulence", tcod.NOISE_SIMPLEX, tcod.noise.TURBULENCE],
["wavelet fbm", tcod.NOISE_WAVELET, tcod.noise.FBM],
["wavelet turbulence", tcod.NOISE_WAVELET, tcod.noise.TURBULENCE],
]
def __init__(self):
self.name = "Noise"
self.func = 0
self.dx = 0.0
self.dy = 0.0
self.octaves = 4.0
self.zoom = 3.0
self.hurst = tcod.NOISE_DEFAULT_HURST
self.lacunarity = tcod.NOISE_DEFAULT_LACUNARITY
self.noise = self.get_noise()
self.img = tcod.image_new(
SAMPLE_SCREEN_WIDTH * 2, SAMPLE_SCREEN_HEIGHT * 2
)
@property
def algorithm(self):
return self.NOISE_OPTIONS[self.func][1]
@property
def implementation(self):
return self.NOISE_OPTIONS[self.func][2]
def get_noise(self):
return tcod.noise.Noise(
2,
self.algorithm,
self.implementation,
self.hurst,
self.lacunarity,
self.octaves,
seed=None,
)
def on_enter(self):
tcod.sys_set_fps(0)
def on_draw(self):
self.dx = time.perf_counter() * 0.25
self.dy = time.perf_counter() * 0.25
for y in range(2 * sample_console.height):
for x in range(2 * sample_console.width):
f = [
self.zoom * x / (2 * sample_console.width) + self.dx,
self.zoom * y / (2 * sample_console.height) + self.dy,
]
value = self.noise.get_point(*f)
c = int((value + 1.0) / 2.0 * 255)
c = max(0, min(c, 255))
self.img.put_pixel(x, y, (c // 2, c // 2, c))
rectw = 24
recth = 13
if self.implementation == tcod.noise.SIMPLE:
recth = 10
self.img.blit_2x(sample_console, 0, 0)
sample_console.draw_rect(
2,
2,
rectw,
recth,
ch=0,
fg=None,
bg=tcod.grey,
bg_blend=tcod.BKGND_MULTIPLY,
)
sample_console.fg[2 : 2 + rectw, 2 : 2 + recth] = (
sample_console.fg[2 : 2 + rectw, 2 : 2 + recth] * tcod.grey / 255
)
for curfunc in range(len(self.NOISE_OPTIONS)):
text = "%i : %s" % (curfunc + 1, self.NOISE_OPTIONS[curfunc][0])
if curfunc == self.func:
sample_console.print(
2, 2 + curfunc, text, fg=tcod.white, bg=tcod.light_blue
)
else:
sample_console.print(
2, 2 + curfunc, text, fg=tcod.grey, bg=None
)
sample_console.print(
2, 11, "Y/H : zoom (%2.1f)" % self.zoom, fg=tcod.white, bg=None
)
if self.implementation != tcod.noise.SIMPLE:
sample_console.print(
2,
12,
"E/D : hurst (%2.1f)" % self.hurst,
fg=tcod.white,
bg=None,
)
sample_console.print(
2,
13,
"R/F : lacunarity (%2.1f)" % self.lacunarity,
fg=tcod.white,
bg=None,
)
sample_console.print(
2,
14,
"T/G : octaves (%2.1f)" % self.octaves,
fg=tcod.white,
bg=None,
)
def ev_keydown(self, event: tcod.event.KeyDown):
if ord("9") >= event.sym >= ord("1"):
self.func = event.sym - ord("1")
self.noise = self.get_noise()
elif event.sym == ord("e"):
self.hurst += 0.1
self.noise = self.get_noise()
elif event.sym == ord("d"):
self.hurst -= 0.1
self.noise = self.get_noise()
elif event.sym == ord("r"):
self.lacunarity += 0.5
self.noise = self.get_noise()
elif event.sym == ord("f"):
self.lacunarity -= 0.5
self.noise = self.get_noise()
elif event.sym == ord("t"):
self.octaves += 0.5
self.noise.octaves = self.octaves
elif event.sym == ord("g"):
self.octaves -= 0.5
self.noise.octaves = self.octaves
elif event.sym == ord("y"):
self.zoom += 0.2
elif event.sym == ord("h"):
self.zoom -= 0.2
else:
super().ev_keydown(event)
#############################################
# field of view sample
#############################################
DARK_WALL = (0, 0, 100)
LIGHT_WALL = (130, 110, 50)
DARK_GROUND = (50, 50, 150)
LIGHT_GROUND = (200, 180, 50)
SAMPLE_MAP = [
"##############################################",
"####################### #################",
"##################### # ###############",
"###################### ### ###########",
"################## ##### ####",
"################ ######## ###### ####",
"############### #################### ####",
"################ ###### ##",
"######## ####### ###### # # # ##",
"######## ###### ### ##",
"######## ##",
"#### ###### ### # # # ##",
"#### ### ########## #### ##",
"#### ### ########## ###########=##########",
"#### ################## ##### #####",
"#### ### #### ##### #####",
"#### # #### #####",
"######## # #### ##### #####",
"######## ##### ####################",
"##############################################",
]
SAMPLE_MAP = np.array([list(line) for line in SAMPLE_MAP]).transpose()
FOV_ALGO_NAMES = [
"BASIC ",
"DIAMOND ",
"SHADOW ",
"PERMISSIVE0",
"PERMISSIVE1",
"PERMISSIVE2",
"PERMISSIVE3",
"PERMISSIVE4",
"PERMISSIVE5",
"PERMISSIVE6",
"PERMISSIVE7",
"PERMISSIVE8",
"RESTRICTIVE",
]
TORCH_RADIUS = 10
SQUARED_TORCH_RADIUS = TORCH_RADIUS * TORCH_RADIUS
class FOVSample(Sample):
def __init__(self):
self.name = "Field of view"
self.px = 20
self.py = 10
self.recompute = True
self.torch = False
self.map = None
self.noise = None
self.torchx = 0.0
self.light_walls = True
self.algo_num = 0
# 1d noise for the torch flickering
self.noise = tcod.noise_new(1, 1.0, 1.0)
self.map = tcod.map.Map(
SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT, order="F"
)
self.map.walkable[:] = SAMPLE_MAP[:] == " "
self.map.transparent[:] = self.map.walkable[:] | (SAMPLE_MAP == "=")
self.light_map_bg = np.full(
SAMPLE_MAP.shape + (3,), LIGHT_GROUND, dtype=np.uint8
)
self.light_map_bg[SAMPLE_MAP[:] == "#"] = LIGHT_WALL
self.dark_map_bg = np.full(
SAMPLE_MAP.shape + (3,), DARK_GROUND, dtype=np.uint8
)
self.dark_map_bg[SAMPLE_MAP[:] == "#"] = DARK_WALL
def draw_ui(self):
sample_console.print(
1,
1,
"IJKL : move around\n"
"T : torch fx %s\n"
"W : light walls %s\n"
"+-: algo %s"
% (
"on " if self.torch else "off",
"on " if self.light_walls else "off",
FOV_ALGO_NAMES[self.algo_num],
),
fg=tcod.white,
bg=None,
)
def on_enter(self):
tcod.sys_set_fps(60)
# we draw the foreground only the first time.
# during the player movement, only the @ is redrawn.
# the rest impacts only the background color
# draw the help text & player @
sample_console.clear()
self.draw_ui()
tcod.console_put_char(
sample_console, self.px, self.py, "@", tcod.BKGND_NONE
)
# draw windows
sample_console.ch[np.where(SAMPLE_MAP == "=")] = tcod.CHAR_DHLINE
sample_console.fg[np.where(SAMPLE_MAP == "=")] = tcod.black
def on_draw(self):
dx = 0.0
dy = 0.0
di = 0.0
if self.recompute:
self.recompute = False
self.map.compute_fov(
self.px,
self.py,
TORCH_RADIUS if self.torch else 0,
self.light_walls,
self.algo_num,
)
sample_console.bg[:] = self.dark_map_bg[:]
if self.torch:
# slightly change the perlin noise parameter
self.torchx += 0.1
# randomize the light position between -1.5 and 1.5
tdx = [self.torchx + 20.0]
dx = tcod.noise_get(self.noise, tdx, tcod.NOISE_SIMPLEX) * 1.5
tdx[0] += 30.0
dy = tcod.noise_get(self.noise, tdx, tcod.NOISE_SIMPLEX) * 1.5
di = 0.2 * tcod.noise_get(
self.noise, [self.torchx], tcod.NOISE_SIMPLEX
)
# where_fov = np.where(self.map.fov[:])
mgrid = np.mgrid[:SAMPLE_SCREEN_WIDTH, :SAMPLE_SCREEN_HEIGHT]
# get squared distance
light = (mgrid[0] - self.px + dx) ** 2 + (
mgrid[1] - self.py + dy
) ** 2
light = light.astype(np.float16)
visible = (light < SQUARED_TORCH_RADIUS) & self.map.fov[:]
light[...] = SQUARED_TORCH_RADIUS - light
light[...] /= SQUARED_TORCH_RADIUS
light[...] += di
light[...] = light.clip(0, 1)
light[~visible] = 0
sample_console.bg[...] = (
self.light_map_bg.astype(np.float16) - self.dark_map_bg
) * light[..., np.newaxis] + self.dark_map_bg
else:
where_fov = np.where(self.map.fov[:])
sample_console.bg[where_fov] = self.light_map_bg[where_fov]
def ev_keydown(self, event: tcod.event.KeyDown):
MOVE_KEYS = {
ord("i"): (0, -1),
ord("j"): (-1, 0),
ord("k"): (0, 1),
ord("l"): (1, 0),
}
FOV_SELECT_KEYS = {ord("-"): -1, ord("="): 1}
if event.sym in MOVE_KEYS:
x, y = MOVE_KEYS[event.sym]
if SAMPLE_MAP[self.px + x, self.py + y] == " ":
tcod.console_put_char(
sample_console, self.px, self.py, " ", tcod.BKGND_NONE
)
self.px += x
self.py += y
tcod.console_put_char(
sample_console, self.px, self.py, "@", tcod.BKGND_NONE
)
self.recompute = True
elif event.sym == ord("t"):
self.torch = not self.torch
self.draw_ui()
self.recompute = True
elif event.sym == ord("w"):
self.light_walls = not self.light_walls
self.draw_ui()
self.recompute = True
elif event.sym in FOV_SELECT_KEYS:
self.algo_num += FOV_SELECT_KEYS[event.sym]
self.algo_num %= tcod.NB_FOV_ALGORITHMS
self.draw_ui()
self.recompute = True
else:
super().ev_keydown(event)
class PathfindingSample(Sample):
def __init__(self):
self.name = "Path finding"
self.px = 20
self.py = 10
self.dx = 24
self.dy = 1
self.map = None
self.path = None
self.dijk_dist = 0.0
self.using_astar = True
self.dijk = None
self.recalculate = False
self.busy = 0.0
self.oldchar = " "
self.map = tcod.map_new(SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT)
for y in range(SAMPLE_SCREEN_HEIGHT):
for x in range(SAMPLE_SCREEN_WIDTH):
if SAMPLE_MAP[x, y] == " ":
# ground
tcod.map_set_properties(self.map, x, y, True, True)
elif SAMPLE_MAP[x, y] == "=":
# window
tcod.map_set_properties(self.map, x, y, True, False)
self.path = tcod.path_new_using_map(self.map)
self.dijk = tcod.dijkstra_new(self.map)
def on_enter(self):
tcod.sys_set_fps(60)
# we draw the foreground only the first time.
# during the player movement, only the @ is redrawn.
# the rest impacts only the background color
# draw the help text & player @
sample_console.clear()
sample_console.ch[self.dx, self.dy] = ord("+")
sample_console.fg[self.dx, self.dy] = tcod.white
sample_console.ch[self.px, self.py] = ord("@")
sample_console.fg[self.px, self.py] = tcod.white
sample_console.print(
1,
1,
"IJKL / mouse :\nmove destination\nTAB : A*/dijkstra",
fg=tcod.white,
bg=None,
)
sample_console.print(1, 4, "Using : A*", fg=tcod.white, bg=None)
# draw windows
for y in range(SAMPLE_SCREEN_HEIGHT):
for x in range(SAMPLE_SCREEN_WIDTH):
if SAMPLE_MAP[x, y] == "=":
tcod.console_put_char(
sample_console, x, y, tcod.CHAR_DHLINE, tcod.BKGND_NONE
)
self.recalculate = True
def on_draw(self):
if self.recalculate:
if self.using_astar:
tcod.path_compute(
self.path, self.px, self.py, self.dx, self.dy
)
else:
self.dijk_dist = 0.0
# compute dijkstra grid (distance from px,py)
tcod.dijkstra_compute(self.dijk, self.px, self.py)
# get the maximum distance (needed for rendering)
for y in range(SAMPLE_SCREEN_HEIGHT):
for x in range(SAMPLE_SCREEN_WIDTH):
d = tcod.dijkstra_get_distance(self.dijk, x, y)
if d > self.dijk_dist:
self.dijk_dist = d
# compute path from px,py to dx,dy
tcod.dijkstra_path_set(self.dijk, self.dx, self.dy)
self.recalculate = False
self.busy = 0.2
# draw the dungeon
for y in range(SAMPLE_SCREEN_HEIGHT):
for x in range(SAMPLE_SCREEN_WIDTH):
if SAMPLE_MAP[x, y] == "#":
tcod.console_set_char_background(
sample_console, x, y, DARK_WALL, tcod.BKGND_SET
)
else:
tcod.console_set_char_background(
sample_console, x, y, DARK_GROUND, tcod.BKGND_SET
)
# draw the path
if self.using_astar:
for i in range(tcod.path_size(self.path)):
x, y = tcod.path_get(self.path, i)
tcod.console_set_char_background(
sample_console, x, y, LIGHT_GROUND, tcod.BKGND_SET
)
else:
for y in range(SAMPLE_SCREEN_HEIGHT):
for x in range(SAMPLE_SCREEN_WIDTH):
if SAMPLE_MAP[x, y] != "#":
tcod.console_set_char_background(
sample_console,
x,
y,
tcod.color_lerp(
LIGHT_GROUND,
DARK_GROUND,
0.9
* tcod.dijkstra_get_distance(self.dijk, x, y)
/ self.dijk_dist,
),
tcod.BKGND_SET,
)
for i in range(tcod.dijkstra_size(self.dijk)):
x, y = tcod.dijkstra_get(self.dijk, i)
tcod.console_set_char_background(
sample_console, x, y, LIGHT_GROUND, tcod.BKGND_SET
)
# move the creature
self.busy -= tcod.sys_get_last_frame_length()
if self.busy <= 0.0:
self.busy = 0.2
if self.using_astar:
if not tcod.path_is_empty(self.path):
tcod.console_put_char(
sample_console, self.px, self.py, " ", tcod.BKGND_NONE
)
self.px, self.py = tcod.path_walk(self.path, True)
tcod.console_put_char(
sample_console, self.px, self.py, "@", tcod.BKGND_NONE
)
else:
if not tcod.dijkstra_is_empty(self.dijk):
tcod.console_put_char(
sample_console, self.px, self.py, " ", tcod.BKGND_NONE
)
self.px, self.py = tcod.dijkstra_path_walk(self.dijk)
tcod.console_put_char(
sample_console, self.px, self.py, "@", tcod.BKGND_NONE
)
self.recalculate = True
def ev_keydown(self, event: tcod.event.KeyDown):
if event.sym == ord("i") and self.dy > 0:
# destination move north
tcod.console_put_char(
sample_console, self.dx, self.dy, self.oldchar, tcod.BKGND_NONE
)
self.dy -= 1
self.oldchar = sample_console.ch[self.dx, self.dy]
tcod.console_put_char(
sample_console, self.dx, self.dy, "+", tcod.BKGND_NONE
)
if SAMPLE_MAP[self.dx, self.dy] == " ":
self.recalculate = True
elif event.sym == ord("k") and self.dy < SAMPLE_SCREEN_HEIGHT - 1:
# destination move south
tcod.console_put_char(
sample_console, self.dx, self.dy, self.oldchar, tcod.BKGND_NONE
)
self.dy += 1
self.oldchar = sample_console.ch[self.dx, self.dy]
tcod.console_put_char(
sample_console, self.dx, self.dy, "+", tcod.BKGND_NONE
)
if SAMPLE_MAP[self.dx, self.dy] == " ":
self.recalculate = True
elif event.sym == ord("j") and self.dx > 0:
# destination move west
tcod.console_put_char(
sample_console, self.dx, self.dy, self.oldchar, tcod.BKGND_NONE
)
self.dx -= 1
self.oldchar = sample_console.ch[self.dx, self.dy]
tcod.console_put_char(
sample_console, self.dx, self.dy, "+", tcod.BKGND_NONE
)
if SAMPLE_MAP[self.dx, self.dy] == " ":
self.recalculate = True
elif event.sym == ord("l") and self.dx < SAMPLE_SCREEN_WIDTH - 1:
# destination move east
tcod.console_put_char(
sample_console, self.dx, self.dy, self.oldchar, tcod.BKGND_NONE
)
self.dx += 1
self.oldchar = sample_console.ch[self.dx, self.dy]
tcod.console_put_char(
sample_console, self.dx, self.dy, "+", tcod.BKGND_NONE
)
if SAMPLE_MAP[self.dx, self.dy] == " ":
self.recalculate = True
elif event.sym == tcod.event.K_TAB:
self.using_astar = not self.using_astar
if self.using_astar:
tcod.console_print(sample_console, 1, 4, "Using : A* ")
else:
tcod.console_print(sample_console, 1, 4, "Using : Dijkstra")
self.recalculate = True
else:
super().ev_keydown(event)
def ev_mousemotion(self, event: tcod.event.MouseMotion):
mx = event.tile.x - SAMPLE_SCREEN_X
my = event.tile.y - SAMPLE_SCREEN_Y
if (
0 <= mx < SAMPLE_SCREEN_WIDTH
and 0 <= my < SAMPLE_SCREEN_HEIGHT
and (self.dx != mx or self.dy != my)
):
tcod.console_put_char(
sample_console, self.dx, self.dy, self.oldchar, tcod.BKGND_NONE
)
self.dx = mx
self.dy = my
self.oldchar = sample_console.ch[self.dx, self.dy]
tcod.console_put_char(
sample_console, self.dx, self.dy, "+", tcod.BKGND_NONE
)
if SAMPLE_MAP[self.dx, self.dy] == " ":
self.recalculate = True
#############################################
# bsp sample
#############################################
bsp_depth = 8
bsp_min_room_size = 4
# a room fills a random part of the node or the maximum available space ?
bsp_random_room = False
# if true, there is always a wall on north & west side of a room
bsp_room_walls = True
# draw a vertical line
def vline(m, x, y1, y2):
if y1 > y2:
y1, y2 = y2, y1
for y in range(y1, y2 + 1):
m[x][y] = True
# draw a vertical line up until we reach an empty space
def vline_up(m, x, y):
while y >= 0 and not m[x][y]:
m[x][y] = True
y -= 1
# draw a vertical line down until we reach an empty space
def vline_down(m, x, y):
while y < SAMPLE_SCREEN_HEIGHT and not m[x][y]:
m[x][y] = True
y += 1
# draw a horizontal line
def hline(m, x1, y, x2):
if x1 > x2:
x1, x2 = x2, x1
for x in range(x1, x2 + 1):
m[x][y] = True
# draw a horizontal line left until we reach an empty space
def hline_left(m, x, y):
while x >= 0 and not m[x][y]:
m[x][y] = True
x -= 1
# draw a horizontal line right until we reach an empty space
def hline_right(m, x, y):
while x < SAMPLE_SCREEN_WIDTH and not m[x][y]:
m[x][y] = True
x += 1
# the class building the dungeon from the bsp nodes
def traverse_node(bsp_map, node):
if not node.children:
# calculate the room size
if bsp_room_walls:
node.width -= 1
node.height -= 1
if bsp_random_room:
new_width = random.randint(
min(node.width, bsp_min_room_size), node.width
)
new_height = random.randint(
min(node.height, bsp_min_room_size), node.height
)
node.x += random.randint(0, node.width - new_width)
node.y += random.randint(0, node.height - new_height)
node.width, node.height = new_width, new_height
# dig the room
for x in range(node.x, node.x + node.width):
for y in range(node.y, node.y + node.height):
bsp_map[x][y] = True
else:
# resize the node to fit its sons
left, right = node.children
node.x = min(left.x, right.x)
node.y = min(left.y, right.y)
node.w = max(left.x + left.w, right.x + right.w) - node.x
node.h = max(left.y + left.h, right.y + right.h) - node.y
# create a corridor between the two lower nodes
if node.horizontal:
# vertical corridor
if left.x + left.w - 1 < right.x or right.x + right.w - 1 < left.x:
# no overlapping zone. we need a Z shaped corridor
x1 = random.randint(left.x, left.x + left.w - 1)
x2 = random.randint(right.x, right.x + right.w - 1)
y = random.randint(left.y + left.h, right.y)
vline_up(bsp_map, x1, y - 1)
hline(bsp_map, x1, y, x2)
vline_down(bsp_map, x2, y + 1)
else:
# straight vertical corridor
minx = max(left.x, right.x)
maxx = min(left.x + left.w - 1, right.x + right.w - 1)
x = random.randint(minx, maxx)
vline_down(bsp_map, x, right.y)
vline_up(bsp_map, x, right.y - 1)
else:
# horizontal corridor