xxxxxxxxxx
63
var rows = 10, cols = 10;
var sz = 40;
var head, tail;
var speed, speedmult;
function setup() {
createCanvas(400, 400);
// Head init
head = createVector(random(rows), random(cols));
// Taik init
tail = [];
// Speed init
speedmult = 0.5;
speed = createVector(
(5 - head.x > 0) ? random([0, 1]) : random([0, -1]),
(5 - head.y > 0) ? random([0, 1]) : random([0, -1])
);
if (speed.x == speed.y)
speed.x = 0;
}
function draw() {
// Background
background(31);
// Grid
noFill();
stroke(255, 0, 105);
for (let row = 0; row < rows; row++)
for (let col = 0; col < cols; col++)
rect(col * sz, row * sz, sz, sz);
// Snake moves
head.add(p5.Vector.mult(speed, speedmult));
// Snake draw
noStroke();
fill(255, 255, 0);
rect(Math.floor(head.y / sz) * sz,
Math.floor(head.x / sz) * sz, sz, sz);
}
function keyPressed() {
switch(keyCode) {
case 87:
speed = createVector(-1, 0);
break;
case 83:
speed = createVector(1, 0);
break;
case 65:
speed = createVector(0, -1);
break;
case 68:
speed = createVector(0, 1);
break;
default:
break;
}
console.log(speed.x, speed.y);
}