-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTurtle.js
61 lines (46 loc) · 900 Bytes
/
Turtle.js
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
function Turtle(canvas, context, startPos, startAngle){
const rad = (180/Math.PI);
const sin = Math.sin;
const cos = Math.cos;
var x = startPos[0];
var y = startPos[1];
var stack = [];
var angle = startAngle / rad;
var sign = 1;
context.beginPath();
context.moveTo(x, y);
function move(distance){
x += sin(angle) * distance;
y -= cos(angle) * distance;
context.lineTo(x, y);
}
function jump(distance){
x += sin(angle) * distance;
y -= cos(angle) * distance;
context.moveTo(x, y);
}
function turn(a){
angle += sign * a / rad;
}
function invert(){
sign = 0 - sign;
}
function push(){
stack.push([x, y, angle]);
}
function pop(){
var popped = stack.pop();
x = popped[0];
y = popped[1];
angle = popped[2];
context.moveTo(x, y);
}
return {
move: move
,jump: jump
,turn: turn
,invert: invert
,push: push
,pop: pop
};
}