@jawirhytam/kurokuro
Version:
A DjawaScript Turtle Graphics library.
106 lines (82 loc) • 2.31 kB
JavaScript
// kurokuro.js - DjawaScript Turtle Graphics Library
(function(global) {
const canvas = document.getElementById('kurokuroCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
// The Turtle class
class Kuro {
constructor() {
this.reset();
this.init();
}
init() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
}
reset() {
this.x = centerX;
this.y = centerY;
this.angle = -90; // Start facing up
this.penDown = true;
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.init();
}
_draw(distance) {
const rad = (this.angle * Math.PI) / 180;
const newX = this.x + distance * Math.cos(rad);
const newY = this.y + distance * Math.sin(rad);
if (this.penDown) {
ctx.lineTo(newX, newY);
ctx.stroke();
} else {
ctx.moveTo(newX, newY);
}
this.x = newX;
this.y = newY;
}
maju(distance) {
this._draw(distance);
}
mundur(distance) {
this._draw(-distance);
}
mengen(degrees) {
this.angle += degrees;
}
mengiri(degrees) {
this.angle -= degrees;
}
penMunggah() {
this.penDown = false;
}
penMudun() {
this.penDown = true;
}
}
// --- Global API for DjawaScript ---
// Create a single global instance of our turtle
const kura = new Kuro();
global.maju = function(distance) {
kura.maju(distance);
};
global.mundur = function(distance) {
kura.mundur(distance);
};
global.mengen = function(degrees) {
kura.mengen(degrees);
};
global.mengiri = function(degrees) {
kura.mengiri(degrees);
};
global.penMunggah = function() {
kura.penMunggah();
};
global.penMudun = function() {
kura.penMudun();
};
global.reset = function() {
kura.reset();
}
console.log("Kurokuro library loaded.");
})(window);