forked from CoderAcademyEdu/morning-challenges-term1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path27_maze.rb
46 lines (42 loc) · 1.65 KB
/
27_maze.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
require 'matrix'
class Maze
# List of valid moves, each mapped to a row and column offset hash
# eg. moving north means going up one row (-1 rows, 0 columns) in the maze array
@@valid_moves = {
'N': { row: -1, col: 0 },
'S': { row: 1, col: 0 },
'E': { row: 0, col: 1 },
'W': { row: 0, col: -1 }
}
def initialize(maze)
@maze = maze
# Find the start location (element with value 2)
# First find the row that includes the value 2
start_row = maze.find { |row| row.include?(2) }
# Construct player position hash from column and row indexes
@player_position = { col: start_row.index(2), row: maze.index(start_row) }
end
def walk(moves)
for move in moves do
# Convert move to symbol so we can use it to reference @@valid_moves
move = move.to_sym
# Ignore invalid moves
if @@valid_moves[move]
# Adjust the player position according to the direction moved
@player_position[:col] += @@valid_moves[move][:col]
@player_position[:row] += @@valid_moves[move][:row]
# Get the value at the new location in the maze
# This will fail if we're outside the maze, triggering the rescue clause
value = @maze[@player_position[:row]][@player_position[:col]]
# Hit a wall?
return 'Dead' if value == 1
# Reached the exit?
return 'Finish' if value == 3
end
end
# If we didn't finish or die, then we're lost!
'Lost'
rescue
'Dead'
end
end