-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrover.go
77 lines (68 loc) · 1.38 KB
/
rover.go
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
package main
import (
"image"
"log"
"time"
)
// RoverDriver drives a rover arount the surface of Mars.
type RoverDriver struct {
commandc chan command
}
func NewRoverDriver() *RoverDriver {
r := &RoverDriver{
commandc: make(chan command),
}
go r.drive()
return r
}
type command int
const (
right = command(0)
left = command(1)
)
// drive is responsible for driving the rover. It
// is expected to be started in a goroutine.
func (r *RoverDriver) drive() {
pos := image.Point{X: 0, Y: 0}
direction := image.Point{X: 1, Y: 0}
updateInterval := 250 * time.Millisecond
nextMove := time.After(updateInterval)
for {
select {
case c := <-r.commandc:
switch c {
case right:
direction = image.Point{
X: -direction.Y,
Y: direction.X,
}
case left:
direction = image.Point{
X: direction.Y,
Y: -direction.X,
}
}
log.Printf("new direction %v", direction)
case <-nextMove:
pos = pos.Add(direction)
log.Printf("moved to %v", pos)
nextMove = time.After(updateInterval)
}
}
}
// Left turns the rover left (90° counterclockwise).
func (r *RoverDriver) Left() {
r.commandc <- left
}
// Right turns the rover right (90° clockwise).
func (r *RoverDriver) Right() {
r.commandc <- right
}
func main() {
r := NewRoverDriver()
time.Sleep(3 * time.Second)
r.Left()
time.Sleep(3 * time.Second)
r.Right()
time.Sleep(3 * time.Second)
}