Module: MazeSolver

Defined in:
lib/maze_solver.rb,
lib/maze_solver/maze.rb,
lib/maze_solver/tree.rb,
lib/maze_solver/element.rb,
lib/maze_solver/version.rb,
lib/maze_solver/position.rb

Defined Under Namespace

Classes: Element, Maze, Position, Tree

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.from_file(file_name) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/maze_solver.rb', line 42

def from_file(file_name)
  ## Read file and export it to a 2D array
  ## Throw error if file doesnt exist

  begin
    File.readlines(file_name).map { |line| line.split('') }
  rescue abort("can't open #{file_name}" )
  end
end

.to_image(file_name) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/maze_solver.rb', line 25

def to_image(file_name)
  ## Print solution to console
  maze_array = from_file(file_name)
  maze_list = to_maze(maze_array)
  maze = Maze.new(maze_list)
  solution = maze.solve

  maze_list.each do |element|
    maze_array[element.position.y][element.position.x] = '*' if solution.find { |se| se == element }
  end

  puts '!!!!!!!SOLUTIOM!!!!!!!'
  print maze_array.join('')

  nil
end

.to_json(file_name) ⇒ Object

Better to implemented on a class after thoughts.…..Anyway..mabe later!!!



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/maze_solver.rb', line 11

def to_json(file_name)
  
  maze_array = from_file(file_name)
  maze_list = to_maze(maze_array)
  maze = Maze.new(maze_list)
  solution = maze.solve

  solution_array = solution.map do |element|
    { value: element.value, position: "(#{element.position.x}, #{element.position.y})" }
  end

  JSON.generate(solution_array)
end

.to_maze(maze_array) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/maze_solver.rb', line 52

def to_maze(maze_array)
  maze = []  
  maze_array.each_with_index do |line, line_index|
    line.each_with_index do |char, col_index|
      case char
        when '_' 
          then maze << Element.new(char, Position.new(col_index, line_index,), 'PATH')
        when 'X'
          then maze << Element.new(char, Position.new(col_index, line_index,), 'WALL')
        when 'S'
          then maze << Element.new(char, Position.new(col_index, line_index,), 'START')
        when 'G'
          then maze <<  Element.new(char, Position.new(col_index, line_index,), 'GOAL' )
      end
    end
  end
  maze
end