-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWkndrfile.mkmaze
3458 lines (2938 loc) · 117 KB
/
Wkndrfile.mkmaze
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
# encoding: UTF-8
module Theseus
module Formatters
class ASCII
# Renders an UpsilonMaze to an ASCII representation, using 3 characters
# horizontally and 4 characters vertically to represent a single octagonal
# cell, and 3 characters horizontally and 2 vertically to represent a square
# cell.
# _ _ _
# / \_/ \_/ \
# | |_| |_| |
# \_/ \_/ \_/
# |_| |_| |_|
# / \_/ \_/ \
#
# You shouldn't ever need to instantiate this class directly. Rather, use
# UpsilonMaze#to(:ascii) (or UpsilonMaze#to_s to get the string directly).
class Upsilon < ASCII
# Returns a new Sigma canvas for the given maze (which should be an
# instance of SigmaMaze). The +options+ parameter is not used.
#
# The returned object will be fully initialized, containing an ASCII
# representation of the given SigmaMaze.
def initialize(maze, options={})
super(maze.width * 2 + 1, maze.height * 2 + 3)
maze.height.times do |y|
py = y * 2
maze.row_length(y).times do |x|
cell = maze[x, y]
next if cell == 0
px = x * 2
if (x + y) % 2 == 0
draw_octogon_cell(px, py, cell)
else
draw_square_cell(px, py, cell)
end
end
end
end
private
def draw_octogon_cell(px, py, cell) #:nodoc:
self[px+1, py] = "_" if cell & Maze::N == 0
self[px, py+1] = "/" if cell & Maze::NW == 0
self[px+2, py+1] = "\\" if cell & Maze::NE == 0
self[px, py+2] = "|" if cell & Maze::W == 0
self[px+2, py+2] = "|" if cell & Maze::E == 0
self[px, py+3] = "\\" if cell & Maze::SW == 0
self[px+1, py+3] = "_" if cell & Maze::S == 0
self[px+2, py+3] = "/" if cell & Maze::SE == 0
end
def draw_square_cell(px, py, cell) #:nodoc:
self[px+1, py+1] = "_" if cell & Maze::N == 0
self[px, py+2] = "|" if cell & Maze::W == 0
self[px+1, py+2] = "_" if cell & Maze::S == 0
self[px+2, py+2] = "|" if cell & Maze::E == 0
end
end
end
end
end
module Theseus
module Formatters
class ASCII
# Renders an OrthogonalMaze to an ASCII representation.
#
# The ASCII formatter for the OrthogonalMaze actually supports three different
# output types:
#
# [:plain] Uses standard 7-bit ASCII characters. Width is 2x+1, height is
# y+1. This mode cannot render weave mazes without significant
# ambiguity.
# [:unicode] Uses unicode characters to render cleaner lines. Width is
# 3x, height is 2y. This mode has sufficient detail to correctly
# render mazes with weave!
# [:lines] Draws passages as lines, using unicode characters. Width is
# x, height is y. This mode can render weave mazes, but with some
# ambiguity.
#
# The :plain mode is the default, but you can specify a different one using
# the :mode option.
#
# You shouldn't ever need to instantiate this class directly. Rather, use
# OrthogonalMaze#to(:ascii) (or OrthogonalMaze#to_s to get the string directly).
class Orthogonal < ASCII
# Returns the dimensions of the given maze, rendered in the given mode.
# The +mode+ must be +:plain+, +:unicode+, or +:lines+.
def self.dimensions_for(maze, mode)
case mode
when :plain, nil then
[maze.width * 2 + 1, maze.height + 1]
when :unicode then
[maze.width * 3, maze.height * 2]
when :lines then
[maze.width, maze.height]
else
abort "unknown mode #{mode.inspect}"
end
end
# Create and return a fully initialized ASCII canvas. The +options+
# parameter may specify a +:mode+ parameter, as described in the documentation
# for this class.
def initialize(maze, options={})
mode = options[:mode] || :plain
width, height = self.class.dimensions_for(maze, mode)
super(width, height)
maze.height.times do |y|
length = maze.row_length(y)
length.times do |x|
case mode
when :plain then draw_plain_cell(maze, x, y)
when :unicode then draw_unicode_cell(maze, x, y)
when :lines then draw_line_cell(maze, x, y)
end
end
end
end
private
def draw_plain_cell(maze, x, y) #:nodoc:
c = maze[x, y]
return if c == 0
px, py = x * 2, y
cnw = maze.valid?(x-1,y-1) ? maze[x-1,y-1] : 0
cn = maze.valid?(x,y-1) ? maze[x,y-1] : 0
cne = maze.valid?(x+1,y-1) ? maze[x+1,y-1] : 0
cse = maze.valid?(x+1,y+1) ? maze[x+1,y+1] : 0
cs = maze.valid?(x,y+1) ? maze[x,y+1] : 0
csw = maze.valid?(x-1,y+1) ? maze[x-1,y+1] : 0
if c & Maze::N == 0
self[px, py] = "_" if y == 0 || (cn == 0 && cnw == 0) || cnw & (Maze::E | Maze::S) == Maze::E
self[px+1, py] = "_"
self[px+2, py] = "_" if y == 0 || (cn == 0 && cne == 0) || cne & (Maze::W | Maze::S) == Maze::W
end
if c & Maze::S == 0
bottom = y+1 == maze.height
self[px, py+1] = "_" if bottom || (cs == 0 && csw == 0) || csw & (Maze::E | Maze::N) == Maze::E
self[px+1, py+1] = "_"
self[px+2, py+1] = "_" if bottom || (cs == 0 && cse == 0) || cse & (Maze::W | Maze::N) == Maze::W
end
self[px, py+1] = "|" if c & Maze::W == 0
self[px+2, py+1] = "|" if c & Maze::E == 0
end
UTF8_SPRITES = [
[" ",
" "], # " "
["│ │",
"└─┘"], # "╵" 5
["┌─┐",
"│ │"], # "╷" 6
["│ │",
"│ │"], # "│" 10
["┌──",
"└──"], # "╶" 7
["│ └",
"└──"], # "└"
["┌──",
"│ ┌"], # "┌"
["│ └",
"│ ┌"], # "├" 3
["──┐",
"──┘"], # "╴" 8
["┘ │",
"──┘"], # "┘"
["──┐",
"┐ │"], # "┐"
["┘ │",
"┐ │"], # "┤" 4
["───",
"───"], # "─" 9
["┘ └",
"───"], # "┴" 2
["───",
"┐ ┌"], # "┬" 1
["┘ └",
"┐ ┌"] # "┼" 0
]
def draw_unicode_cell(maze, x, y) #:nodoc:
cx, cy = 3 * x, 2 * y
cell = maze[x, y]
UTF8_SPRITES[cell & Maze::PRIMARY].each_with_index do |row, sy|
row.length.times do |sx|
char = row[sx]
self[cx+sx, cy+sy] = char
end
end
under = cell >> Maze::UNDER_SHIFT
if under & Maze::N != 0
self[cx, cy] = "┴"
self[cx+2, cy] = "┴"
end
if under & Maze::S != 0
self[cx, cy+1] = "┬"
self[cx+2, cy+1] = "┬"
end
if under & Maze::W != 0
self[cx, cy] = "┤"
self[cx, cy+1] = "┤"
end
#road coming from right under bridge
if under & Maze::E != 0
self[cx+2, cy] = "├"
self[cx+2, cy+1] = "├"
end
end
UTF8_LINES = [".", "╵", "╷", "│", "╶", "└", "┌", "├", "╴", "┘", "┐", "┤", "─", "┴", "┬", "┼"]
def draw_line_cell(maze, x, y) #:nodoc:
self[x, y] = UTF8_LINES[maze[x, y] & Maze::PRIMARY]
end
end
end
end
end
module Theseus
module Formatters
class ASCII
# Renders a DeltaMaze to an ASCII representation, using 4 characters
# horizontally and 2 characters vertically to represent a single cell.
#
# __
# /\ /
# /__\/
# /\ /\
# /__\/__\
# /\ /\ /\
# /__\/__\/__\
#
# You shouldn't ever need to instantiate this class directly. Rather, use
# DeltaMaze#to(:ascii) (or DeltaMaze#to_s to get the string directly).
class Delta < ASCII
# Returns a new Delta canvas for the given maze (which should be an
# instance of DeltaMaze). The +options+ parameter is not used.
#
# The returned object will be fully initialized, containing an ASCII
# representation of the given DeltaMaze.
def initialize(maze, options={})
super((maze.width + 1) * 2, maze.height * 2 + 1)
maze.height.times do |y|
py = y * 2
maze.row_length(y).times do |x|
cell = maze[x, y]
next if cell == 0
px = x * 2
if maze.points_up?(x, y)
if cell & Maze::W == 0
self[px+1,py+1] = "/"
self[px,py+2] = "/"
elsif y < 1
self[px+1,py] = "_"
end
if cell & Maze::E == 0
self[px+2,py+1] = "\\"
self[px+3,py+2] = "\\"
elsif y < 1
self[px+2,py] = "_"
end
if cell & Maze::S == 0
self[px+1,py+2] = self[px+2,py+2] = "_"
end
else
if cell & Maze::W == 0
self[px,py+1] = "\\"
self[px+1,py+2] = "\\"
elsif x > 0 && maze[x-1,y] & Maze::S == 0
self[px+1,py+2] = "_"
end
if cell & Maze::E == 0
self[px+3,py+1] = "/"
self[px+2,py+2] = "/"
elsif x < maze.row_length(y) && maze[x+1,y] & Maze::S == 0
self[px+2,py+2] = "_"
end
if cell & Maze::N == 0
self[px+1,py] = self[px+2,py] = "_"
end
end
end
end
end
end
end
end
end
module Theseus
module Formatters
class ASCII
# Renders a SigmaMaze to an ASCII representation, using 3 characters
# horizontally and 3 characters vertically to represent a single cell.
# _ _ _
# / \_/ \_/ \_
# \_/ \_/ \_/ \
# / \_/ \_/ \_/
# \_/ \_/ \_/ \
# / \_/ \_/ \_/
# \_/ \_/ \_/ \
# / \_/ \_/ \_/
# \_/ \_/ \_/ \
#
# You shouldn't ever need to instantiate this class directly. Rather, use
# SigmaMaze#to(:ascii) (or SigmaMaze#to_s to get the string directly).
class Sigma < ASCII
# Returns a new Sigma canvas for the given maze (which should be an
# instance of SigmaMaze). The +options+ parameter is not used.
#
# The returned object will be fully initialized, containing an ASCII
# representation of the given SigmaMaze.
def initialize(maze, options={})
super(maze.width * 2 + 2, maze.height * 2 + 2)
maze.height.times do |y|
py = y * 2
maze.row_length(y).times do |x|
cell = maze[x, y]
next if cell == 0
px = x * 2
shifted = x % 2 != 0
ry = shifted ? py+1 : py
nw = shifted ? Maze::W : Maze::NW
ne = shifted ? Maze::E : Maze::NE
sw = shifted ? Maze::SW : Maze::W
se = shifted ? Maze::SE : Maze::E
self[px+1,ry] = "_" if cell & Maze::N == 0
self[px,ry+1] = "/" if cell & nw == 0
self[px+2,ry+1] = "\\" if cell & ne == 0
self[px,ry+2] = "\\" if cell & sw == 0
self[px+1,ry+2] = "_" if cell & Maze::S == 0
self[px+2,ry+2] = "/" if cell & se == 0
end
end
end
end
end
end
end
module Theseus
# Theseus::Maze is an abstract class, intended to act solely as a superclass
# for specific maze types. Subclasses include OrthogonalMaze, DeltaMaze,
# SigmaMaze, and UpsilonMaze.
#
# Each cell in the maze is a bitfield. The bits that are set indicate which
# passages exist leading AWAY from this cell. Bits in the low byte (corresponding
# to the PRIMARY bitmask) represent passages on the normal plane. Bits
# in the high byte (corresponding to the UNDER bitmask) represent passages
# that are passing under this cell. (Under/over passages are controlled via the
# #weave setting, and are not supported by all maze types.)
class Maze
N = 0x01 # North
S = 0x02 # South
E = 0x04 # East
W = 0x08 # West
NW = 0x10 # Northwest
NE = 0x20 # Northeast
SW = 0x40 # Southwest
SE = 0x80 # Southeast
# bitmask identifying directional bits on the primary plane
PRIMARY = 0x000000FF
# bitmask identifying directional bits under the primary plane
UNDER = 0x0000FF00
# bits reserved for use by individual algorithm implementations
RESERVED = 0xFFFF0000
# The size of the PRIMARY bitmask (e.g. how far to the left the
# UNDER bitmask is shifted).
UNDER_SHIFT = 8
# The algorithm object used to generate this maze. Defaults to
# an instance of Algorithms::RecursiveBacktracker.
attr_reader :algorithm
# The width of the maze (number of columns).
#
# In general, it is safest to use the #row_length method for a particular
# row, since it is theoretically possible for a maze subclass to describe
# a different width for each row.
attr_reader :width
# The height of the maze (number of rows).
attr_reader :height
# An integer between 0 and 100 (inclusive). 0 means passages will only
# change direction when they encounter a barrier they cannot move through
# (or under). 100 means that as passages are built, a new direction will
# always be randomly chosen for each step of the algorithm.
attr_reader :randomness
# An integer between 0 and 100 (inclusive). 0 means passages will never
# move over or under existing passages. 100 means whenever possible,
# passages will move over or under existing passages. Note that not all
# maze types support weaving.
attr_reader :weave
# An integer between 0 and 100 (inclusive), signifying the percentage
# of deadends in the maze that will be extended in some direction until
# they join with an existing passage. This will create loops in the
# graph. Thus, 0 is a "perfect" maze (with no loops), and 100 is a
# maze that is totally multiply-connected, with no dead-ends.
attr_reader :braid
# One of :none, :x, :y, or :xy, indicating which boundaries the maze
# should wrap around. The default is :none, indicating no wrapping.
# If :x, the maze will wrap around the left and right edges. If
# :y, the maze will wrap around the top and bottom edges. If :xy, the
# maze will wrap around both edges.
#
# A maze that wraps in a single direction may be mapped onto a cylinder.
# A maze that wraps in both x and y may be mapped onto a torus.
attr_reader :wrap
# A Theseus::Mask (or similar) instance, that is used by the algorithm to
# determine which cells in the space are allowed. This lets you create
# mazes that fill shapes, or flow around patterns.
attr_reader :mask
# One of :none, :x, :y, :xy, or :radial. Note that not all maze types
# support symmetry. The :x symmetry means the maze will be mirrored
# across the x axis. Similarly, :y symmetry means the maze will be
# mirrored across the y axis. :xy symmetry causes the maze to be
# mirrored across both axes, and :radial symmetry causes the maze to
# be mirrored radially about the center of the maze.
attr_reader :symmetry
# A 2-tuple (array) indicating the x and y coordinates where the maze
# should be entered. This is used primarly when generating the solution
# to the maze, and generally defaults to the upper-left corner.
attr_reader :entrance
# A 2-tuple (array) indicating the x and y coordinates where the maze
# should be exited. This is used primarly when generating the solution
# to the maze, and generally defaults to the lower-right corner.
attr_reader :exit
# A short-hand method for creating a new maze object and causing it to
# be generated, in one step. Returns the newly generated maze.
def self.generate(options={})
new(options).generate!
end
# Creates and returns a new maze object. Note that the maze will _not_
# be generated; the maze is initially blank.
#
# Many options are supported:
#
# [:width] The number of columns in the maze. Note that different
# maze types count columns and rows differently; you'll
# want to see individual maze types for more info.
# [:height] The number of rows in the maze.
# [:algorithm] The maze algorithm to use. This should be a class,
# adhering to the interface described by Theseus::Algorithms::Base.
# It defaults to Theseus::Algorithms::RecursiveBacktracker.
# [:symmetry] The symmetry to be used when generating the maze. This
# defaults to +:none+, but may also be +:x+ (to have the
# maze mirrored across the x-axis), +:y+ (to mirror the
# maze across the y-axis), +:xy+ (to mirror across both
# axes simultaneously), and +:radial+ (to mirror the maze
# radially about the center). Some symmetry types may
# result in loops being added to the maze, regardless of
# the braid value (see the +:braid+ parameter).
# (NOTE: not all maze types support symmetry equally.)
# [:randomness] An integer between 0 and 100 (inclusive) indicating how
# randomly the maze is generated. A 0 means that the maze
# passages will prefer to go straight whenever possible.
# A 100 means the passages will choose random directions
# as often as possible.
# [:mask] An instance of Theseus::Mask (or something that acts
# similarly). This can be used to constrain the maze so that
# it fills or avoids specific areas, so that shapes and
# patterns can be made. (NOTE: not all algorithms support
# masks.)
# [:weave] An integer between 0 and 100 (inclusive) indicating how
# frequently passages move under or over other passages.
# A 0 means the passages will never move over/under other
# passages, while a 100 means they will do so as often
# as possible. (NOTE: not all maze types and algorithms
# support weaving.)
# [:braid] An integer between 0 and 100 (inclusive) representing
# the percentage of dead-ends that should be removed after
# the maze has been generated. Dead-ends are removed by
# extending them in some direction until they join with
# another passage. This will introduce loops into the maze,
# making it "multiply-connected". A braid value of 0 will
# always result in a "perfect" maze (with no loops), while
# a value of 100 will result in a maze with no dead-ends.
# [:wrap] Indicates which edges of the maze should wrap around.
# +:x+ will cause the left and right edges to wrap, and
# +:y+ will cause the top and bottom edges to wrap. You
# can specify +:xy+ to wrap both left-to-right and
# top-to-bottom. The default is +:none+ (for no wrapping).
# [:entrance] A 2-tuple indicating from where the maze is entered.
# By default, the maze's entrance will be the upper-left-most
# point. Note that it may lie outside the bounds of the maze
# by one cell (e.g. [-1,0]), indicating that the entrance
# is on the very edge of the maze.
# [:exit] A 2-tuple indicating from where the maze is exited.
# By default, the maze's entrance will be the lower-right-most
# point. Note that it may lie outside the bounds of the maze
# by one cell (e.g. [width,height-1]), indicating that the
# exit is on the very edge of the maze.
# [:prebuilt] Sometimes, you may want the new maze to be considered to be
# generated, but not actually have anything generated into it.
# You can set the +:prebuilt+ parameter to +true+ in this case,
# allowing you to then set the contents of the maze by hand,
# using the #[]= method.
def initialize(options={})
@deadends = nil
@width = (options[:width] || 10).to_i
@height = (options[:height] || 10).to_i
@symmetry = (options[:symmetry] || :none).to_sym
configure_symmetry
@randomness = options[:randomness] || 100
@mask = options[:mask] || TransparentMask.new
@weave = options[:weave] || 0
@braid = options[:braid] || 0
@wrap = options[:wrap] || :none
@cells = setup_grid or raise "expected #setup_grid to return the new grid"
@entrance = options[:entrance] || default_entrance
@exit = options[:exit] || default_exit
algorithm_class = options[:algorithm] || Algorithms::RecursiveBacktracker
@algorithm = algorithm_class.new(self, options)
@generated = options[:prebuilt]
end
# Generates the maze if it has not already been generated. This is
# essentially the same as calling #step repeatedly. If a block is given,
# it will be called after each step.
def generate!
yield if block_given? while step unless generated?
self
end
# Creates a new Theseus::Path object based on this maze instance. This can
# be used to (for instance) create special areas of the maze or routes through
# the maze that you want to color specially. The following demonstrates setting
# a particular cell in the maze to a light-purple color:
#
# path = maze.new_path(color: 0xff7fffff)
# path.set([5,5])
# maze.to(:png, paths: [path])
def new_path(meta={})
Path.new(self, meta)
end
# Instantiates and returns a new solver instance which encapsulates a
# solution algorithm. The options may contain the following keys:
#
# [:type] This defaults to +:backtracker+ (for the Theseus::Solvers::Backtracker
# solver), but may also be set to +:astar+ (for the Theseus::Solvers::Astar
# solver).
# [:a] A 2-tuple (defaulting to #start) that says where in the maze the
# solution should begin.
# [:b] A 2-tuple (defaulting to #finish) that says where in the maze the
# solution should finish.
#
# The returned solver will not yet have generated the solution. Use
# Theseus::Solvers::Base#solve or Theseus::Solvers::Base#step to generate the
# solution.
def new_solver(options={})
type = options[:type] || :backtracker
require "theseus/solvers/#{type}"
klass = Theseus::Solvers.const_get(type.to_s.capitalize)
a = options[:a] || start
b = options[:b] || finish
klass.new(self, a, b)
end
# Returns the solution for the maze as an array of 2-tuples, each indicating
# a cell (in sequence) leading from the start to the finish.
#
# See #new_solver for a description of the supported options.
def solve(options={})
new_solver(options).solution
end
# Returns the bitfield for the cell at the given (+x+,+y+) coordinate.
def [](x,y)
@cells[y][x]
end
# Sets the bitfield for the cell at the given (+x+,+y+) coordinate.
def []=(x,y,value)
@cells[y][x] = value
end
# Completes a single iteration of the maze generation algorithm. Returns
# +false+ if the method should not be called again (e.g., the maze has
# been completed), and +true+ otherwise.
def step
return false if @generated
if @deadends && @deadends.any?
dead_end = @deadends.pop
braid_cell(dead_end[0], dead_end[1])
@generated = @deadends.empty?
return !@generated
end
if @algorithm.step
return true
else
return finish!
end
end
# Returns +true+ if the maze has been generated.
def generated?
@generated
end
# Since #entrance may be external to the maze, #start returns the cell adjacent to
# #entrance that lies within the maze. If #entrance is already internal to the
# maze, this method returns #entrance. If #entrance is _not_ adjacent to any
# internal cell, this method returns +nil+.
def start
adjacent_point(@entrance)
end
# Since #exit may be external to the maze, #finish returns the cell adjacent to
# #exit that lies within the maze. If #exit is already internal to the
# maze, this method returns #exit. If #exit is _not_ adjacent to any
# internal cell, this method returns +nil+.
def finish
adjacent_point(@exit)
end
# Returns an array of the possible exits for the cell at the given coordinates.
# Note that this does not take into account boundary conditions: a move in any
# of the returned directions may not actually be valid, and should be verified
# before being applied.
#
# This is used primarily by subclasses to allow for different shaped cells
# (e.g. hexagonal cells for SigmaMaze, octagonal cells for UpsilonMaze).
def potential_exits_at(x, y)
raise NotImplementedError, "subclasses must implement #potential_exits_at"
end
# Returns true if the maze may be wrapped in the x direction (left-to-right).
def wrap_x?
@wrap == :x || @wrap == :xy
end
# Returns true if the maze may be wrapped in the y direction (top-to-bottom).
def wrap_y?
@wrap == :y || @wrap == :xy
end
# Returns true if the given coordinates are valid within the maze. This will
# be the case if:
#
# 1. The coordinates lie within the maze's bounds, and
# 2. The current mask for the maze does not restrict the location.
#
# If the maze wraps in x, the x coordinate is unconstrained and will be
# mapped (via modulo) to the bounds. Similarly, if the maze wraps in y,
# the y coordinate will be unconstrained.
def valid?(x, y)
return false if !wrap_y? && (y < 0 || y >= height)
y %= height
return false if !wrap_x? && (x < 0 || x >= row_length(y))
x %= row_length(y)
return @mask[x, y]
end
# Moves the given (+x+,+y+) coordinates a single step in the given
# +direction+. If wrapping in either x or y is active, the result will
# be mapped to the maze's current bounds via modulo arithmetic. The
# resulting coordinates are returned as a 2-tuple.
#
# Example:
#
# x2, y2 = maze.move(x, y, Maze::W)
def move(x, y, direction)
nx, ny = x + dx(direction), y + dy(direction)
ny %= height if wrap_y?
nx %= row_length(ny) if wrap_x? && ny > 0 && ny < height
[nx, ny]
end
# Returns a array of all dead-ends in the maze. Each element of the array
# is a 2-tuple containing the coordinates of a dead-end.
def dead_ends
dead_ends = []
@cells.each_with_index do |row, y|
row.each_with_index do |cell, x|
dead_ends << [x, y] if dead?(cell)
end
end
dead_ends
end
# Removes one cell from all dead-ends in the maze. Each call to this method
# removes another level of dead-ends, making the maze increasingly sparse.
def sparsify!
dead_ends.each do |(x, y)|
cell = @cells[y][x]
direction = cell & PRIMARY
nx, ny = move(x, y, direction)
# if the cell includes UNDER codes, shifting it all UNDER_SHIFT bits to the right
# will convert those UNDER codes to PRIMARY codes. Otherwise, it will
# simply zero the cell, resulting in a blank spot.
@cells[y][x] >>= UNDER_SHIFT
# if it's a weave cell (that moves over or under another corridor),
# nix it and move back one more, so we don't wind up with dead-ends
# underneath another corridor.
if @cells[ny][nx] & (opposite(direction) << UNDER_SHIFT) != 0
@cells[ny][nx] &= ~((direction | opposite(direction)) << UNDER_SHIFT)
nx, ny = move(nx, ny, direction)
end
@cells[ny][nx] &= ~opposite(direction)
end
end
# Returns the direction opposite to the given +direction+. This will work
# even if the +direction+ value is in the UNDER bitmask.
def opposite(direction)
if direction & UNDER != 0
opposite(direction >> UNDER_SHIFT) << UNDER_SHIFT
else
case direction
when N then S
when S then N
when E then W
when W then E
when NE then SW
when NW then SE
when SE then NW
when SW then NE
end
end
end
# Returns the direction that is the horizontal mirror to the given +direction+.
# This will work even if the +direction+ value is in the UNDER bitmask.
def hmirror(direction)
if direction & UNDER != 0
hmirror(direction >> UNDER_SHIFT) << UNDER_SHIFT
else
case direction
when E then W
when W then E
when NW then NE
when NE then NW
when SW then SE
when SE then SW
else direction
end
end
end
# Returns the direction that is the vertical mirror to the given +direction+.
# This will work even if the +direction+ value is in the UNDER bitmask.
def vmirror(direction)
if direction & UNDER != 0
vmirror(direction >> UNDER_SHIFT) << UNDER_SHIFT
else
case direction
when N then S
when S then N
when NE then SE
when NW then SW
when SE then NE
when SW then NW
else direction
end
end
end
# Returns the direction that results by rotating the given +direction+
# 90 degrees in the clockwise direction. This will work even if the +direction+
# value is in the UNDER bitmask.
def clockwise(direction)
if direction & UNDER != 0
clockwise(direction >> UNDER_SHIFT) << UNDER_SHIFT
else
case direction
when N then E
when E then S
when S then W
when W then N
when NW then NE
when NE then SE
when SE then SW
when SW then NW
end
end
end
# Returns the direction that results by rotating the given +direction+
# 90 degrees in the counter-clockwise direction. This will work even if
# the +direction+ value is in the UNDER bitmask.
def counter_clockwise(direction)
if direction & UNDER != 0
counter_clockwise(direction >> UNDER_SHIFT) << UNDER_SHIFT
else
case direction
when N then W
when W then S
when S then E
when E then N
when NW then SW
when SW then SE
when SE then NE
when NE then NW
end
end
end
# Returns the change in x implied by the given +direction+.
def dx(direction)
case direction
when E, NE, SE then 1
when W, NW, SW then -1
else 0
end
end
# Returns the change in y implied by the given +direction+.
def dy(direction)
case direction
when S, SE, SW then 1
when N, NE, NW then -1
else 0
end
end
# Returns the number of cells in the given row. This is generally safer
# than relying the #width method, since it is theoretically possible for
# a maze to have a different number of cells for each of its rows.
def row_length(row)
@cells[row].length
end
# Returns +true+ if the given cell is a dead-end. This considers only
# passages on the PRIMARY plane (the UNDER bits are ignored, because the
# current algorithm for generating mazes will never result in a dead-end
# that is underneath another passage).
def dead?(cell)
raw = cell & PRIMARY
raw == N || raw == S || raw == E || raw == W ||
raw == NE || raw == NW || raw == SE || raw == SW
end
# If +point+ is already located at a valid point within the maze, this
# does nothing. Otherwise, it examines the potential exits from the
# given point and looks for the first one that leads immediately to a
# valid point internal to the maze. When it finds one, it adds a passage
# to that cell leading to +point+. If no such adjacent cell exists, this
# method silently does nothing.
def add_opening_from(point)
x, y = point
if valid?(x, y)
# nothing to be done
else
potential_exits_at(x, y).each do |direction|
nx, ny = move(x, y, direction)
if valid?(nx, ny)
@cells[ny][nx] |= opposite(direction)
return
end
end
end
end
# If +point+ is already located at a valid point withint he maze, this
# simply returns +point+. Otherwise, it examines the potential exits
# from the given point and looks for the first one that leads immediately
# to a valid point internal to the maze. When it finds one, it returns
# that point. If no such point exists, it returns +nil+.
def adjacent_point(point)
x, y = point
if valid?(x, y)
point
else
potential_exits_at(x, y).each do |direction|
nx, ny = move(x, y, direction)
return [nx, ny] if valid?(nx, ny)
end
end
end
# Returns the direction of +to+ relative to +from+. +to+ and +from+
# are both points (2-tuples).
def relative_direction(from, to)
# first, look for the case where the maze wraps, and from and to
# are on opposite sites of the grid.
if wrap_x? && from[1] == to[1] && (from[0] == 0 || to[0] == 0) && (from[0] == @width-1 || to[0] == @width-1)
if from[0] < to[0]
W
else
E
end
elsif wrap_y? && from[0] == to[0] && (from[1] == 0 || to[1] == 0) && (from[1] == @height-1 || to[1] == @height-1)
if from[1] < to[1]
N
else
S
end
elsif from[0] < to[0]
if from[1] < to[1]
SE
elsif from[1] > to[1]
NE
else
E
end
elsif from[0] > to[0]
if from[1] < to[1]
SW
elsif from[1] > to[1]
NW
else
W
end
elsif from[1] < to[1]
S
elsif from[1] > to[1]
N
else
# same point!
nil
end
end
# Applies a move in the given direction to the cell at (x,y). The +direction+
# parameter may also be :under, in which case the cell is left-shifted so as
# to move the existing passages to the UNDER plane.