-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturtle.js
87 lines (83 loc) · 2.09 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const commandLookup = {
"fd": function(amt) {
turtle.forward(amt);
},
"bd": function(amt) {
turtle.forward(-amt);
},
"rt": function(angle) {
turtle.right(angle);
},
"lt": function(angle) {
turtle.right(-angle);
},
"pu": function() {
turtle.pen = false;
},
"pd": function() {
turtle.pen = true;
}
}
class Turtle {
constructor(x, y, angle) {
this.x = x;
this.y = y;
this.dir = angle;
}
reset() {
// console.log(this.x, this.y, this.dir)
translate(this.x, this.y)
rotate(this.dir)
this.pen = true
}
runCode(tokens) {
let index = 0;
while (index < tokens.length) {
let token = tokens[index++]
let amt, angle
switch (token) {
case 'fd':
amt = parseInt(tokens[index++])
this.forward(amt)
break;
case 'bd':
console.log("bd")
amt = parseInt(tokens[index++])
this.forward(-amt)
break;
case 'rt':
angle = tokens[index++]
this.right(angle)
break;
case 'lt':
angle = parseInt(tokens[index++])
this.right(-angle)
break;
case 'pu':
this.pen = false
break;
case 'pd':
this.pen = true
break;
default:
console.log("Invalid Token at ", index - 1)
// console.log(tokens)
break;
}
// index++;
angle = undefined
amt = undefined
}
}
forward(amt) {
if (this.pen == true) {
stroke(255)
strokeWeight(2)
line(0, 0, amt, 0)
}
translate(amt, 0)
}
right(angle) {
rotate(angle);
}
}