As a beginner in JavaScript, I've been learning CSS and HTML as well. I decided to practice my skills by creating a snake game without following any tutorials. I know my code might not be the best and lacks good practices, but I'm just doing this for fun.
let playerXpos =0;
let playerYpos =0;
let coordArray = [[playerXpos, playerYpos]];
//player movement
document.addEventListener('keydown', (e) => playerMove(e.key));
function playerMove (key) {
clearInterval(playerRightInterval);
clearInterval(playerLeftInterval);
clearInterval(playerUpInterval);
clearInterval(playerDownInterval);
switch(key) {
case "ArrowRight":
playerRightInterval = setInterval(function () {
if (playerXpos > 67.5) {deathFunction();} else {
playerXpos += 1.5;
playerGrowth();
}
}, 90);
break;
case "ArrowLeft":
playerLeftInterval = setInterval(function () {
if (playerXpos <= 0) {deathFunction();} else {
playerXpos -= 1.5;
playerGrowth();
}
}, 90);
break;
case "ArrowDown":
playerDownInterval = setInterval(function () {
if (playerYpos > 57.5) {deathFunction();} else {
playerYpos += 1.5;
playerGrowth();
}
}, 90);
break;
case "ArrowUp":
playerUpInterval = setInterval(function () {
if (playerYpos <= 0) {deathFunction();} else {
playerYpos -= 1.5;
playerGrowth();
}
}, 90);
break;
}
}
//player growing & more moving
function playerGrowth () {
if (coordArray.includes([playerXpos, playerYpos])) {
console.log("ya dead lol");
}
coordArray.unshift([playerXpos, playerYpos]);
if (playerXpos == appleX && playerYpos == appleY) {
playerArray.push(document.createElement("div"));
playerArray[playerArray.length-1].className = "player";
wholeSnake.appendChild(playerArray[playerArray.length-1]);
playerArray[playerArray.length-1].style.backgroundColor = colourArray[(playerArray.length -1)-(Math.floor((playerArray.length -1)/6)*6)];
appleMove();
} else {
coordArray.pop();
}
for (let i=0; i < coordArray.length; i++) {
playerArray[i].style.marginLeft = coordArray[i][0] + "vh";
playerArray[i].style.marginTop = coordArray[i][1] + "vh";
}
}
I've stored the positions of the "snake pieces" in an array and updated them with .unshift and .pop as the snake moves. To check if the snake hits itself, I attempted to see if the next position is already in the coordinate array. However, I'm facing issues with this logic.
The problematic line is right under the comment section "player growing & more moving."
I've been struggling with this problem for a while, any assistance would be greatly appreciated!