-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturtle_draw.go
77 lines (66 loc) · 1.61 KB
/
turtle_draw.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 turtle
import "fmt"
// A drawing Turtle.
type TurtleDraw struct {
Turtle // Turtle agent to move around.
Pen // Pen used when drawing.
W *World // World to draw on.
}
// Create a new TurtleDraw, attached to the World w.
func NewTurtleDraw(w *World) *TurtleDraw {
t := *New()
p := *NewPen()
td := &TurtleDraw{t, p, w}
return td
}
// Move the turtle forward and draw the line if the Pen is On.
func (td *TurtleDraw) Forward(dist float64) {
x0, y0 := td.X, td.Y
td.Turtle.Forward(dist)
x1, y1 := td.X, td.Y
line := Line{x0, y0, x1, y1, &td.Pen}
if td.On {
td.drawLine(line)
}
}
// Move the turtle backward and draw the line if the Pen is On.
func (td *TurtleDraw) Backward(dist float64) {
td.Forward(-dist)
}
// Teleport the Turtle to (x, y) and draw the line if the Pen is On.
func (td *TurtleDraw) SetPos(x, y float64) {
x0, y0 := td.X, td.Y
td.Turtle.SetPos(x, y)
x1, y1 := td.X, td.Y
line := Line{x0, y0, x1, y1, &td.Pen}
if td.On {
td.drawLine(line)
}
}
// Execute the received instruction.
func (td *TurtleDraw) DoInstruction(i Instruction) {
switch i.Cmd {
case CmdForward:
td.Forward(i.Amount)
case CmdBackward:
td.Backward(i.Amount)
case CmdLeft:
td.Left(i.Amount)
case CmdRight:
td.Right(i.Amount)
}
}
var _ fmt.Stringer = &TurtleDraw{}
// Write the TurtleDraw state.
//
// Implements: fmt.Stringer
func (td *TurtleDraw) String() string {
sT := td.Turtle.String()
sP := td.Pen.String()
return fmt.Sprintf("Turtle: %s Pen: %s", sT, sP)
}
// Send the line to the world and wait for it to be drawn
func (td *TurtleDraw) drawLine(l Line) {
td.W.DrawLineCh <- l
<-td.W.doneLineCh
}