top of page
Search
Writer's picturelinuxtech

How to make a simple snake game using html


source code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta http-equiv="X-UA-Compatible" content="ie=edge" />

<title>Snake game made by linux tech</title>

</head>

<body>

<canvas id="canvas" width="600" height="500"></canvas>


<script>

var canvas, ctx;


window.onload = function() {

canvas = document.getElementById("canvas");

ctx = canvas.getContext("2d");


document.addEventListener("keydown", keyDownEvent);


// render X times per second

var x = 8;

setInterval(draw, 1000 / x);

};


// game world

var gridSize = (tileSize = 20); // 20 x 20 = 400

var nextX = (nextY = 0);


// snake

var defaultTailSize = 3;

var tailSize = defaultTailSize;

var snakeTrail = [];

var snakeX = (snakeY = 10);


// apple

var appleX = (appleY = 15);


// draw

function draw() {

// move snake in next pos

snakeX += nextX;

snakeY += nextY;


// snake over game world?

if (snakeX < 0) {

snakeX = gridSize - 1;

}

if (snakeX > gridSize - 1) {

snakeX = 0;

}


if (snakeY < 0) {

snakeY = gridSize - 1;

}

if (snakeY > gridSize - 1) {

snakeY = 0;

}


//snake bite apple?

if (snakeX == appleX && snakeY == appleY) {

tailSize++;


appleX = Math.floor(Math.random() * gridSize);

appleY = Math.floor(Math.random() * gridSize);

}


//paint background

ctx.fillStyle = "yellow";

ctx.fillRect(0, 0, canvas.width, canvas.height);


// paint snake

ctx.fillStyle = "blue";

for (var i = 0; i < snakeTrail.length; i++) {

ctx.fillRect(

snakeTrail[i].x * tileSize,

snakeTrail[i].y * tileSize,

tileSize,

tileSize

);


//snake bites it's tail?

if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) {

tailSize = defaultTailSize;

}

}


// paint apple

ctx.fillStyle = "white";

ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);


//set snake trail

snakeTrail.push({ x: snakeX, y: snakeY });

while (snakeTrail.length > tailSize) {

snakeTrail.shift();

}

}


// input

function keyDownEvent(e) {

switch (e.keyCode) {

case 37:

nextX = -1;

nextY = 0;

break;

case 38:

nextX = 0;

nextY = -1;

break;

case 39:

nextX = 1;

nextY = 0;

break;

case 40:

nextX = 0;

nextY = 1;

break;

}

}

</script>

</body>

</html>

35 views0 comments

Recent Posts

See All

HOw to make a simple login form using HTML.

source code: <html> <head> <title>Login Page</title> </head> <body> <form name="loginForm" method="post" action="login.php"> <table...

How to make a simple chessboard using HTML

source code: <html> <head> <meta charset="UTF-8"> <title>simple chessborad made by linux tech</title> <style type="text/css"> .chessboard...

Comments


bottom of page