Popular

Source code snake game on Javascript

1. How to implement
 - Create a file name Game.html
 - Open the file by Note pad
 - Copy the code and paste in the file, save and open with Browser

2. Code


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<style>
body, html {height: 99%;}
#canvas {
width:100%;
height: 100%;
background-color:grey;
}
</style>
</html>
<script>
const MATRIX_SIZE = 20;
class BodyCell {
constructor(position) {this.position = position;}
}

const snake = [new BodyCell(190), new BodyCell(191)];
var foodPosition = Math.floor(Math.random() * 399);
function draw() {
var canvas = document.getElementById('canvas');
if(canvas.getContext) {
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;
context.clearRect(0, 0, canvas.with, canvas.height);

drawMess(context, canvas.width, canvas.height);
}
}

function drawMess(context, canvasWidth, canvasHeight) {
context.fillStyle="black";
var cellWidth = canvasWidth / MATRIX_SIZE;
var cellHeight = canvasHeight / MATRIX_SIZE;
for($i=0;$i<MATRIX_SIZE;$i++) {
context.beginPath();
context.moveTo($i*cellWidth,0);
context.lineTo($i*cellWidth, canvasHeight);
context.stroke();

context.beginPath();
context.moveTo(0, $i*cellHeight);
context.lineTo(canvasWidth, $i*cellHeight);
context.stroke();

}

for($i=0;$i<snake.length;$i++) {
var x = snake[$i].position % MATRIX_SIZE;
var y = Math.floor(snake[$i].position / MATRIX_SIZE);
context.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight);
}

var foodX = foodPosition % MATRIX_SIZE;
var foodY = Math.floor(foodPosition / MATRIX_SIZE);
context.fillRect(foodX * cellWidth, foodY * cellHeight, cellWidth, cellHeight);
}
var direction = 0;
var speed = 200;
var lastFrameTime = 0;
function updateLoop() {
updateGame();
draw();
}

function updateGame() {
if(lastFrameTime == 0) {
lastFrameTime = new Date().getTime();
return;
}
if(new Date().getTime() - lastFrameTime < speed) {
return;
}
lastFrameTime = new Date().getTime();
var moveStep = 0;
switch(direction) {
case 0: moveStep = 1; break;
case 1: moveStep = -1; break;
case 2: moveStep = -MATRIX_SIZE; break;
case 3: moveStep = MATRIX_SIZE; break;
}

var tailPosition = snake[snake.length - 1].position;
for($i=snake.length -1;$i>0;$i--) snake[$i].position = snake[$i-1].position;
snake[0].position += moveStep;
if(snake[0].position >= 400) snake[0].position = snake[0].position % MATRIX_SIZE;
if(snake[0].position <0) snake[0].position = MATRIX_SIZE * MATRIX_SIZE - snake[0].position % MATRIX_SIZE;

if(snake[0].position == foodPosition) {
foodPosition = Math.floor(Math.random() * 399);
snake[snake.length] = new BodyCell(tailPosition);
}
}

setInterval(updateLoop, 10);

document.addEventListener('keypress', (event) => {
var name = event.key;
if(name == 'w') direction =2; else if(name=='a') direction = 1; else if(name=='d') direction = 0;
else if(name='s') direction = 3;
}, false);
</script>

Comments