Skip to content

Instantly share code, notes, and snippets.

@quangdatpham
Last active October 18, 2019 07:16
Show Gist options
  • Save quangdatpham/2515439725a11221beca9d266b888e22 to your computer and use it in GitHub Desktop.
Save quangdatpham/2515439725a11221beca9d266b888e22 to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/lonokon
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Sneak Game</title>
</head>
<body>
<canvas width="400" height="400"></canvas>
<script id="jsbin-javascript">
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
setInterval(renderGame, 100);
window.addEventListener('keydown', updateVelocity);
let player = { x: 5, y: 5 };
let apple = { x: 10, y: 10 };
let velocity = { x: 0, y: 0};
let gs = 20;
let tc = 20;
let trail = [{ x: 5, y: 5 }, { x: 5, y: 6 }, { x: 5, y: 7 }, { x: 5, y: 8 }, { x: 5, y: 9 }];
let tail = 5;
let gameStart = false;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, gs * tc, gs * tc);
ctx.fillStyle = 'blue';
for (var i = 0; i < trail.length; i++) {
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs, gs);
}
function resetGame() {
player = { x: 5, y: 5 };
apple = { x: 10, y: 10 };
velocity = { x: 0, y: 0};
gs = 20;
tc = 20;
trail = [{ x: 5, y: 5 }, { x: 5, y: 6 }, { x: 5, y: 7 }, { x: 5, y: 8 }, { x: 5, y: 9 }];
tail = 5;
gameStart = false;
}
function renderGame() {
player.x += velocity.x;
player.y += velocity.y;
if (player.x < 0)
player.x = tc - 1;
if (player.x > tc - 1)
player.x = 0;
if (player.y < 0)
player.y = tc - 1;
if (player.y > tc - 1)
player.y = 0;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, gs * tc, gs * tc);
ctx.fillStyle = 'blue';
for (var i = 0; i < trail.length; i++) {
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs, gs);
if (player.x === trail[i].x && player.y === trail[i].y) {
resetGame();
}
}
trail.unshift({ x: player.x, y: player.y });
while (trail.length > tail) {
trail.pop();
}
if (player.x === apple.x && player.y === apple.y) {
tail++;
apple.x = Math.floor(Math.random() * tc);
apple.y = Math.floor(Math.random() * tc);
}
ctx.fillStyle = 'red';
ctx.fillRect(apple.x * gs, apple.y * gs, gs, gs);
}
function updateVelocity(e) {
gameStart = true;
switch (e.keyCode) {
case 37:
if (velocity.x == 1)
break;
velocity.x = -1;
velocity.y = 0;
break;
case 38:
if (velocity.y == 1)
break;
velocity.x = 0;
velocity.y = -1;
break;
case 39:
if (velocity.x == -1)
break;
velocity.x = 1;
velocity.y = 0;
break;
case 40:
if (velocity.y == -1)
break;
velocity.x = 0;
velocity.y = 1;
break;
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment