JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Snow Drop Animation</title>
<style>
canvas {
background-color: #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const gameSize = 500;
const blockSize = 10;
const gameSpeed = 20;
class Snake {
constructor() {
this.body = [{ x: gameSize / 2, y: gameSize / 2 }];
this.direction = 'right';
}
move() {
const head = this.body[0];
if (head.x >= canvas.width) {
this.body[0].x = 0;
}
if (head.x < 0) {
this.body[0].x = canvas.width;
}
if (head.y >= canvas.height) {
this.body[0].y = 0;
}
if (head.y < 0) {
this.body[0].y = canvas.height;
}
switch (this.direction) {
case 'right':
this.body.unshift({ x: head.x + blockSize, y: head.y });
break;
case 'left':
this.body.unshift({ x: head.x - blockSize, y: head.y });
break;
case 'up':
this.body.unshift({ x: head.x, y: head.y - blockSize });
break;
case 'down':
this.body.unshift({ x: head.x, y: head.y + blockSize });
break;
}
this.body.pop();
}
setDirection(newDirection, opositeDirection) {
if(this.direction != newDirection && this.direction != opositeDirection){
this.direction = newDirection;
}
}
}
class Food {
constructor() {
this.x = Math.floor(Math.random() * gameSize / blockSize) * blockSize;
this.y = Math.floor(Math.random() * gameSize / blockSize) * blockSize;
}
}
const snake = new Snake();
let food = new Food();
document.addEventListener('keydown', (event) => {
switch (event.key) {
case 'ArrowUp':
snake.setDirection('up', 'down');
break;
case 'ArrowDown':
snake.setDirection('down', 'up');
break;
case 'ArrowLeft':
snake.setDirection('left', 'right');
...