Skip to content

Instantly share code, notes, and snippets.

@lbxa
Created June 4, 2017 11:20
Show Gist options
  • Save lbxa/d75e8dbccbdb4da94daace4a108a2668 to your computer and use it in GitHub Desktop.
Save lbxa/d75e8dbccbdb4da94daace4a108a2668 to your computer and use it in GitHub Desktop.
Snake
<div class="wrapper" style="display:flex;width: 100% !important; height:100% !important;">
<canvas id="gameCanvas" width="400" height="400" style="margin: auto;"></canvas>
</div>
<script>
window.onload = function() {
canvas = document.getElementById("gameCanvas");
canvasBuffer = canvas.getContext("2d");
document.addEventListener("keydown", keyPush);
var fithteenTimesPerSecond = 1000/15;
setInterval(game, fithteenTimesPerSecond);
}
xVelocity = yVelocity = 0;
playerXCoo = playerYCoo = 10;
gridCount = tileCount = 20;
appleXCoo = appleYCoo = Math.floor(Math.random() * gridCount);
trail = [];
tail = 5;
function game() {
playerXCoo += xVelocity;
playerYCoo += yVelocity;
if (playerXCoo < 0) {
playerXCoo = tileCount - 1;
}
if (playerXCoo > tileCount - 1) {
playerXCoo = 0;
}
if (playerYCoo < 0) {
playerYCoo = tileCount - 1;
}
if (playerYCoo > tileCount - 1) {
playerYCoo = 0;
}
canvasBuffer.fillStyle = "navy";
canvasBuffer.fillRect(0, 0, canvas.width, canvas.height);
canvasBuffer.fillStyle = "white";
for (var i = 0; i < trail.length; i++) {
canvasBuffer.fillRect(trail[i].x * gridCount, trail[i].y * gridCount, gridCount - 2, gridCount - 2);
if ((trail[i].x == playerXCoo) && (trail[i].y == playerYCoo)){
tail = 5;
}
}
if ((appleXCoo == playerXCoo) && (appleYCoo == playerYCoo)) {
tail++;
appleXCoo = Math.floor(Math.random()*tileCount);
appleYCoo = Math.floor(Math.random()*tileCount);
console.log(tail);
}
trail.push({x:playerXCoo, y:playerYCoo});
while (trail.length > tail) {
trail.shift();
}
canvasBuffer.fillStyle = "red";
canvasBuffer.fillRect(appleXCoo * gridCount, appleYCoo * gridCount, gridCount - 2, gridCount - 2);
}
function keyPush(event) {
var left, right, up, down;
left = 37; down = 38; right = 39; up = 40;
switch(event.keyCode) {
case left:
xVelocity = -1; yVelocity = 0;
break;
case up:
xVelocity = 0; yVelocity = 1;
break;
case right:
xVelocity = 1; yVelocity = 0;
break;
case down:
xVelocity = 0; yVelocity = -1;
break;
default:
// do nothing
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment