So one project that I tried for learning JavaScript was a snake game; I’ll put the code down below:
<canvas id="gc" width="400" height="400"></canvas> //window size
<script>
window.onload=function() {
canv=document.getElementById("gc"); //set canvas to window properties
ctx=canv.getContext("2d"); //set type of canvas, 2 axis or 2d
document.addEventListener("keydown",keypush);
setInterval(game,1000/15); // interval time that calls a game function 15 times per second? Snake works on a very low frame-rate
}
px=py=10; //snake position, where it starts
gs=tc=20; //gs gridsize, tc tilecount
ax=ay=15; // apples for x & y?
xv=yv=0; // snake velocity
trail=[]; // array for snake tail, you need to keep track of previous path taken
tail = 5; //initial lenght of snake tail
function game() { // game function that is 15 times per second
px+=xv; // px = px + xv;
py+=yv;
//wrap for player position, imagine grid that has lower-left corner as (0,0) and upper right corner as (20,20).
if(px<0){ //if x position is less than zero
px= tc-1; //then set x position to 20-1
}
if(px>tc-1){ // if x position is more than 20-1
px= 0; // then set x position to 0
}
if(py<0){ // if y position is less than 0
py= tc-1; // then set y position to 20-1
}
if(py>tc-1){ // if y position is more than 20-1
py= 0; // set y position to 0
}
ctx.fillStyle="black"; //fill canvas with black background color
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 you step on your own tail, reset tail length
tail = 5;
}
}
trail.push({x:px,y:py}); //push is to add, you are adding x & y positions to array
while(trail.length>tail){
trail.shift();
}
// lengthen tail by 1 if you step on an apples
if(ax==px && ay==py) { // step on apple means snake position and apple position are same
tail++;
//randomize apple position, floor to insure integer
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); //what is ax & ay? gs is gridscale(20). 18 canvas width, 18 canvas height?
}
function keyPush(evt) { // function that event listener is using
switch(evt.keyCode){ // using cases (like if-then statements)
case 37: // code for arrow keys; Left arrow key
xv=-1;yv=0; //x-velocity, y-velocity set value
break;
case 38: // down arrow key
xv=0;yv=-1;
break;
case 39: // right arrow key
xv=1;yv=0;
break;
case 40: // up arrow key
xv=0;yv=1;
break;
}
}
</script>
The code works just fine as an HTML file, as long as you take out the comments. I’ll see if I can load the game directly into this web page at a later date.
