-
Notifications
You must be signed in to change notification settings - Fork 0
/
turtle.go
75 lines (63 loc) · 1.39 KB
/
turtle.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
package turtle
import (
"fmt"
"math"
)
// A minimal Turtle agent, moving on a cartesian plane.
//
// https://en.wikipedia.org/wiki/Turtle_graphics
type Turtle struct {
X, Y float64 // Position.
Deg float64 // Orientation in degrees.
}
// Create a new Turtle.
func New() *Turtle {
return new(Turtle)
}
// Move the Turtle forward by dist.
func (t *Turtle) Forward(dist float64) {
rad := Deg2rad(t.Deg)
t.X += dist * math.Cos(rad)
t.Y += dist * math.Sin(rad)
}
// Move the Turtle backward by dist.
func (t *Turtle) Backward(dist float64) {
t.Forward(-dist)
}
// Rotate the Turtle counter clockwise by deg degrees.
func (t *Turtle) Left(deg float64) {
t.Deg += deg
}
// Rotate the Turtle clockwise by deg degrees.
func (t *Turtle) Right(deg float64) {
t.Deg -= deg
}
// Teleport the Turtle to (x, y).
func (t *Turtle) SetPos(x, y float64) {
t.X = x
t.Y = y
}
// Orient the Turtle towards deg.
func (t *Turtle) SetHeading(deg float64) {
t.Deg = deg
}
// Execute the received instruction.
func (t *Turtle) DoInstruction(i Instruction) {
switch i.Cmd {
case CmdForward:
t.Forward(i.Amount)
case CmdBackward:
t.Backward(i.Amount)
case CmdLeft:
t.Left(i.Amount)
case CmdRight:
t.Right(i.Amount)
}
}
var _ fmt.Stringer = &Turtle{}
// Write the Turtle state.
//
// Implements: fmt.Stringer
func (t *Turtle) String() string {
return fmt.Sprintf("(%9.4f, %9.4f) ^ %9.4f", t.X, t.Y, t.Deg)
}