exercism/go/robot-simulator/robot.go

149 lines
2.3 KiB
Go

package robot
import "fmt"
const testVersion = 3
// Stuff added for step 1
const (
N = iota
E
S
W
ErrDir
)
func Advance() {
switch Step1Robot.Dir {
case N:
Step1Robot.Y++
case E:
Step1Robot.X++
case S:
Step1Robot.Y--
case W:
Step1Robot.X--
}
}
func Left() {
switch Step1Robot.Dir {
case N:
Step1Robot.Dir = W
case E:
Step1Robot.Dir = N
case S:
Step1Robot.Dir = E
case W:
Step1Robot.Dir = S
}
}
func Right() {
switch Step1Robot.Dir {
case N:
Step1Robot.Dir = E
case E:
Step1Robot.Dir = S
case S:
Step1Robot.Dir = W
case W:
Step1Robot.Dir = N
}
}
func (d Dir) String() string {
switch d {
case N:
return "N"
case E:
return "E"
case S:
return "S"
default:
return "W"
}
}
// Stuff added for step 2
type Action byte
func StartRobot(cmd chan Command, act chan Action) {
fmt.Println("Starting Robot")
for {
fmt.Println("Waiting for command")
j, more := <-cmd
fmt.Println("Received a Command:", j)
if more {
// Received a command, try to act in the room
act <- Action(j)
}
}
fmt.Println("Robot Done")
}
func Room(extent Rect, robot Step2Robot, act chan Action, rep chan Step2Robot) {
fmt.Println("Starting Room")
for {
j, more := <-act
if more {
// Received an action, try to perform it
if j == 'R' { // Turn Right
switch robot.Dir {
case N:
robot.Dir = E
case E:
robot.Dir = S
case S:
robot.Dir = W
case W:
robot.Dir = N
}
} else if j == 'L' { // Turn Left
switch robot.Dir {
case N:
robot.Dir = W
case E:
robot.Dir = N
case S:
robot.Dir = E
case W:
robot.Dir = S
}
} else if j == 'A' { // Advance
switch robot.Dir {
case N:
if robot.Pos.Northing < extent.Max.Northing {
robot.Pos.Northing++
} else {
fmt.Println("Hit North Wall")
}
case E:
if robot.Pos.Easting < extent.Max.Easting {
robot.Pos.Easting++
} else {
fmt.Println("Hit East Wall")
}
case S:
if robot.Pos.Northing > extent.Min.Northing {
robot.Pos.Northing--
} else {
fmt.Println("Hit South Wall")
}
case W:
if robot.Pos.Easting > extent.Min.Easting {
robot.Pos.Easting--
} else {
fmt.Println("Hit West Wall")
}
}
}
} else {
// Done, report back
rep <- robot
}
}
close(rep)
fmt.Println("Room Done")
}