JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<body>
<canvas id="snake-game" width="400" height="400"></canvas>
</body>
JavaScript
"use strict";
var canvas = document.getElementById("snake-game");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var blockSize = 10;
var widthInBlocks = width / blockSize;
var heightInBlocks = height / blockSize;
var score = 0;
drawBorder();
drawScore();
var snake = new Snake();
snake.draw();
function Block(col, row) {
this.col = col;
this.row = row;
}
Block.drawSquare = function(color) {
var x = this.col * blockSize;
var y = this.row * blockSize;
ctx.fillStyle = color;
ctx.fillRect(x, y, blockSize, blockSize);
};
Block.drawCircle = function(color) {
var centerX = this.col * blockSize + blockSize / 2;
var centerY = this.row * blockSize + blockSize / 2;
ctx.fillStyle = color;
circle(centerX, centerY, blockSize / 2, true);
};
Block.equal = function(otherBlock) {
return this.col === otherBlock.col && this.row === otherBlock.row;
};
function Snake() {
this.segments = [
new Block(7, 5),
new Block(6, 5),
new Block(5, 5)
];
this.direction = "right";
this.nextDirection = "right";
}
Snake.draw = function() {
this.segments.forEach(drawSquare("Blue"));
};
function drawBorder() {
ctx.fillStyle = "Black";
ctx.fillRect(0, 0, width, blockSize);
ctx.fillRect(0, height - blockSize, width, blockSize);
ctx.fillRect(0, 0, blockSize, height);
ctx.fillRect(width - blockSize, 0, blockSize, height);
}
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "Black";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Score: " + score, blockSize, blockSize);
}
function gameOver() {
...