JSFiddle - React, Tailwind, and code Playground
by Jordan Sayner
HTML
<div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="score"></div>
</div>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
#score {
margin-top: 10px;
font-family: Arial, sans-serif;
text-align: center;
}
JavaScript
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
const canvasSize = 20;
let snake = [{x: 9 * box, y: 9 * box}];
let direction = null;
let food = {
x: Math.floor(Math.random() * canvasSize) * box,
y: Math.floor(Math.random() * canvasSize) * box,
};
let score = 0;
let highestScore = getCookie("highestScore") || 0;
document.getElementById("score").innerHTML = `Score: ${score} | Highest Score: ${highestScore}`;
document.addEventListener("keydown", directionHandler);
function directionHandler(event) {
if (event.keyCode == 37 && direction != "RIGHT") direction = "LEFT";
if (event.keyCode == 38 && direction != "DOWN") direction = "UP";
if (event.keyCode == 39 && direction != "LEFT") direction = "RIGHT";
if (event.keyCode == 40 && direction != "UP") direction = "DOWN";
}
function draw() {
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i == 0 ? "darkgreen" : "green";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "white";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction == "LEFT") snakeX -= box;
if (direction == "UP") snakeY -= box;
if (direction == "RIGHT") snakeX += box;
if (direction == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * canvasSize) * box,
y: Math.floor(Math.random() * canvasSize) * box,
};
} else {
snake.pop();
}
let newHead = {x: snakeX, y: snakeY};
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
if (score >...