annotate wilsons.rb @ 0:1eef88068f9f tip

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