Hi so i’m working on creating a snake game and ive created an if statement so when the head of the snake (snakeX && snakeY) come into contact with foodX && foodY it’s supposed to randomly change the position of the food. It’s not working. What am I doing wrong?
let foodX, foodY;
let snakeX = 5,
snakeY = 10;
let velocityX = 0,
velocityY = 0;
const changeFoodPosition = () => {
// Passing a random 0 - 30 value as food position
foodX = Math.floor(Math.random() * 30) + 1;
foodY = Math.floor(Math.random() * 30) + 1;
};
const changeDirection = (e) => {
//Changing velocity value of Event (e) Arrow Keys
if (e.key === "ArrowUp") {
velocityX = 0;
velocityY = -1;
} else if (e.key === "ArrowDown") {
velocityX = 0;
velocityY = 1;
} else if (e.key === "ArrowLeft") {
velocityX = -1;
velocityY = 0;
} else if (e.key === "ArrowRight") {
velocityX = 1;
velocityY = 0;
}
};
const initGame = () => {
let htmlMarkup = `<div class='food' style="grid-area: ${foodY} / ${foodY}"></div>`;
// Changing food position if snake head overlaps food
if (snakeX === foodX && snakeY === foodY) {
changeFoodPosition();
}
The variables need to be reevaluated after they change and the DOM needs to be updated. They are not magic state variables that cause re-renders you have to re-render yourself by calling whatever code updates the DOM.
They’re called at the bottom. changeFoodPosition, setInterval, changeDirection and initGame is called at the bottom i just messed up and didnt post all the code like i thought i had.