44 lines
1.5 KiB
HTML
44 lines
1.5 KiB
HTML
|
|
<!doctype html>
|
||
|
|
<html>
|
||
|
|
<head>
|
||
|
|
<meta charset="utf-8">
|
||
|
|
<title>Snake Game</title>
|
||
|
|
<style>
|
||
|
|
body { display:flex; height:100vh; align-items:center; justify-content:center; }
|
||
|
|
canvas { border:1px solid #333; }
|
||
|
|
</style>
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
<canvas id="game" width="300" height="300"></canvas>
|
||
|
|
<script>
|
||
|
|
const canvas = document.getElementById('game');
|
||
|
|
const ctx = canvas.getContext('2d');
|
||
|
|
const size = 10;
|
||
|
|
let dir = 'right';
|
||
|
|
let snake = [{x:2,y:0},{x:1,y:0},{x:0,y:0}];
|
||
|
|
let food = {x:8,y:8};
|
||
|
|
document.addEventListener('keydown', e => {
|
||
|
|
if (e.key.includes('Arrow')) dir = e.key.replace('Arrow','').toLowerCase();
|
||
|
|
});
|
||
|
|
function draw(){
|
||
|
|
ctx.fillStyle = '#fff'; ctx.fillRect(0,0,300,300);
|
||
|
|
ctx.fillStyle = '#f00'; ctx.fillRect(food.x*size,food.y*size,size,size);
|
||
|
|
ctx.fillStyle = '#000';
|
||
|
|
snake.forEach(s => ctx.fillRect(s.x*size,s.y*size,size,size));
|
||
|
|
}
|
||
|
|
function update(){
|
||
|
|
const head = {...snake[0]};
|
||
|
|
if (dir==='right') head.x++;
|
||
|
|
if (dir==='left') head.x--;
|
||
|
|
if (dir==='up') head.y--;
|
||
|
|
if (dir==='down') head.y++;
|
||
|
|
if (head.x===food.x && head.y===food.y){ snake.unshift(head); food = {x:Math.floor(Math.random()*30), y:Math.floor(Math.random()*30)} }
|
||
|
|
else { snake.pop(); snake.unshift(head); }
|
||
|
|
snake[0].x = (snake[0].x+30)%30;
|
||
|
|
snake[0].y = (snake[0].y+30)%30;
|
||
|
|
}
|
||
|
|
setInterval(()=>{ update(); draw(); }, 120);
|
||
|
|
</script>
|
||
|
|
</body>
|
||
|
|
</html>
|