xxxxxxxxxx
184
let SZ = 10;
let x, y;
let currentKey = null;
let cubeDraw = null;
let drawing = true;
let started = true;
let selfdrive = false;
let selfmode = null;
const basicCubeDraw = () => {
cfront();
ctop();
cside();
};
function pickDir(){
drawing = true;
selfmode = random(['a','z','ArrowLeft','ArrowRight','ArrowUp','ArrowDown'])
}
const keyHandler = {
a: () => {
y--;
cubeDraw = basicCubeDraw;
},
z: () => {
y++;
cubeDraw = () => {
cside();
cfront();
};
},
ArrowLeft: () => {
x--;
cubeDraw = () => {
ctop();
cfront();
};
},
ArrowRight: () => {
x++;
cubeDraw = basicCubeDraw;
},
ArrowUp: () => {
x++;
y--;
cubeDraw = () => {
ctop();
cside();
};
},
ArrowDown: () => {
x--;
y++;
cubeDraw = basicCubeDraw;
},
};
function setup() {
createCanvas(400, 400);
background(240);
SZ = width / 30;
x = width / 2;
y = height / 2;
cubeDraw = basicCubeDraw;
}
function titleScreen(){
textAlign(CENTER,CENTER);
text(`escher-sketcher
by kirk is
based on a program by benjamin bartels
published in 'antic' magazine august 1983
arrow keys, and 'a' and 'z' move
space toggles drawing pen on/off
'c' clear screen
'r' toggle random self-driving mode
click to start`,width/2,height/2);
}
function draw() {
if(!started) {
titleScreen();
return;
}
drawCube(x, y);
if (!selfdrive && currentKey && keyHandler[currentKey]) {
keyHandler[currentKey]();
}
if(selfdrive) {
keyHandler[selfmode]();
if(random()< .05){
pickDir();
}
}
x = constrain(x,SZ,width-SZ);
y = constrain(y,SZ,height-SZ);
}
function keyPressed() {
currentKey = key;
if(key == ' ') drawing = !drawing;
if(key == 'c') background(240);
if(key == 'r') {
selfdrive = !selfdrive;
if(selfdrive) pickDir();
}
}
function keyReleased() {
currentKey = null;
cubeDraw = null;
}
function mousePressed(){
started = true;
background(240);
}
function ctop() {
fill(255);
stroke(255);
beginShape();
vertex(0,0);
vertex(-SZ,-SZ);
vertex(0,-SZ*2);
vertex(SZ,-SZ);
endShape(CLOSE);
}
function cfront() {
stroke(32);
line(-SZ,-SZ,-SZ,-0);
stroke(255);
line(0,0,0,SZ);
fill(128);
stroke(128);
beginShape();
vertex(0,0);
vertex(-SZ,-SZ);
vertex(-SZ,0);
vertex(0,SZ);
endShape(CLOSE);
}
function cside() {
fill(32);
stroke(32);
beginShape();
vertex(0,0);
vertex(SZ,-SZ);
vertex(SZ,0);
vertex(0,SZ);
endShape(CLOSE);
endShape(CLOSE);
}
function drawCube(x, y) {
if(! drawing) return;
push();
translate(x, y);
cubeDraw && cubeDraw();
pop();
}