Snake color demo
Showing the different ways you can use color in a snake game
by Braden Best
HTML
<canvas class="screen">Look. It's 2017. There is no excuse for this message to be visible. Go download a better browser before you get infected with a trojan horse by one of the many, many exploit kits out there.</canvas><br>
<p>
Shown: Three snakes. One is rendered all in one color (white), another has colors embedded in each piece, the last (longest) has an independent array, so it looks more natural, like it's slithering and not "revealing" some kind of background pattern (the "Chowder" effect)
</p>
JavaScript
const T_SINGLE = 0; // Single array
const T_DOUBLE = 1; // Two arrays
const T_BLACK = 2; // misnomer; it's rendered white
const CANVAS_SIZE = 30;
const SCALE = 10;
const FPS = 24;
const NPIECES = 10;
const rand = n => Math.floor(Math.random() * n);
function random_color(){
const char = "024ACE";
let buffer = "#";
for(let i = 0; i < 6; i++)
buffer += char[rand(char.length)];
return buffer;
}
function Snake(args = {}){
var x = args.x || 0;
var y = args.y || CANVAS_SIZE / 2;
var npieces = args.npieces || NPIECES;
var type = args.type || T_SINGLE;
var timer = args.timer || 0;
var body = new Array();
var colors = new Array();
function init(){
for(let i = 0; i < npieces; i++){
body.push([-1, -1]);
colors.push(random_color());
body[i][2] = colors[i];
}
}
function move(){
timer = (timer + 1) % 12;
if(timer >= 0 && timer <= 4)
x = (x + 1) % CANVAS_SIZE;
else
y = (y + 1) % CANVAS_SIZE;
}
function rotate(){
var tail = body.pop();
tail[0] = x;
tail[1] = y;
body.unshift(tail);
}
function draw(ctx){
var color_table = [];
color_table[T_BLACK] = "#fff";
for(let i = 0; i < body.length; i++){
color_table[T_SINGLE] = body[i][2];
color_table[T_DOUBLE] = colors[i];
ctx.fillStyle = color_table[type];
ctx.fillRect(body[i][0] * SCALE, body[i][1] * SCALE, SCALE, SCALE);
}
}
init();
return {move, draw, rotate};
}
(function(){
var canvas = document.querySelector("canvas.screen");
var ctx = canvas.getContext("2d");
canvas.width = CANVAS_SIZE * SCALE;
canvas.height = CANVAS_SIZE * SCALE;
var snakes = [
Snake({
type: T_SINGLE,
x: -12 +...