I am creating a JavaScript game which is very similar to classic arcade Snake game. For every piece of food snake eats it gets +1 on its size starting with size 5. It is contained in canvas of 450X450 px with the size of one cell 10x10 px (picture).
The original game is taken and modified from another source, but my goal is to create autopilot.
This is the function that generates food
function create_food() {
food = {
x: Math.round(Math.random() * (w - cw) / cw),
y: Math.round(Math.random() * (h - cw) / cw),
};
}
Basically it is random number from 0 to width_of_canvas - snake_cell / snake_cell ((450-10)/10). So food has coordinate x and coordinate y. On very similar principle are the snake cells but it is an array with all the snake cells.
function create_snake() {
snake_array = []; //Empty array to start with
length = 5;
for (var i = length - 1; i >= 0; i--) {
//This will create a horizontal snake starting from the top left
snake_array.push({
x: i,
y: 0
});
}
}
Only difference is there are multiple fields in snake array while there is only one in food array.
PROBLEM: I don't want food spawning INSIDE my snake, so I need to check if the coordinates of the food would be same as one of the fields in snake array.
I was thinking of inArray() function but I don't know how to use it in this case.
EXAMPLE: food[0].x = 31; food[0].y = 22
- snake_array[0].x = 28; snake_array[0].y = 22
- snake_array[1].x = 29; snake_array[1].y = 22
- snake_array[2].x = 30; snake_array[2].y = 22
- snake_array[3].x = 31; snake_array[3].y = 22 collision
- snake_array[4].x = 32; snake_array[4].y = 22
EDIT: thanks @Siguza