Browse Source

actually adding sidewinder

john melesky 3 years ago
parent
commit
6b993a04c7
5 changed files with 79 additions and 2 deletions
  1. 5 2
      README.md
  2. 4 0
      src/binary_tree_demo.rb
  3. 26 0
      src/grid.rb
  4. 34 0
      src/sidewinder.rb
  5. 10 0
      src/sidewinder_demo.rb

+ 5 - 2
README.md

@@ -1,3 +1,6 @@
-# mazes_for_programmers
+# Mazes for Programmers
+
+Following the [Mazes for Programmers book](http://www.mazesforprogrammers.com/), by Jamis Buck
+
+Requires gem `chunky_png`
 
-following the Mazes for Programmers book, by Jamis Buck

+ 4 - 0
src/binary_tree_demo.rb

@@ -6,3 +6,7 @@ BinaryTree.on(grid)
 
 puts grid
 
+img = grid.to_png
+img.save "maze_binary_tree.png"
+
+

+ 26 - 0
src/grid.rb

@@ -1,3 +1,4 @@
+require 'chunky_png'
 require 'cell'
 
 class Grid
@@ -87,4 +88,29 @@ class Grid
     output
   end
 
+  def to_png(cell_size: 10)
+    img_width  = cell_size * columns
+    img_height = cell_size * rows
+
+    background = ChunkyPNG::Color::WHITE
+    wall = ChunkyPNG::Color::BLACK
+
+    img = ChunkyPNG::Image.new(img_width+1, img_height+1, background)
+
+    each_cell do |cell|
+      x1 = cell.column * cell_size
+      y1 = cell.row * cell_size
+      x2 = (cell.column + 1) * cell_size
+      y2 = (cell.row + 1) * cell_size
+
+      img.line(x1, y1, x2, y1, wall) unless cell.north
+      img.line(x1, y1, x1, y2, wall) unless cell.west
+
+      img.line(x2, y1, x2, y2, wall) unless cell.linked?(cell.east)
+      img.line(x1, y2, x2, y2, wall) unless cell.linked?(cell.south)
+    end
+
+    img
+  end
+
 end

+ 34 - 0
src/sidewinder.rb

@@ -0,0 +1,34 @@
+class Sidewinder
+
+  def self.on(grid)
+    grid.each_row do |row|
+
+      run = []
+
+      row.each do |cell|
+        run << cell
+
+        at_eastern_boundary = (cell.east == nil)
+        at_northern_boundary = (cell.north == nil)
+
+        should_close_out =
+          at_eastern_boundary ||
+          (!at_northern_boundary && rand(2) == 0)
+
+        if should_close_out
+          member = run.sample
+          member.link(member.north) if member.north
+          run.clear
+        else
+          cell.link(cell.east)
+        end
+
+      end
+
+    end
+
+    grid
+  end
+
+end
+

+ 10 - 0
src/sidewinder_demo.rb

@@ -0,0 +1,10 @@
+require 'grid'
+require 'sidewinder'
+
+grid = Grid.new(19,19)
+
+Sidewinder.on(grid)
+
+puts grid
+
+