const snake = [[0,0],[1,1],[1,2]];
for (let i = 0 ; i < 9 ; i++){
randomiseFoodLocation();
}
function randomiseFoodLocation(){
let x = 0
let y = 0;
for (let check = 0 ; check == 0;){
x = Math.floor(Math.random() * (2));
y = Math.floor(Math.random() * (2));
for (let j = 0 ; j < snake.length ; j++){
if (x!=snake[j][0] && y!=snake[j][1]){
check++;
}
}
}
console.log("Food Location = "+x+","+y);
}
console.log("snake = "+snake);
What I want to achieve is to
1 select random x and y coordinates on my grid which works
and
2 check if those coordinates are empty which doesn’t
I also have a visual depiction of where the snake is on the grid and where the food is located I won’t however I cannot post it here as it is required for code in posts to be limited to the absolute minimum required to show a proble which I would consieder to be the above as such I provide
1 a pastebin link to the source code of the full project https://pastebin.com/KaeEFh3M
2 a pastebin link to the source code of the display of the error https://pastebin.com/umm3g1m6
also I am aware of the fact that I’m checking the index 0 of snake which is equal to 0 yes starting the check from 1 does in fact result in having no food positions equal to any of the snake positions however it does also result in no positions anywhere along the y axis of the snake and stops working as soon as the snake starts moving around in the x axis
2
Answers
I solved the problem but the answer wouldn't solve anybody elses problem I kinda just remembered that I've already made a system to detect if a specific spot is a snake or not So I just reused that as a patchy workaround I still have no Idea why does this not work
Try
check = 1
instead ofcheck++
.check++
may not stop the loop.I hope it helps.