Reputation: 23
I have basic knowledge of c++ and am trying to create a simple Snake game that runs in a while loop, as long as a "Game Over" condition evaluates to false. If it turns to "true" (when the snakes head goes out of bounds), "Game Over!" is printed on a lcd screen.
For some reason, the code skips directly to the game over screen without running the game itself.
My code involves a few classes, and in one of those I have a collision detection function that looks like this:
bool SnakeEngine::collision_detection()
{
// check the snake coordinates so that the head doesn't go off screen
if (_head_y < 1) {
return 1;
}
if (_head_y > HEIGHT - 4) {
return 1;
}
if (_head_x < 1) {
return 1;
}
if (_head_x > WIDTH - 4) {
return 1;
} else {
return 0;
}
}
And in the main loop I have:
int main()
{
snake.draw(lcd); // draw the initial game frame and the sprites
lcd.refresh();
while(!snake.collision_detection()) {
snake.read_input(pad); // reads the user input
snake.update(pad); // updates the sprites positions and calls the collision_detection() function
render(); // clears the lcd, draws the sprites in the updated positions, refreshes the lcd
wait(1.0f/fps);
}
lcd.printString("Game Over!",6,4);
lcd.refresh();
}
How come is this not working? Thank you
Upvotes: 0
Views: 1620
Reputation: 6298
The collision detection is a suspect. If all specific conditions which you check do not return true
(1
) the final result should be false
(0
).
This condition is too restrictive:
if (_head_x > WIDTH - 4) {
return 1;
} else {
return 0;
}
It should be limited to:
if (_head_x > WIDTH - 4) {
return 1;
}
return 0;
The modified code with the use of bool
types true
and false
looks like:
bool SnakeEngine::collision_detection()
{
// check the snake coordinates so that the head doesn't go off screen
if (_head_y < 1) {
return true;
}
if (_head_y > HEIGHT - 4) {
return true;
}
if (_head_x < 1) {
return true;
}
if (_head_x > WIDTH - 4) {
return true;
}
return false;
}
Upvotes: 1
Reputation: 5166
Try this, just guessing.I think when all the four conditions are false, than you should conclude that there is no collision. I think you did a blunder in the last else
statement in your collision_detection()
.
bool SnakeEngine::collision_detection()
{
// check the snake coordinates so that the head doesn't go off screen
if ( _head_y < 1 || _head_y > (HEIGHT - 4) || _head_x < 1 || _head_x > (WIDTH - 4) )
return true;
return false;
}
Upvotes: 0