forked from CoderAcademy-BRI/ruby-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38_maze.rb
More file actions
87 lines (75 loc) · 2.3 KB
/
Copy path38_maze.rb
File metadata and controls
87 lines (75 loc) · 2.3 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Maze Runner
# Introduction
# Welcome Adventurer. Your aim is to navigate the maze and reach the finish point without
# touching any walls. Doing so will kill you instantly!
# Task
# You will be given a 2D array of the maze and an array of directions.
# Your task is to follow the directions given.
# If you reach the end point before all your moves have gone, you should return Finish.
# If you hit any walls or go outside the maze border, you should return Dead.
# If you find yourself still in the maze after using all the moves, you should return Lost.
# The Maze array will look like
# maze = [[1,1,1,1,1,1,1],
# [1,0,0,0,0,0,3],
# [1,0,1,0,1,0,1],
# [0,0,1,0,0,0,1],
# [1,0,1,0,1,0,1],
# [1,0,0,0,0,0,1],
# [1,2,1,0,1,0,1]]
# ..with the following key
# 0 = Safe place to walk
# 1 = Wall
# 2 = Start Point
# 3 = Finish Point
# Rules
# 1. The Maze array will always be square i.e. N x N
# 2. The start and finish positions could be anywhere in the maze
# 3. The directions array will always be in upper case and will be in the format of:
# N = North, E = East, W = West and S = South. (North is assumed to be the top)
# Good luck, and stay safe!
class Maze
def initialize(maze)
@maze = maze
y = 0
maze.each do |row|
x = 0
row.each do |point|
@startpos = [y, x] if point == 2
x += 1
end
y += 1
end
end
def walk(moves)
pos = @startpos
for move in moves
case move
when "N"
pos[0] -= 1
when "S"
pos[0] += 1
when "E"
pos[1] += 1
when "W"
pos[1] -= 1
end
case @maze[pos[0]][pos[1]]
when 3
return "Finish"
when 1
return "Dead"
when nil
return "Dead"
end
end
return "Lost"
end
end
# maze = [[1,1,1,1,1,1,1],
# [1,0,0,0,0,0,3],
# [1,0,1,0,1,0,1],
# [0,0,1,0,0,0,1],
# [1,0,1,0,1,0,1],
# [1,0,0,0,0,0,1],
# [1,2,1,0,1,0,1]]
# testmaze = Maze.new(maze)