Created
September 14, 2023 14:24
-
-
Save ppsdatta/446a6070eb44e2143025c2cff0effe66 to your computer and use it in GitHub Desktop.
Turtle code in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Turtle { | |
constructor(ox, oy, ctx) { | |
this.ctx = ctx; | |
this.ox = ox; | |
this.oy = oy; | |
this.reset(); | |
} | |
reset() { | |
this.x = this.ox; | |
this.y = this.oy; | |
this.angle = 0; | |
this.pen = true; | |
} | |
radians(n) { | |
return (Math.PI * n) / 180.0; | |
} | |
fwd(n) { | |
const nx = this.x + n * Math.cos(this.radians(this.angle - 90)); | |
const ny = this.y + n * Math.sin(this.radians(this.angle - 90)); | |
if (this.pen) { | |
this.ctx.moveTo(this.x, this.y); | |
this.ctx.lineTo(nx, ny); | |
this.ctx.stroke(); | |
} | |
this.x = nx; | |
this.y = ny; | |
return this; | |
} | |
back(n) { | |
const curr = this.angle; | |
this.angle += 180; | |
this.fwd(n); | |
this.angle = curr; | |
} | |
left(n) { | |
this.angle -= n; | |
return this; | |
} | |
right(n) { | |
this.angle += n; | |
return this; | |
} | |
penup() { | |
this.pen = false; | |
return this; | |
} | |
pendown() { | |
this.pen = true; | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment