Last active
March 4, 2018 18:37
-
-
Save jonatas/53222ae118a4a8f94cc9a5f4bb9e699c to your computer and use it in GitHub Desktop.
Simple maze solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
game = <<~MAZE | |
++++++++++++++++++++++ | |
+ + ++ ++ + | |
+ + + +++ + ++ | |
+ + + ++ ++++ + ++ | |
+++ ++++++ +++ + + | |
+ ++ ++ + | |
+++++ ++++++ +++++ + | |
+ + +++++++ + + | |
+ +++++++ S + + | |
+ + +++ | |
++++++++++++++++++ +++ | |
MAZE | |
BRICK = '💠' | |
SPACE = '⚪' | |
TRIED = '⚫' | |
TURTLE = '🐢' | |
BAD = '🔴' | |
GOOD = '🔵' | |
class Game | |
attr_accessor :start_row, :start_col, :maze | |
def initialize(board) | |
@maze = [] | |
board.lines.map(&:chomp).each_with_index.map do |line, x| | |
@maze[x] = [] | |
line.chars.each_with_index.map do |char, y| | |
@maze[x][y] = | |
if char == 'S' | |
@start_row, @start_col = x, y | |
TURTLE | |
elsif char == '+' | |
BRICK | |
else | |
char | |
end | |
end | |
end | |
@width = @maze.first.size | |
@height = @maze.size | |
end | |
def update_position(x, y,value: nil) | |
if value | |
@maze[x][y] = value | |
end | |
print_board x,y | |
end | |
def exit?(x,y) | |
x == 0 || | |
y == 0 || | |
x == @height-1 || | |
y == @width - 1 | |
end | |
def print_board _x, _y | |
puts "\e[H\e[2J" | |
all_good = 0 | |
(0..@height-1).each do |x| | |
(0..@width-1).each do |y| | |
label = | |
if _x == x && _y == y | |
TURTLE | |
elsif exit?(x, y) && @maze[x][y] == GOOD | |
all_good += 1 | |
'🏁' | |
else | |
@maze[x][y] | |
end | |
print label | |
end | |
print "\n" | |
end | |
sleep 0.01 | |
if all_good == 2 | |
exit | |
end | |
end | |
end | |
def search_from(game, x, y) | |
puts "search from #{x} #{y}" | |
game.update_position(x, y) | |
if [BAD, BRICK, TRIED].include?(game.maze[x][y]) | |
return false | |
else | |
if game.exit? x, y | |
game.update_position x, y, value: GOOD | |
puts "You Won!!" | |
return true | |
end | |
game.update_position x, y, value: TRIED | |
end | |
if [search_from(game, x-1,y), | |
search_from(game, x+1,y), | |
search_from(game, x, y+1), | |
search_from(game, x, y-1)].find(true) | |
game.update_position x, y, value: GOOD | |
return true | |
else | |
game.update_position x, y, value: BAD | |
return false | |
end | |
end | |
g = Game.new(game) | |
search_from(g, g.start_row, g.start_col) | |
sleep 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment