Created
January 5, 2018 13:09
-
-
Save maqmaqmaq/effd0fa68a57927e56a7bfa34767b6b2 to your computer and use it in GitHub Desktop.
Snake in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<title>Snake Game</title> | |
<link rel="stylesheet" href=""> | |
</head> | |
<body> | |
<canvas id="gc" width="400" height="400"></canvas> | |
<script type="text/javascript"> | |
window.onload = function(){ | |
canv = document.getElementById("gc"); | |
ctx = canv.getContext('2d'); | |
document.addEventListener('keydown',keyPush); | |
setInterval(game,1000/10); | |
}; | |
px=py=10; | |
gs=tc=20; | |
ax=ay=15; | |
xv=yv=0; | |
tail=5; | |
trail = []; | |
function game() | |
{ | |
px+=xv; | |
py+=yv; | |
if(px<0) | |
{ | |
px = tc-1; | |
} | |
if(px>tc-1) | |
{ | |
px = 0; | |
} | |
if(px<0) | |
{ | |
px = tc-1; | |
} | |
if(px<0) | |
{ | |
px = tc-1; | |
} | |
ctx.fillStyle = "black"; | |
ctx.fillRect(0,0,canv.width,canv.height); | |
ctx.fillStyle = "lime"; | |
for(var i=0;i<trail.length;i++) | |
{ | |
ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2); | |
if (trail[i].x == px && trail[i].y == py) | |
{ | |
tail = 5; | |
} | |
} | |
trail.push({ x:px,y:py}); | |
while(trail.length > tail) | |
{ | |
trail.shift(); | |
} | |
if (ax == px && ay == py) | |
{ | |
tail++; | |
ax = Math.floor(Math.random()*tc); | |
ay = Math.floor(Math.random()*tc); | |
} | |
ctx.fillStyle = "red"; | |
ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2); | |
} | |
function keyPush(evt) | |
{ | |
switch(evt.keyCode) | |
{ | |
case 37: | |
xv=-1;yv=0; | |
break; | |
case 38: | |
xv=0;yv=-1; | |
break; | |
case 39: | |
xv=1;yv=0; | |
break; | |
case 40: | |
xv=0;yv=1; | |
break; | |
} | |
} | |
</script> | |
</body> | |
</html> |
My friend also did something similar!
Though I don't no how to run it on this website,maybe you cant?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey what a coincidence I coded this as well just my code is a bit messy