-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1841 lines (1496 loc) · 87.5 KB
/
main.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
import pygame
import random
import math
import time
import traceback
import asyncio
from copy import deepcopy
from tile import Tile
from button import Button
from pattern import Pattern
from rule_index import RuleIndex
from sample_tile import SampleTile
from tile_button import TileButton
from paint_tile import PaintTile
from info_text import InfoText
from hover_box import HoverBox
from arrow_button import ArrowButton
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (105, 105, 105)
GREY = (175, 175, 175)
LIGHTGREY = (213, 213, 213)
LIGHTGREEN = (0, 255, 127)
GREEN = (0, 255, 00)
LAWNGREEN = (124,252,0)
DARKISHGREEN = (50, 205, 50)
DARKGREEN = (0, 128, 0)
LIGHTYELLOW = (255, 255, 125)
YELLOW = (255, 255, 0)
GOLD = (255, 215, 0)
KHAKI = (240, 230, 140)
ORANGE = (255, 165, 0)
ORANGEBROWN = (218, 165, 32)
ORANGERED = (255, 69, 0)
LIGHTBROWN = (244, 164, 96)
BROWN = (139, 69, 19)
DARKBROWN = (92, 64, 51)
DARKRED = (128, 0, 0)
RED = (255, 0, 0)
CRIMSON = (220, 20, 60)
DARKPURPLE = (75, 0, 130)
PURPLE = (150, 50, 255)
LIGHTPURPLE = (186, 85, 211)
PINK = (255, 20, 147)
LIGHTISHPINK = (255, 105, 180)
LIGHTPINK = (255, 228, 225)
CYAN = (0, 255, 255)
LIGHTBLUE = (100, 175, 255)
LIGHTISHBLUE = (30, 144, 255)
BLUE = (0, 0, 255)
DARKBLUE = (0, 0, 155)
COLOR_LIST = [WHITE, LIGHTGREY, GREY, DARKGREY, BLACK,
DARKBROWN, BROWN, LIGHTBROWN, ORANGEBROWN,
KHAKI, LIGHTYELLOW, YELLOW, GOLD, ORANGE,
ORANGERED, RED, DARKRED, CRIMSON, PINK,
LIGHTISHPINK, LIGHTPINK, LIGHTPURPLE, PURPLE,
DARKPURPLE, DARKBLUE, BLUE, LIGHTISHBLUE, LIGHTBLUE,
CYAN, LIGHTGREEN, GREEN, LAWNGREEN, DARKISHGREEN, DARKGREEN]
BACKGROUND_COLOR = (155, 155, 155)
SCREEN_TEXT_COLOR = (30, 30, 30)
IMPORTANT_SCREEN_TEXT_COLOR = (170, 0, 30)
HELP_TITLE_TEXT_COLOR = (105, 0, 135)
UP = (0, -1)
LEFT = (-1, 0)
DOWN = (0, 1)
RIGHT = (1, 0)
UP_LEFT = (-1, -1)
UP_RIGHT = (1, -1)
DOWN_LEFT = (-1, 1)
DOWN_RIGHT = (1, 1)
directions = [UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT]
# 3x3 Patterns
UP_LEFT_DIAG = (-1, -2)
UP_RIGHT_DIAG = (1, -2)
LEFT_UP_DIAG = (-2, -1)
LEFT_DOWN_DIAG = (-2, 1)
RIGHT_UP_DIAG = (2, -1)
RIGHT_DOWN_DIAG = (2, 1)
DOWN_LEFT_DIAG = (-1, 2)
DOWN_RIGHT_DIAG = (1, 2)
directions_3x3 = [
UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT,
UP_LEFT_DIAG, UP_RIGHT_DIAG, LEFT_UP_DIAG, LEFT_DOWN_DIAG,
RIGHT_UP_DIAG, RIGHT_DOWN_DIAG, DOWN_LEFT_DIAG, DOWN_RIGHT_DIAG
]
# List of premade sample Base Tiles
sample_tile_list = []
# Unused color variations of original sample tile
# original_pixel_array = [
# (WHITE, WHITE, WHITE, WHITE),
# (WHITE, BLACK, BLACK, BLACK),
# (WHITE, BLACK, LIGHTGREY, BLACK),
# (WHITE, BLACK, BLACK, BLACK),
# ]
# original_sample_tile = SampleTile(original_pixel_array, 4, 4)
# green_original_pixel_array = [
# ((50, 205, 50), (50, 205, 50), (50, 205, 50), (50, 205, 50)),
# ((50, 205, 50), (0, 128, 0), (0, 128, 0), (0, 128, 0)),
# ((50, 205, 50), (0, 128, 0), (240, 230, 140), (0, 128, 0)),
# ((50, 205, 50), (0, 128, 0), (0, 128, 0), (0, 128, 0))
# ]
# green_original_sample_tile = SampleTile(green_original_pixel_array, 4, 4)
beige_brown_green_original_pixel_array = [
((240, 230, 140), (240, 230, 140), (240, 230, 140), (240, 230, 140)),
((240, 230, 140), (92, 64, 51), (92, 64, 51), (92, 64, 51)),
((240, 230, 140), (92, 64, 51), (124, 252, 0), (92, 64, 51)),
((240, 230, 140), (92, 64, 51), (92, 64, 51), (92, 64, 51))
]
beige_brown_green_original_sample_tile = SampleTile(beige_brown_green_original_pixel_array, 4, 4)
flower_pix_array = [
((0, 128, 0), (124, 252, 0), (124, 252, 0), (124, 252, 0), (255, 20, 147), (255, 228, 225)),
((124, 252, 0), (124, 252, 0), (218, 165, 32), (124, 252, 0), (124, 252, 0), (255, 20, 147)),
((124, 252, 0), (218, 165, 32), (255, 255, 125), (218, 165, 32), (124, 252, 0), (124, 252, 0)),
((124, 252, 0), (124, 252, 0), (218, 165, 32), (124, 252, 0), (124, 252, 0), (124, 252, 0)),
((75, 0, 130), (124, 252, 0), (124, 252, 0), (124, 252, 0), (124, 252, 0), (255, 69, 0)),
((100, 175, 255), (75, 0, 130), (124, 252, 0), (124, 252, 0), (255, 69, 0), (255, 215, 0))
]
flower_sample_tile = SampleTile(flower_pix_array, 6, 6)
fire_pix_array = [
((92, 64, 51), (92, 64, 51), (92, 64, 51), (255, 0, 0), (92, 64, 51), (92, 64, 51), (92, 64, 51)),
((92, 64, 51), (92, 64, 51), (255, 0, 0), (255, 165, 0), (255, 0, 0), (92, 64, 51), (92, 64, 51)),
((92, 64, 51), (255, 0, 0), (255, 165, 0), (255, 255, 125), (255, 165, 0), (255, 0, 0), (92, 64, 51)),
((255, 0, 0), (255, 165, 0), (255, 255, 125), (255, 255, 125), (255, 255, 125), (255, 165, 0), (255, 0, 0)),
((92, 64, 51), (255, 0, 0), (255, 165, 0), (255, 255, 125), (255, 165, 0), (255, 0, 0), (92, 64, 51)),
((92, 64, 51), (92, 64, 51), (255, 0, 0), (255, 165, 0), (255, 0, 0), (92, 64, 51), (92, 64, 51)),
((92, 64, 51), (92, 64, 51), (92, 64, 51), (255, 0, 0), (92, 64, 51), (92, 64, 51), (92, 64, 51))
]
fire_sample_tile = SampleTile(fire_pix_array, 7, 7)
ice_pix_array = [
((0, 0, 155), (0, 0, 155), (30, 144, 255), (0, 255, 255)),
((0, 0, 155), (30, 144, 255), (0, 255, 255), (255, 255, 255)),
((30, 144, 255), (0, 255, 255), (255, 255, 255), (255, 255, 255)),
((0, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255))
]
ice_sample_tile = SampleTile(ice_pix_array, 4, 4)
purple_void_pix_array = [
((0, 0, 0), (0, 0, 0), (255, 228, 225), (186, 85, 211), (150, 50, 255), (75, 0, 130), (75, 0, 130)),
((0, 0, 0), (255, 228, 225), (186, 85, 211), (150, 50, 255), (75, 0, 130), (75, 0, 130), (75, 0, 130)),
((255, 228, 225), (186, 85, 211), (150, 50, 255), (75, 0, 130), (75, 0, 130), (75, 0, 130), (150, 50, 255)),
((186, 85, 211), (150, 50, 255), (75, 0, 130), (75, 0, 130), (75, 0, 130), (150, 50, 255), (186, 85, 211)),
((150, 50, 255), (75, 0, 130), (75, 0, 130), (75, 0, 130), (150, 50, 255), (186, 85, 211), (255, 228, 225)),
((75, 0, 130), (75, 0, 130), (75, 0, 130), (150, 50, 255), (186, 85, 211), (255, 228, 225), (0, 0, 0)),
((75, 0, 130), (75, 0, 130), (150, 50, 255), (186, 85, 211), (255, 228, 225), (0, 0, 0), (0, 0, 0))
]
purple_void_sample_tile = SampleTile(purple_void_pix_array, 7, 7)
test_pix_array = [
((255, 255, 255), (255, 255, 125), (124, 252, 0)),
((255, 0, 0), (30, 144, 255), (255, 165, 0)),
((139, 69, 19), (0, 0, 0), (105, 105, 105))
]
test_pix_array_tile = SampleTile(test_pix_array, 3, 3)
sample_tile_list.append(test_pix_array_tile)
sample_tile_list.append(beige_brown_green_original_sample_tile)
sample_tile_list.append(ice_sample_tile)
sample_tile_list.append(flower_sample_tile)
sample_tile_list.append(fire_sample_tile)
sample_tile_list.append(purple_void_sample_tile)
def get_rotated_pix_array(pix_array) -> tuple:
"""
Take a two dimensional pixel array (list) and return a tuple consisting of
the same pixel array in tuple form, every 90 degree rotation of the original pixel array,
and the vertical and horizontal mirror of the pixel array.
"""
rotated_pix_array_270 = tuple(zip(*pix_array[::-1]))
rotated_pix_array_180 = tuple(zip(*rotated_pix_array_270[::-1]))
rotated_pix_array_90 = tuple(zip(*rotated_pix_array_180[::-1]))
if len(pix_array) == 2:
# 2x2 patterns
vertically_flipped_pix_array = tuple(pix_array[0][::-1]), tuple(pix_array[-1][::-1])
elif len(pix_array) == 3:
# 3x3 patterns
vertically_flipped_pix_array = tuple(pix_array[0][::-1]), tuple(pix_array[1][::-1]), tuple(pix_array[-1][::-1])
horizontally_flipped_pix_array = tuple(pix_array[::-1])
pix_array = tuple(pix_array)
return (pix_array, rotated_pix_array_90, rotated_pix_array_180, rotated_pix_array_270, vertically_flipped_pix_array, horizontally_flipped_pix_array)
def get_offset_tiles(pattern, offset, pattern_size) -> tuple:
"""
Return the tile(s) from input pattern pix_array which intersects with
input offset coordinates (x, y) from the perspective of the offset.
"""
if pattern_size == 2:
if offset == (0, 0):
return pattern.pix_array
if offset == (-1, -1):
return tuple([pattern.pix_array[1][1]])
if offset == (0, -1):
return tuple(pattern.pix_array[1][:])
if offset == (1, -1):
return tuple([pattern.pix_array[1][0]])
if offset == (-1, 0):
return tuple([pattern.pix_array[0][1], pattern.pix_array[1][1]])
if offset == (1, 0):
return tuple([pattern.pix_array[0][0], pattern.pix_array[1][0]])
if offset == (-1, 1):
return tuple([pattern.pix_array[0][1]])
if offset == (0, 1):
return tuple(pattern.pix_array[0][:])
if offset == (1, 1):
return tuple([pattern.pix_array[0][0]])
elif pattern_size == 3:
if offset == (0, 0):
return pattern.pix_array
if offset == (-1, -1):
return ((pattern.pix_array[1][1], pattern.pix_array[1][2]),
(pattern.pix_array[2][1], pattern.pix_array[2][2]))
if offset == (0, -1):
return ((pattern.pix_array[1][0], pattern.pix_array[1][1], pattern.pix_array[1][2]),
(pattern.pix_array[2][0], pattern.pix_array[2][1], pattern.pix_array[2][2]))
if offset == (1, -1):
return ((pattern.pix_array[1][0], pattern.pix_array[1][1]),
(pattern.pix_array[2][0], pattern.pix_array[2][1]))
if offset == (-1, 0):
return ((pattern.pix_array[0][1], pattern.pix_array[0][2]),
(pattern.pix_array[1][1], pattern.pix_array[1][2]),
(pattern.pix_array[2][1], pattern.pix_array[2][2]))
if offset == (1, 0):
return ((pattern.pix_array[0][0], pattern.pix_array[0][1]),
(pattern.pix_array[1][0], pattern.pix_array[1][1]),
(pattern.pix_array[2][0], pattern.pix_array[2][1]))
if offset == (-1, 1):
return ((pattern.pix_array[0][1], pattern.pix_array[0][2]),
(pattern.pix_array[1][1], pattern.pix_array[1][2]))
if offset == (0, 1):
return ((pattern.pix_array[0][0], pattern.pix_array[0][1], pattern.pix_array[0][2]),
(pattern.pix_array[1][0], pattern.pix_array[1][1], pattern.pix_array[1][2]))
if offset == (1, 1):
return ((pattern.pix_array[0][0], pattern.pix_array[0][1]),
(pattern.pix_array[1][0], pattern.pix_array[1][1]))
if offset == (-1, -2):
return (pattern.pix_array[2][1], pattern.pix_array[2][2])
if offset == (1, -2):
return (pattern.pix_array[2][0], pattern.pix_array[2][1])
if offset == (-2, -1):
return (pattern.pix_array[1][2]), (pattern.pix_array[2][2])
if offset == (-2, 1):
return (pattern.pix_array[0][2], pattern.pix_array[1][2])
if offset == (2, -1):
return (pattern.pix_array[1][0], pattern.pix_array[2][0])
if offset == (2, 1):
return (pattern.pix_array[0][0], pattern.pix_array[1][0])
if offset == (-1, 2):
return (pattern.pix_array[0][1], pattern.pix_array[0][2])
if offset == (1, 2):
return (pattern.pix_array[0][0], pattern.pix_array[0][1])
def get_valid_directions(position, output_width, output_height, pattern_size) -> list:
"""
Return a list of strings representing the valid directions that can be taken
from the given input position on the grid.
"""
x, y = position
valid_directions = []
if pattern_size == 2:
if x == 0:
valid_directions.extend([RIGHT])
if y == 0:
valid_directions.extend([DOWN, DOWN_RIGHT])
elif y == output_height-1:
valid_directions.extend([UP, UP_RIGHT])
else:
valid_directions.extend([DOWN, DOWN_RIGHT, UP, UP_RIGHT])
elif x == output_width-1:
valid_directions.extend([LEFT])
if y == 0:
valid_directions.extend([DOWN, DOWN_LEFT])
elif y == output_height-1:
valid_directions.extend([UP, UP_LEFT])
else:
valid_directions.extend([DOWN, DOWN_LEFT, UP, UP_LEFT])
else:
valid_directions.extend([LEFT, RIGHT])
if y == 0:
valid_directions.extend([DOWN, DOWN_LEFT, DOWN_RIGHT])
elif y == output_height-1:
valid_directions.extend([UP, UP_LEFT, UP_RIGHT])
else:
valid_directions.extend([UP, UP_LEFT, UP_RIGHT, DOWN, DOWN_LEFT, DOWN_RIGHT])
elif pattern_size == 3:
if x == 0:
valid_directions.extend([RIGHT])
if y == 0:
valid_directions.extend([DOWN, DOWN_RIGHT, RIGHT_DOWN_DIAG, DOWN_RIGHT_DIAG])
elif y == output_height-1:
valid_directions.extend([UP, UP_RIGHT, UP_RIGHT_DIAG, RIGHT_UP_DIAG])
else:
valid_directions.extend([DOWN, DOWN_RIGHT, UP, UP_RIGHT, RIGHT_DOWN_DIAG, DOWN_RIGHT_DIAG, UP_RIGHT_DIAG, UP_LEFT_DIAG])
elif x == output_width-1:
valid_directions.extend([LEFT])
if y == 0:
valid_directions.extend([DOWN, DOWN_LEFT, LEFT_DOWN_DIAG, DOWN_LEFT_DIAG])
elif y == output_height-1:
valid_directions.extend([UP, UP_LEFT, UP_LEFT_DIAG, LEFT_UP_DIAG])
else:
valid_directions.extend([DOWN, DOWN_LEFT, UP, UP_LEFT, LEFT_DOWN_DIAG, DOWN_LEFT_DIAG, UP_LEFT_DIAG, LEFT_UP_DIAG])
else:
valid_directions.extend([LEFT, RIGHT])
if y == 0:
valid_directions.extend([DOWN, DOWN_LEFT, DOWN_RIGHT, LEFT_DOWN_DIAG, DOWN_LEFT_DIAG, RIGHT_DOWN_DIAG, DOWN_RIGHT_DIAG])
elif y == output_height-1:
valid_directions.extend([UP, UP_LEFT, UP_RIGHT, LEFT_UP_DIAG, UP_LEFT_DIAG, RIGHT_UP_DIAG, UP_RIGHT_DIAG])
else:
valid_directions.extend([UP, UP_LEFT, UP_RIGHT, DOWN, DOWN_LEFT, DOWN_RIGHT,
LEFT_DOWN_DIAG, DOWN_LEFT_DIAG, RIGHT_DOWN_DIAG, DOWN_RIGHT_DIAG,
LEFT_UP_DIAG, UP_LEFT_DIAG, RIGHT_UP_DIAG, UP_RIGHT_DIAG
])
return valid_directions
def get_patterns(pattern_size, base_tile) -> tuple:
"""
Return a tuple consisting of a list of every unique pattern of input size pattern_size x pattern_size
inside input base_tile object, a dictionary of each unique pattern's occurence weight and a dictionary
of each unique pattern's probability of being propagated.
"""
pattern_list = []
occurence_weights = {}
probability = {}
pix_array = base_tile.pix_array
# Get every 2x2 pattern in Base Tile along with all rotations and mirrors of pattern
for row in range(base_tile.width - (pattern_size - 1)):
for col in range(base_tile.height - (pattern_size - 1)):
pattern = []
for pix in pix_array[row:row+pattern_size]:
pattern.append(pix[col:col+pattern_size])
pattern_rotations = get_rotated_pix_array(pattern)
for rotation in pattern_rotations:
if rotation not in occurence_weights:
occurence_weights[rotation] = 1
else:
occurence_weights[rotation] += 1
pattern_list.extend(pattern_rotations)
# Remove all duplicate patterns
unique_pattern_list = []
for pattern in pattern_list:
if pattern not in unique_pattern_list:
unique_pattern_list.append(pattern)
pattern_list = unique_pattern_list
# Calculate probability for every unique pattern
sum_of_weights = 0
for weight in occurence_weights:
sum_of_weights += occurence_weights[weight]
for pattern in pattern_list:
probability[pattern] = occurence_weights[pattern] / sum_of_weights
pattern_list = [Pattern(pattern) for pattern in pattern_list]
occurence_weights = {pattern:occurence_weights[pattern.pix_array] for pattern in pattern_list}
probability = {pattern:probability[pattern.pix_array] for pattern in pattern_list}
return pattern_list, occurence_weights, probability
def initialize_wave_function(pattern_list, output_width, output_height) -> list:
"""
Create and return a two dimensional array of size output_width x output_height,
where every element stores a list of every pattern in input pattern_list.
"""
coefficients = []
for col in range(output_width):
row = []
for r in range(output_height):
row.append(pattern_list)
coefficients.append(row)
return coefficients
def is_wave_function_fully_collapsed(coefficients) -> bool:
"""Check if wave function is fully collapsed meaning that for each tile available is only one pattern."""
for col in coefficients:
for entry in col:
if len(entry) > 1:
return False
return True
def get_possible_patterns_at_position(position, coefficients) -> list:
"""Return possible patterns at position (x, y)."""
x, y = position
possible_patterns = coefficients[x][y]
return possible_patterns
def get_shannon_entropy(position, coefficients, probability) -> float:
"""Calcualte the Shannon Entropy of the wavefunction at position (x, y)."""
x, y = position
entropy = 0
# A cell with one valid pattern has 0 entropy
if len(coefficients[x][y]) == 1:
return 0
for pattern in coefficients[x][y]:
entropy += probability[pattern] * math.log(probability[pattern], 2)
entropy *= -1
# Add noise to break ties and near-ties
entropy -= random.uniform(0, 0.1)
return entropy
def get_min_entropy_at_pos(coefficients, probability) -> tuple:
"""Return position of tile with the lowest entropy."""
min_entropy = None
min_entropy_pos = None
for x, col in enumerate(coefficients):
for y, row in enumerate(col):
entropy = get_shannon_entropy((x, y), coefficients, probability)
if entropy == 0:
continue
if min_entropy is None or entropy < min_entropy:
min_entropy = entropy
min_entropy_pos = (x, y)
return min_entropy_pos
def observe(coefficients, probability, coefficients_state) -> tuple:
"""
Return the position of the grid with the lowest entropy after assigning
a pattern to the position and updating the grid.
"""
# Find the lowest entropy
min_entropy_pos = get_min_entropy_at_pos(coefficients, probability)
if min_entropy_pos == None:
print("All tiles have 0 entropy")
return
# Choose a pattern at lowest entropy position which is most frequent in the sample
possible_patterns = get_possible_patterns_at_position(min_entropy_pos, coefficients)
random_pattern = random.choice([pat for pat in possible_patterns])
# Set this pattern to be the only available at this position
coefficients[min_entropy_pos[0]][min_entropy_pos[1]] = random_pattern
# Store current state in history of WFC progress
current_coefficients = deepcopy(coefficients)
coefficients_state.append(current_coefficients)
return min_entropy_pos
def propagate(min_entropy_pos, coefficients, rule_index, output_width, output_height, pattern_size, coefficients_state):
"""Propagate wave function at min_entropy_pos, updating its neighbouring tiles' patterns."""
stack = [min_entropy_pos]
while len(stack) > 0:
pos = stack.pop()
possible_patterns = get_possible_patterns_at_position(pos, coefficients)
# Iterate through each location immediately adjacent to the current location
for direction in get_valid_directions(pos, output_width, output_height, pattern_size):
adjacent_pos = (pos[0] + direction[0], pos[1] + direction[1])
possible_patterns_at_adjacent = get_possible_patterns_at_position(adjacent_pos, coefficients)
# Iterate over all still available patterns in adjacent tile
# and check if pattern is still possible in this location
if not isinstance(possible_patterns_at_adjacent, list):
possible_patterns_at_adjacent = [possible_patterns_at_adjacent]
for possible_pattern_at_adjacent in possible_patterns_at_adjacent:
if len(possible_patterns) > 1:
is_possible = any([rule_index.check_possibility(pattern, possible_pattern_at_adjacent, direction) for pattern in possible_patterns])
else:
is_possible = rule_index.check_possibility(possible_patterns, possible_pattern_at_adjacent, direction)
"""
If the tile is not compatible with any of the tiles in the current location's wavefunction
then it's impossible for it to ever get choosen so it needs to be removed from the other
location's wavefunction
"""
if not is_possible:
x, y = adjacent_pos
coefficients[x][y] = [patt for patt in coefficients[x][y] if patt.pix_array != possible_pattern_at_adjacent.pix_array]
# Store current state in history of WFC progress
current_coefficients = deepcopy(coefficients)
coefficients_state.append(current_coefficients)
if adjacent_pos not in stack:
stack.append(adjacent_pos)
async def execute_wave_function_collapse(patterns, output_width, output_height, pattern_size, asyncio_queue, wfc_state):
"""Start wave function collapse algorithm with input patterns and send updates to GUI through asyncio."""
pattern_list = patterns[0]
occurence_weights = patterns[1]
probability = patterns[2]
if pattern_size == 2:
direction_list = directions
elif pattern_size == 3:
direction_list = directions_3x3
# Create rules for adjacent patterns for every pattern
rule_index = RuleIndex(pattern_list, direction_list)
number_of_rules = 0
for pattern in pattern_list:
for direction in direction_list:
for pattern_next in pattern_list:
overlap = get_offset_tiles(pattern_next, direction, pattern_size)
og_dir = tuple([direction[0]*-1, direction[1]*-1])
part_of_og_pattern = get_offset_tiles(pattern, og_dir, pattern_size)
if overlap == part_of_og_pattern:
rule_index.add_rule(pattern, direction, pattern_next)
number_of_rules += 1
coefficients = initialize_wave_function(pattern_list, output_width, output_height)
perf_time_start = time.perf_counter()
print("Wave Function Collapse Started")
has_wfc_failed = False
# List to store WFC progress history
coefficients_state = []
# Status message to report result of WFC
wfc_status = ""
# Actual start of WFC algorihm
try:
while not is_wave_function_fully_collapsed(coefficients):
if wfc_state["interrupt"]:
print("break")
wfc_status = "finished-interrupted"
break
# Add latest status to asyncio queue to give real time updates to GUI
await asyncio_queue.put(["ongoing", deepcopy(coefficients)])
min_entropy_pos = observe(coefficients, probability, coefficients_state)
await asyncio_queue.put(["ongoing", deepcopy(coefficients)])
propagate(min_entropy_pos, coefficients, rule_index, output_width, output_height, pattern_size, coefficients_state)
# Sleep to allow GUI to update while algorithm is running
await asyncio.sleep(0)
await asyncio_queue.put(["ongoing", deepcopy(coefficients)])
except Exception as e:
has_wfc_failed = True
# print("WFC FAIL: ", e)
traceback.print_exc()
perf_time_end = time.perf_counter()
print(f"Wave Function Collapse Ended After {(perf_time_end - perf_time_start):.3f}s")
if wfc_status == "":
if not has_wfc_failed:
wfc_status = "finished-success"
else:
wfc_status = "finished-fail"
"""
Create Pixel Array of final image by storing the top left color of the pattern
at every position in the wave function matrix.
"""
final_pixels = []
for i in coefficients:
row = []
for j in i:
if isinstance(j, list):
if len(j) > 0:
first_pixel = j[0].pix_array[0][0]
else:
"""
If WFC fails, the position that failed will be assigned grey or
"transparent" color since it will not have any pattern stored.
"""
first_pixel = BACKGROUND_COLOR
else:
first_pixel = j.pix_array[0][0]
row.append(first_pixel)
final_pixels.append(row)
# Add final information about the executed WFC into asyncio queue
await asyncio_queue.put([wfc_status, final_pixels, coefficients_state, round((perf_time_end - perf_time_start), 3)])
def draw_window(screen):
"""Fill window with background color."""
screen.fill(BACKGROUND_COLOR)
def get_pattern_tiles(patterns, pattern_size, enlargement_scale) -> list:
"""Create and return a list of Tile objects for every pattern in 'patterns' list."""
y_offset = 24
x_offset = 20
tiles_per_row_limit = 19 # Maximum tiles per row
# X and Y offset for 3x3 patterns
if pattern_size == 3:
y_offset = 34
x_offset = 30
tiles_per_row_limit = 12
x = 10 # Start x-coordinate
y = 339 # Start y-coordinate
tile_list = []
for col in range(len(patterns)):
if col % tiles_per_row_limit == 0 and col > 1:
# Start new row if tiles_per_row_limit reached
y += y_offset
x -= tiles_per_row_limit * (pattern_size + x_offset)
tile = Tile(pattern_size, pattern_size, (col * (pattern_size + x_offset) + x), y, patterns[col].pix_array, enlargement_scale)
tile_list.append(tile)
return tile_list
def update_patterns(pattern_group, pattern_tile_list, pattern_draw_limit):
"""Add list of Tile objects input to pattern_group Sprite group."""
pattern_group.empty()
# Removes any patterns beyond pattern_draw_limit amount from pattern_tile_list
pattern_tile_list = pattern_tile_list[:pattern_draw_limit]
for pattern in pattern_tile_list:
pattern_group.add(pattern)
def create_tile_buttons(base_tile_list) -> list:
"""Create and return a list of Tile objects for every sample Base Tile from input list."""
tile_buttons = []
for tile in base_tile_list:
tile_button = TileButton(tile.x, tile.y, tile.image)
tile_buttons.append(tile_button)
return tile_buttons
def draw_selected_tile_border(screen, tile):
"""Draw a yellow border around input Tile object."""
pygame.draw.rect(screen, YELLOW, (tile.x-5, tile.y-5, tile.width + 10, tile.height + 10), 4)
def show_prob(patterns):
"""Display each pattern from input's probability."""
# CURRENTLY UNUSED FUNCTION
count = 1
for pattern, prob in patterns[2].items():
print(count, pattern.pix_array, prob)
count += 1
def get_pattern_dict(pattern_list) -> dict:
"""Return a dictionary that stores every pattern in input's position in (x, y) form."""
# CURRENTLY UNUSED FUNCTION
pattern_dict = {}
for pattern in pattern_list:
pattern_dict[pattern.pix_array] = (pattern.x, pattern.y)
return pattern_dict
def create_empty_paint_grid(x_pos, y_pos, cols, rows, tile_size) -> list:
"""Create and return grid of white colored PaintTile objects from input coordinates and dimensions."""
grid = []
for col in range(cols):
new_row = []
for row in range(rows):
tile = PaintTile(tile_size, tile_size, (x_pos + tile_size * col), (y_pos + tile_size * row), WHITE)
new_row.append(tile)
grid.append(new_row)
return grid
def create_colored_paint_grid(x_pos, y_pos, tile_size, pix_array) -> list:
"""Create and return a paint grid colored in the same way as input pix_array."""
grid = []
for i, row in enumerate(pix_array):
new_row = []
for j, color in enumerate(row):
tile = PaintTile(tile_size, tile_size, (x_pos + tile_size * i), (y_pos + tile_size * j), color)
new_row.append(tile)
grid.append(new_row)
return grid
def create_pix_array(paint_grid) -> list:
"""Create and return a color pixel array tuple from input Paint Grid."""
pix_array = []
for col in paint_grid:
new_row = []
for tile in col:
new_row.append(tile.color)
pix_array.append(tuple(new_row))
return pix_array
def create_paint_color_tiles() -> list:
"""Create and return a list of different colored PaintTile objects."""
y = 28
x = 10
tiles_per_row_limit = 17 # Maximum paint tiles per row
color_tile_list = []
for col in range(34):
if col % tiles_per_row_limit == 0 and col > 0:
# Start new row if tiles_per_row_limit reached
y += 33
x = 10
if col < len(COLOR_LIST):
# Create a paint tile for every color in COLOR_LIST
color_tile = PaintTile(30, 30, x, y, (COLOR_LIST[col]))
else:
# Create grey paint tiles if loop is longer than the amount of colors in COLOR_LIST
# (Mostly for debugging purposes)
color_tile = PaintTile(30, 30, x, y, GREY)
color_tile_list.append(color_tile)
x += 33
return color_tile_list
def get_output_size_text_color(size) -> tuple:
"""Return a color based on input size number."""
if size < 15:
return GREEN
elif size >= 15 and size < 22:
return YELLOW
return IMPORTANT_SCREEN_TEXT_COLOR # Red
def print_tile_colors(tile):
"""Print the pixel array of input Tile object in terminal."""
print(tile.pix_array)
def create_tile_list(tile_list, tile_list_x_pos, tile_list_y_pos, tile_list_offset, enlargement_scale, tiles_per_row_limit) -> list:
"""Create and return a list of Tile objects from input tile_list."""
x_pos = tile_list_x_pos
y_pos = tile_list_y_pos
tile_width = 0 # Width of last tile in row
row_max_height = 0 # Height of largest tile in row
new_tile_list = []
for i, tile in enumerate(tile_list, start=1):
new_tile = Tile(tile.width, tile.height, x_pos, y_pos, tile.pix_array, enlargement_scale)
new_tile_list.append(new_tile)
if tile.height > row_max_height:
row_max_height = tile.height
if i % tiles_per_row_limit == 0:
# Start new row if tiles_per_row_limit is reached
x_pos = tile_list_x_pos
y_pos = y_pos + row_max_height * enlargement_scale + tile_list_offset
tile_width = 0
row_max_height = 0
else:
# Calculate x-coordinate of next tile in list if next tile is to be placed on the same row
tile_width = tile.width * enlargement_scale
x_pos += tile_width + tile_list_offset
return new_tile_list
async def main(loop):
"""Take an asyncio event loop object and create GUI of application."""
pygame.init()
size_27_font = pygame.font.Font(pygame.font.get_default_font(), 27)
size_24_font = pygame.font.Font(pygame.font.get_default_font(), 24)
size_20_font = pygame.font.Font(pygame.font.get_default_font(), 20)
size_18_font = pygame.font.Font(pygame.font.get_default_font(), 18)
size_17_font = pygame.font.Font(pygame.font.get_default_font(), 17)
# Dimensions of Pygame window
WIDTH = 800
HEIGHT = 640
clock = pygame.time.Clock()
FPS = 60
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Paint A Wave Function Collapse")
# Sprite Group for Pattern Tiles extracted from Base Tile
pattern_group = pygame.sprite.Group()
# Sprite Group for first grid
wfc_grid_group = pygame.sprite.Group()
# Sprite Group for second grid
wfc_second_grid_group = pygame.sprite.Group()
# Sprite Group for all Paint Tiles
paint_color_group = pygame.sprite.Group()
# Sprite Group for HoverBox (Must be called last to be drawn on top)
hover_box_group = pygame.sprite.Group()
hover_box_font = size_18_font
hover_box_line_height = hover_box_font.get_linesize()
start_wfc_button = Button(WHITE, 509, 114, 150, 44, "Start WFC", BLACK, LIGHTGREY, big_text=True)
cancel_wfc_button = Button(GREY, 668, 118, 120, 40, "Cancel WFC", DARKGREY, GREY)
skip_replay_button = Button(GREY, 509, 163, 130, 40, "Skip Replay", DARKGREY, GREY)
replay_animation_button = Button(GREY, 509, 208, 170, 40, "Replay Last WFC", DARKGREY, GREY)
paint_new_tile_button = Button(WHITE, 650, 320, 140, 36, "Paint New Tile", BLACK, LIGHTGREY)
return_to_wfc_button = Button(WHITE, 600, 7, 190, 40, "Return To WFC", BLACK, LIGHTGREY, big_text=True)
help_button = Button(WHITE, 9, 596, 110, 37, "HELP", BLACK, LIGHTGREY, big_text=True)
return_from_help_button = Button(WHITE, 673, 593, 120, 40, "Return", BLACK, LIGHTGREY, big_text=True)
increase_wfc_output_size_button = ArrowButton(WHITE, 709, 48, 26, 17, BLACK, LIGHTGREY, is_pointing_up=True)
decrease_wfc_output_size_button = ArrowButton(WHITE, 709, 67, 26, 17, BLACK, LIGHTGREY, is_pointing_up=False)
toggle_anim_during_wfc_button = Button(WHITE, 369, 548, 50, 20, "Change", BLACK, LIGHTGREY, small_text=True)
toggle_anim_after_wfc_button = Button(WHITE, 369, 570, 50, 20, "Change", BLACK, LIGHTGREY, small_text=True)
increase_replay_speed_button = ArrowButton(WHITE, 165, 513, 26, 17, BLACK, LIGHTGREY, is_pointing_up=True)
decrease_replay_speed_button = ArrowButton(WHITE, 165, 532, 26, 17, BLACK, LIGHTGREY, is_pointing_up=False)
increase_paint_grid_size_button = ArrowButton(WHITE, 300, 95, 26, 17, BLACK, LIGHTGREY, is_pointing_up=True)
decrease_paint_grid_size_button = ArrowButton(WHITE, 300, 114, 26, 17, BLACK, LIGHTGREY, is_pointing_up=False)
clear_paint_grid_button = Button(WHITE, 9, 520, 170, 40, "Clear Paint Grid", BLACK, LIGHTGREY)
toggle_grid_lines_button = Button(WHITE, 190, 520, 170, 40, "Toggle Grid Lines", BLACK, LIGHTGREY)
save_tile_button = Button(WHITE, 615, 120, 150, 46, "Save Tile", BLACK, LIGHTGREY, big_text=True)
delete_tile_button = Button(WHITE, 600, 320, 190, 36, "Delete Selected Tile", BLACK, LIGHTGREY)
copy_tile_button = Button(WHITE, 440, 268, 190, 36, "Copy Selected Tile", BLACK, LIGHTGREY)
# Unused buttons
test_button = Button(WHITE, 460, 540, 110, 40, "TEST", BLACK, LIGHTGREY)
test_paint_button = Button(WHITE, 620, 30, 150, 40, "TEST", BLACK, LIGHTGREY)
set_pattern_size_2_button = Button(WHITE, 590, 540, 200, 40, "Set Pattern Size 2", BLACK, LIGHTGREY)
set_pattern_size_3_button = Button(WHITE, 590, 590, 200, 40, "Set Pattern Size 3", BLACK, LIGHTGREY)
run = True
draw_second_grid = True
# Tile Sprite for first grid
wfc_output = None
# Tile Sprite for second grid
wfc_output_2 = None
# Scale at which a Tile pixel gets scaled up by
enlargement_scale = 8
# X and Y start position of list of Base Tiles
tile_list_x_pos = 455
tile_list_y_pos = 368
# Free space between every Tile in list of Base Tiles
tile_list_offset = 12
# Height of largest Base Tile in last row
base_tile_max_height = 7
# Amount of Base Tiles to be drawn per row
base_tiles_per_row_limit = 5
# Max amount of Base Tiles allowed in list of Base Tiles
max_base_tiles = 20
# List of Base Tiles
base_tile_list = create_tile_list(sample_tile_list, tile_list_x_pos, tile_list_y_pos, tile_list_offset, enlargement_scale, base_tiles_per_row_limit)
# Width and height of Pattern extracted from Base Tile
pattern_size = 3
# Index of selected Base Tile in base_tile_list
selected_base_tile_index = 0
"""
Tuple consisting of a list of every unique Pattern from Base Tile,
along with two dictionaries to store each patterns occurence weights
and probability respectively.
"""
patterns = get_patterns(pattern_size, base_tile_list[selected_base_tile_index])
# List of all Tile objects in Pattern list
pattern_tile_list = get_pattern_tiles(patterns[0], pattern_size, enlargement_scale)
# Amount of maximum patterns to be drawn on screen
pattern_draw_limit = 57
# Add Patterns to be drawn on screen to pattern_group Sprite Group
update_patterns(pattern_group, pattern_tile_list, pattern_draw_limit)
# Start position of first grid
grid_x_pos = 10
grid_y_pos = 28
# Start position of second grid
second_grid_x_pos = 260
second_grid_y_pos = 28
# Output size of WFC image in pixels
output_width = 20
output_height = 20
# Different color to represent slowness of WFC at different output sizes
output_size_text_color = get_output_size_text_color(output_width)
grid_size = output_width
# Maximum and minimum allowed output sizes
output_grid_upper_limit = 30
output_grid_lower_limit = 10
# Clickable buttons for every selectable Base Tile
tile_buttons = create_tile_buttons(base_tile_list)
# Draw selected Base Tile
selected_base_tile = tile_buttons[selected_base_tile_index]
selected_base_tile_x_pos = 510
selected_base_tile_y_pos = 50
selected_base_tile_image = selected_base_tile.image.copy()
selected_base_tile_text = size_20_font.render("Base Tile", True, SCREEN_TEXT_COLOR)
# Full history of WFC progress stored as a list of images
wfc_order_list = []
# Index of current WFC state image as second grid loops through the full WFC progress
wfc_list_count = 0
# Number to represent the interval of elements from wfc_order_list to be stored in sliced_list
wfc_replay_slice_num = 5
# Sliced history list of WFC progress where only every Nth element is stored
sliced_list = []
# Final image of WFC
last_image = None
# Maximum and minimum allowed values for wfc_replay_slice_num
wfc_slice_num_upper_limit = 15
wfc_slice_num_lower_limit = 1
# Default game state
game_state = "wfc"
# Game state to return to from Help state
previous_game_state = "wfc"
current_color_text = size_18_font.render("Paint Color:", True, SCREEN_TEXT_COLOR)
# Start position of Paint Grid
paint_grid_x_pos = 10
paint_grid_y_pos = 158
# Size of clickable Tile in Paint Grid
paint_grid_tile_size = 50
# Size of Paint Grid/Painted Tile
paint_grid_cols = 4
paint_grid_rows = 4
#Maximum and minimum allowed sized for Paint Grid/Painted Tile
paint_grid_size_limit_upper = 7
paint_grid_size_limit_lower = 3
paint_guide_color_text = size_18_font.render("Click on a color in the color panel to change color", True, IMPORTANT_SCREEN_TEXT_COLOR)
paint_guide_grid_text = size_18_font.render("Click on a square in the grid to paint the tile", True, IMPORTANT_SCREEN_TEXT_COLOR)
paint_guide_save_text_lines = ["Click on 'Save Tile' to", "save the current tile"]
paint_guide_save_text = []
for line in paint_guide_save_text_lines:
paint_guide_save_text.append(size_18_font.render(line, True, IMPORTANT_SCREEN_TEXT_COLOR))
current_paint_tile_size_text = size_18_font.render(f"Tile Size: {paint_grid_cols}x{paint_grid_rows}", True, SCREEN_TEXT_COLOR)
painted_tile_text = size_20_font.render("Painted Tile", True, SCREEN_TEXT_COLOR)
# Clickable Paint Grid
paint_grid = create_empty_paint_grid(paint_grid_x_pos, paint_grid_y_pos, paint_grid_cols, paint_grid_rows, paint_grid_tile_size)
# Pixel Array of the Paint Grid
paint_grid_pix_array = create_pix_array(paint_grid)
# Default selected color
current_color = CRIMSON
# Tile to show which color is selected
current_color_tile = PaintTile(30, 30, paint_grid_x_pos + 114, 99, current_color)