comparison wilsons.rb @ 0:1eef88068f9f tip

initial commit of maze game source
author ferencd
date Sun, 15 Sep 2019 11:46:47 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:1eef88068f9f
1 #---
2 # Excerpted from "Mazes for Programmers",
3 # published by The Pragmatic Bookshelf.
4 # Copyrights apply to this code. It may not be used to create training material,
5 # courses, books, articles, and the like. Contact us if you are in doubt.
6 # We make no guarantees that this code is fit for any purpose.
7 # Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information.
8 #---
9 class Wilsons
10
11 def on(grid)
12 unvisited = []
13 grid.each_cell { |cell| unvisited << cell }
14
15 first = unvisited.sample
16 unvisited.delete(first)
17
18 while unvisited.any?
19 cell = unvisited.sample
20 path = [cell]
21
22 while unvisited.include?(cell)
23 cell = cell.neighbors.sample
24 position = path.index(cell)
25 if position
26 path = path[0..position]
27 else
28 path << cell
29 end
30 end
31
32 0.upto(path.length-2) do |index|
33 path[index].link(path[index + 1])
34 unvisited.delete(path[index])
35 end
36 end
37
38 grid
39 end
40
41 end