Last active
September 13, 2017 23:22
-
-
Save charleyramm/567116e5e95b59991c2189bbe3abe972 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<canvas id="gc" width="400" height="400"></canvas> | |
<script> // https://youtu.be/xGmXxpIj6vs?t=3m46s | |
window.onload=function() { | |
canv=document.getElementById("gc"); | |
ctx=canv.getContext("2d"); | |
document.addEventListener("keydown",keyPush); | |
setInterval(game,1000/15); | |
} | |
px=py=10; // player x,y | |
gs=tc=20; // grid size, tile count | |
ax=ay=15; // apple x,y | |
xv=yv=0; // x,y velocity | |
trail=[]; // trail array | |
tail = 5; | |
function game() { | |
px+=xv; | |
py+=yv; | |
if(px<0) { // wrap left to right | |
px= tc-1; | |
} | |
if(px>tc-1) { // wrap right to left | |
px= 0; | |
} | |
if(py<0) { | |
py= tc-1; | |
} | |
if(py>tc-1) { | |
py= 0; | |
} | |
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) { // if we hit our trail | |
tail = 5; | |
xv=yv=0; // x,y velocity | |
} | |
} | |
trail.push({x:px,y:py}); | |
while(trail.length>tail){ | |
trail.shift(); | |
} | |
if(ax==px && ay==py) { // if we hit the apple | |
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: // LEFT | |
xv=-1;yv=0; | |
break; | |
case 38: // UP | |
xv=0;yv=-1; | |
break; | |
case 39: // RIGHT | |
xv=1;yv=0; | |
break; | |
case 40: // DOWN | |
xv=0;yv=1; | |
break; | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment