-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGridWorld.scala
64 lines (53 loc) · 1.92 KB
/
GridWorld.scala
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
import scala.collection.mutable
import scala.io.StdIn
class GridWorld(rows: Int, cols: Int) {
val maxRows: Int = rows - 1
val maxCols: Int = cols - 1
var robot: Robot = _ // forward declare robot variable
// world array
val world: Array[Array[Char]] = Array.ofDim[Char](rows, cols)
// populate world and make robot
def make(): Robot = {
var dirt: mutable.Set[Int] = mutable.Set() // keep track of goal locations
// populate world array
var r = 0
while (r < rows) {
val row = StdIn.readLine()
var c = 0
for (col <- row) {
if (col == '@') { // robot start pos
if (robot != null) // already have a start pos
throw new IllegalStateException(
"Multiple robot start positions found")
robot = new Robot(r, c, this)
world(r)(c) = '_' // add empty space under robot
} else world(r)(c) = col // add entry into world
if (col == '*') dirt += r * (maxCols+1) + c // add goal to set
c += 1
}
r += 1
}
if (robot != null) { robot.goal = dirt; robot }
else throw new IllegalStateException("No robot start position found")
}
// print initial world and size
def print(): Unit = {
if (robot == null) println("Cannot print world: world not made yet!")
else {
// Print world size
println("size: " + cols + "x" + rows)
// print world
for (r <- 0 until rows) {
var row = ""
for (c <- 0 until cols)
if (robot.currRow == r && robot.currCol == c) row += "@" + " " // check for robot
else if (world(r)(c) == '*' &&
!robot.goal(r * (maxCols+1) + c)) row += "_" + " " // check if goal visited
else row += world(r)(c) + " "
println(row)
}
}
}
// returns the contents of the selected cell
def apply(row: Int, col: Int): Char = world(row)(col)
}