JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="game-field" class="game-field" width="600" height="600">Игра не поддерживается вашим браузером</canvas>
CSS
.game-field {
border: 1px solid #eee;
display: block;
margin: 0 auto;
}
JavaScript
function GameManager(snake, fruit) {
this.fieldId = document.getElementById('game-field');
this.height = this.fieldId.height;
this.width = this.fieldId.width;
this.snake = new Snake();
this.fruit = new Fruit();
this.getCtx = function () {
return this.fieldId.getContext('2d');
}
}
GameManager.prototype.drawSnake = function () {
var len = this.snake.length,
i;
for (i = 0; i < len; i++) {
this.snake.coords.push([i * this.snake.cellWidth, 0]);
this.getCtx().fillStyle = this.snake.cellColor;
this.getCtx().fillRect(i * this.snake.cellWidth, 0, this.snake.cellWidth, this.snake.cellHeight);
this.getCtx().strokeStyle = this.snake.cellStroke;
this.getCtx().lineWidth = 2;
this.getCtx().strokeRect(i * this.snake.cellWidth, 0, this.snake.cellWidth, this.snake.cellHeight);
}
this.snake.x = this.snake.coords[this.snake.coords.length - 1][0];
this.snake.y = this.snake.coords[this.snake.coords.length - 1][1];
}
GameManager.prototype.drawFruit = function () {
this.fruit.x = getRandomCoords(this.fruit.width, this.width);
this.fruit.y = getRandomCoords(this.fruit.height, this.height);
this.getCtx().drawImage(this.fruit.image, this.fruit.x, this.fruit.y);
function getRandomCoords(min, max) {
var rand = Math.floor(Math.random() * (max - min + 1)) + min;
return Math.floor(rand / min) * min;
}
}
GameManager.prototype.start = function () {
this.drawFruit();
this.drawSnake();
this.keyListen();
this.snake.move();
}
GameManager.prototype.over = function () {
alert('Over')
}
GameManager.prototype.keyListen = function () {
var LEFT_KEY = 37,
UP_KEY = 38,
RIGHT_KEY = 39,
DOWN_KEY = 40,
self = this;
document.addEventListener('keydown', function (e) {
var key = e.keyCode ? e.keyCode : e.which;
switch (key) {
case LEFT_KEY:
if (self.snake.direction !== 'right') {
self.snake.direction = 'left';
}
break;
case UP_KEY:
if (self.snake.direction !== 'down') {
self.snake.direction =...