Im mew to javascript and am trying to make a snake game. I have everything minus the loosing part.
Heres my code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var gs = 20;
var xpos = 9 * gs;
var ypos = 9 * gs;
var xvelo = 0;
var yvelo = 0;
var appleX = Math.floor(Math.random() * 20)* gs;
var appleY = Math.floor(Math.random() * 20)* gs;
var tail = [{x:0, y:0}, {x:20 * gs, y:20 * gs}, {x:20 * gs, y:20 * gs}, {x:20 * gs, y:20 * gs}, {x:20 * gs, y:20 * gs}, {x:20 * gs, y:20 * gs}];
document.addEventListener("keydown", keyPressed);
function keyPressed(){
if (event.keyCode == 37) {
xvelo = -1 * gs;
yvelo = 0;
}
if (event.keyCode == 38) {
xvelo = 0;
yvelo = -1 * gs;
}
if (event.keyCode == 39) {
xvelo = 1 * gs;
yvelo = 0;
}
if (event.keyCode == 40) {
xvelo = 0;
yvelo = 1 * gs;
}
}
function fillBackground(){
ctx.beginPath();
ctx.fillStyle = "black";
ctx.rect(0, 0, 20 * gs, 20 * gs);
ctx.fill();
ctx.closePath();
}
function makeApple(applex, appley){
ctx.beginPath();
ctx.fillStyle = "red";
ctx.rect(applex, appley, 1 * gs, 1 * gs);
ctx.fill();
ctx.closePath();
}
function makeSnake(xpos, ypos){
ctx.beginPath();
ctx.fillStyle = "white";
ctx.rect(xpos, ypos, 1 * gs, 1 * gs);
ctx.fill();
ctx.closePath();
}
fillBackground();
setInterval(gameInterval, 1000/5);
function gameInterval(){
console.log("hello");
xpos += xvelo;
ypos += yvelo;
fillBackground();
makeApple(appleX, appleY);
makeSnake(xpos, ypos);
tail.push({x:xpos, y:ypos})
tail.shift();
for (var i = 0; i < tail.length; i++) {
makeSnake(tail[i].x, tail[i].y);
}
if (xpos == appleX && ypos == appleY) {
appleX = Math.floor(Math.random() * 20)* gs;
appleY = Math.floor(Math.random() * 20)* gs;
tail.unshift({x:20 * gs, y:20 * gs});
}
if (xpos <= -1 && xvelo == -1 * gs) {
xpos = 20 * gs;
}
if (xpos >= 21 * gs && xvelo == 1 * gs) {
xpos = -1 * gs;
}
if (ypos <= -1 && yvelo == -1 * gs) {
ypos = 20 *gs;
}
if (ypos >= 21 * gs && yvelo == 1 * gs) {
ypos = -1 * gs;
}
}
The snake should reset whenever it touches part of itself, meaning any value in the tail array, I just don"t know how to make that happen when you have a array that can be infinity long. Anybody know how.
also this is plain javascript with no extra stuff at all. the only other piece of code os some html so i can run it in chrome