JSFiddle - React, Tailwind, and code Playground
by Sebastian Kay
HTML
<wrapper>
<canvas id="canvas"></canvas>
<div class="counter">
<p>Points: <strong id="points">0</strong></p>
<p>Record: <strong id="record"></strong></p>
</div>
</wrapper>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
max-width: 100%;
overflow: hidden;
background: linear-gradient(to right, #605C3C, #3C3B3F);
}
wrapper {
display: flex;
flex-direction: row;
}
.counter {
margin-left: 40px;
color: white;
font-family: sans-serif;
width: 100px;
}
JavaScript
window.onload = () => {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
cw = canvas.width = canvas.height = 250,
s = cw / 20, x = y = 0,
rows = cols = cw / s,
direction = { dir: 'right', change: true },
tail = [],
food = {x, y},
head,
drawInterval,
speed = 100,
points,
record;
if (localStorage.getItem('record')) record = localStorage.getItem('record');
else record = 0;
_('record').innerHTML = record;
createFood();
draw();
document.addEventListener('keydown', e => getDirection(e));
function cutTale() {
alert('shit');
tail = [];
}
function createFood(caught = false) {
var xf = Math.floor(Math.random() * cols) * s;
var yf = Math.floor(Math.random() * rows) * s;
for (var i = 0; i < tail.length; i++) {
if (xf == tail[i].x + s && yf == tail[i].y ) { createFood(); return; };
if (xf == tail[i].x && yf == tail[i].y + s) { createFood(); return; };
if (xf + s == tail[i].x && yf == tail[i].y ) { createFood(); return; };
if (xf == tail[i].x && yf + s == tail[i].y ) { createFood(); return; };
if (xf == tail[i].x && yf == tail[i].y) { createFood(); return; };
}
food = { ...food, x: xf, y: yf };
tail = [ ...tail, '1' ];
if (caught) {
points = tail.length - 1;
if (record < points) {
record = points;
localStorage.setItem('record', record);
_('record').innerHTML = record;
};
_('points').innerHTML = points;
}
}
function getDirection(e) {
switch(e.keyCode) {
case 37: if (direction.dir !== 'right' && direction.change)
direction = { ...direction, dir: 'left', change: false }; break;
case 38: if (direction.dir !== 'bottom' && direction.change)
direction = { ...direction, dir: 'top', change: false }; break;
case 39: if (direction.dir !==...