diff options
author | Noah Loomans <noahloomans@gmail.com> | 2018-04-22 14:51:02 +0200 |
---|---|---|
committer | Noah Loomans <noahloomans@gmail.com> | 2018-04-22 14:51:02 +0200 |
commit | cff0b04e9092613ee24a6a291ba42c086b65c7c8 (patch) | |
tree | a3e5687e4ea457f0f7e6cc57a20cc15cfdba60c5 /maze_solver.rb | |
parent | 98ddcffd5264e355fb6d651d18be9b51c34ae544 (diff) |
Create MazeSolver
Diffstat (limited to 'maze_solver.rb')
-rw-r--r-- | maze_solver.rb | 38 |
1 files changed, 38 insertions, 0 deletions
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 |