Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Snake clone implementation in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>A simple Snake Clone</title>
</head>
<body>
<canvas id="game" width="250" height="250" style="background: #000"></canvas>
<script>
const TIMEOUT = 125
const SIZE = 25
const BOARD_COLS = 10
const BOARD_ROWS = 10
const BOARD_SIZE = (BOARD_COLS * BOARD_ROWS)
var head = 0;
var apple = 45;
var direction = 1;
var tail = [];
var accumulator = 0;
var length = 0;
var i = 0;
var isDead = false;
var ctx = null;
var canvas = null;
var previousTicks = 0;
function draw(position, r, g, b) {
var x = (position % BOARD_COLS) * SIZE;
var y = parseInt(position / BOARD_COLS) * SIZE;
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
ctx.fillRect(x, y, SIZE, SIZE);
}
function random() {
return Math.floor(Math.random() * BOARD_SIZE);
}
function isOnLimits() {
return (direction == 1 && head % BOARD_COLS == 0) ||
(direction == -1 && (head + 1) % BOARD_COLS == 0);
}
function hasCollisionWithTail(position) {
for (var i = 0; i < length; i++)
if (tail[i] == position) return true;
return false;
}
function placeApple() {
do apple = random();
while (head == apple || hasCollisionWithTail(apple));
}
function setDirection(dir) {
if (dir != -direction || length == 0)
direction = dir;
}
function drawBoard() {
for (var i = 0; i < length; ++i)
draw(tail[i], 0, 255, 0);
draw(head, 0, 0, 255);
draw(apple, 255, 0, 0);
}
function move() {
tail[i] = head;
head += direction;
if (++i >= length) i = 0;
if (isOnLimits())
head -= BOARD_COLS * direction;
else if (head < 0)
head += BOARD_SIZE;
else if (head >= BOARD_SIZE)
head -= BOARD_SIZE;
}
function update(delta) {
accumulator += delta;
if (accumulator >= TIMEOUT && !isDead) {
accumulator = 0;
move();
if (head == apple) {
placeApple();
tail[length++] = head;
} else if (hasCollisionWithTail(head)) isDead = true;
}
drawBoard();
}
canvas = document.getElementById('game');
ctx = canvas.getContext('2d');
document.addEventListener('keydown', function(e) {
if (event.keyCode == 38) setDirection(-BOARD_COLS);
else if (event.keyCode == 40) setDirection( BOARD_COLS);
else if (event.keyCode == 37) setDirection(-1);
else if (event.keyCode == 39) setDirection( 1);
}, false);
function main(timestamp) {
var delta = timestamp - previousTicks;
previousTicks = timestamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
update(delta);
requestAnimationFrame(main);
}
window.requestAnimationFrame(main);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.