From cff0b04e9092613ee24a6a291ba42c086b65c7c8 Mon Sep 17 00:00:00 2001 From: Noah Loomans Date: Sun, 22 Apr 2018 14:51:02 +0200 Subject: Create MazeSolver --- maze_solver.rb | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 maze_solver.rb (limited to 'maze_solver.rb') diff --git a/maze_solver.rb b/maze_solver.rb new file mode 100644 index 0000000..d529495 --- /dev/null +++ b/maze_solver.rb @@ -0,0 +1,38 @@ +require_relative 'pos' +require_relative 'maze' + +class MazeSolver + attr_reader :maze + attr_reader :stack + + def initialize(maze, start_pos, end_pos) + @maze = maze + @start_pos = start_pos + @end_pos = end_pos + @stack = [start_pos] + @visitedTiles = Array.new(@maze.width) { Array.new(@maze.height) { false } } + end + + def solve!() + while @stack.last != @end_pos + step() + end + end + + def step() + current_tile = @stack.last + + neighbors = @maze.open_neighbors(current_tile) + neighbors.select! do |neighbor| + @visitedTiles[neighbor.x][neighbor.y] == false + end + + if neighbors.empty? + @stack.pop() + else + randomNeighbor = neighbors.sample + @stack.push(randomNeighbor) + @visitedTiles[randomNeighbor.x][randomNeighbor.y] = true + end + end +end -- cgit v1.1