Skip to content

Commit

Permalink
Fix infinite loop when no more room for apple
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisD3D committed Apr 1, 2024
1 parent 015f857 commit 56c500a
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/jeu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,15 @@ bool Jeu::init() {
dirSnake = map.getInitDirection();


std::uniform_int_distribution<> distr(0, map.getWidth() - 1);
std::uniform_int_distribution distr(0, map.getWidth() - 1);
int attempts = 0;
do {
applePos.x = distr(gen);
applePos.y = distr(gen);
attempts++;
if (attempts > 2 * map.getWidth() * map.getHeight()) {
return false;
}
} while (!posValide(applePos, APPLE_SPAWN));

return true;
Expand Down Expand Up @@ -82,9 +87,14 @@ void Jeu::evolue() {
if (posTest == applePos) {
// The snake eats the apple, place a new apple
std::uniform_int_distribution<> distr(0, map.getWidth() - 1);
int attempts = 0;
do {
applePos.x = distr(gen);
applePos.y = distr(gen);
attempts++;
if (attempts > 2 * map.getWidth() * map.getHeight()) {
break; // TODO: lose / win condition ?
}
} while (!posValide(applePos, APPLE_SPAWN));
// Don't remove the last element of the snake to make it grow
} else {
Expand All @@ -93,7 +103,7 @@ void Jeu::evolue() {
}
} else {
// Game over
snake.clear();
snake.clear(); // TODO: lose condition
}
}

Expand Down

0 comments on commit 56c500a

Please sign in to comment.