I know this is rookie code, but it's the first project I've made. I thought my logic was working, but sadly the fruit still manages to spawn on the snake's body.
Note: The sf::Vector2f 'movement' is what I'm setting the head's position to earlier in the code.
The std::vector<sf::RectangleShape> snake_body is a container that holds all of the snake's body tiles.
The random_location y coordinate has 1 being added to it because at the top of the screen is an extra row of tiles where a score counter is located, and the player cannot go there.
Everything works fine in my game except the spawning of the fruit is on the Snake's body. I know I can fix some things, but this specific problem I've been working on for hours with no success. Here's my function to spawn the fruit:
sf::Vector2f spawn_fruit(sf::Vector2f movement, sf::RectangleShape fruit, std::vector<sf::RectangleShape> snake_body) {
sf::Vector2f random_location;
std::srand(time(NULL));
// flag set to true to loop to see if there is actually collision
bool collision = true;
while (collision) {
// if there is no collision, it will stay false
collision = false;
// set spawn location based on time elapsed (cheap way to make random numbers)
random_location.x = rand() % GRID_WIDTH;
random_location.y = rand() % GRID_HEIGHT + 1;
// make sure x and y isn't the same as the snake's current x and y
if (random_location.x == movement.x && random_location.y == movement.y) collision = true;
// make sure x and y isn't the same as snake body's current x and y
for (int i = 0; i < snake_body.size(); i++) {
if (snake_body[i].getPosition().x == random_location.x && snake_body[i].getPosition().y == random_location.y) {
collision = true;
break;
}
}
}
// return the vector
return random_location;
}
Any help would be much appreciated. Thanks!
Aucun commentaire:
Enregistrer un commentaire