Георгий777,
медитируйте ... окончание игры: когда змея укусит свой хвост... всё только для примера ... вариантов решений много...
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
#output {
width:400px;
height:400px;
border-top: 1px solid gray;
border-left: 1px solid gray;
}
.inner {
border-bottom: 1px solid gray;
border-right: 1px solid gray;
width:19px;
height:19px;
float: left;
}
.red{
background-color: #FF0000;
}
.green{
background-color: #008000;
}
</style>
</head>
<body>
<div id="output"></div>
<script>
"use strict"
var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer;
function createMatrix() {
var output = document.getElementById("output"), div, i;
for (i = 0; i < len; i++) {
div = document.createElement("div");
div.className = "inner";
output.appendChild(div);
ar.push(div);
}
}
createMatrix();
function rund(max) {
return Math.floor(Math.random() * max);
}
function generatePoint() {
var num = rund(len);
snake.push(num);
setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
var temp = ar.reduce(function(a, b, k) {
b.classList.contains("red") || b.classList.contains("green") || a.push(k);
return a;
}, []);
var num = temp[rund(temp.length)];
eat.push(num);
setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
generateEat();
}
function move() {
var pointNext = snake[0];
if (direction == "right") {
pointNext += 1;
if (pointNext % col == 0) {
pointNext -= col;
}
}
if (direction == "left") {
if (pointNext % col == 0) {
pointNext += col - 1;
} else {
pointNext -= 1;
}
}
if (direction == "down") {
pointNext += col;
if (pointNext > len) {
pointNext %= len;
}
}
if (direction == "up") {
pointNext -= col;
if (pointNext < 0) {
pointNext += len;
}
}
if (ar[pointNext].classList.contains("green")) {
eat = eat.filter(function(a) {
a != pointNext;
});
snake.push(0);
}
if (ar[pointNext].classList.contains("red")) {
alert("game over");
return;
}
for (var i = 0; i < snake.length; i++) {
var point = snake[i];
setCell(point);
snake[i] = pointNext;
setCell(pointNext, "red");
pointNext = point;
}
timer = window.setTimeout(move, 500);
}
move();
document.onkeydown = function(e) {
switch(e.keyCode) {
case 37:
direction = "left";
break;
case 38:
direction = "up";
break;
case 39:
direction = "right";
break;
case 40:
direction = "down";
break;
}
};
</script>
</body>
</html>