xxxxxxxxxx
var snakes = [];
var chanceOfMakingSnake = 0.1;
var snakeSize = 20;
var oCanvas;
var oDrawingArea;
function setup() {
createCanvas(windowWidth, windowHeight);
background('#111111');
oCanvas = document.getElementById("defaultCanvas0");
oDrawingArea = oCanvas.getContext("2d");
console.log(oDrawingArea);
}
function Snake(edge) {
var initPos = _getSnakeInitSide(edge)
this.dir = createVector(0, 0);
this.vel = createVector(0, 0);
this.pos = createVector(initPos.x, initPos.y);
this.speed = 3;
this.move = function(){
this.dir.x = initPos.dx;
this.dir.y = initPos.dy;
this.vel = this.dir.copy();
this.vel.mult(this.speed);
this.pos.add(this.vel);
}
this.display = function() {
var p = oDrawingArea.getImageData(this.pos.x - (snakeSize/4), this.pos.y - (snakeSize/4), snakeSize/2, snakeSize/2).data;
var hex = "0x" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
// var colournumber = parseInt(hex, 16);
// console.log(hex);
if (hex !== '0xffffff') {
print(this);
square(this.pos.x, this.pos.y, snakeSize);
}
}
}
class TailDot {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
function draw() {
background('#111111');
noStroke();
smooth();
if (Math.random() > chanceOfMakingSnake) {
snakes.push(new Snake(Math.floor(Math.random()*4)));
}
for (let i = 0; i < snakes.length; i++) {
snakes[i].move();
snakes[i].display();
}
}
// --------------------------------------
// -------- private functions -----------
// --------------------------------------
function _getSnakeInitSide(edge) {
let x;
let y;
let dx;
let dy;
switch(edge) {
case 0:
x = Math.random() * windowWidth;;
y = -1*snakeSize;
dx = 0;
dy = 1;
break;
case 1:
x = windowWidth + snakeSize;
y = Math.random() * windowHeight;;
dx = -1;
dy = 0;
break;
case 2:
x = Math.random() * windowWidth;;
y = windowHeight + snakeSize;
dx = 0;
dy = -1;
break;
case 3:
x = -1*snakeSize;
y = Math.random() * windowHeight;;
dx = 1;
dy = 0;
break;
}
return {x,y,dx,dy};
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}