Search code examples
c++collision-detection

Game Over condition simple Snake c++ game


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


Solution

  • 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;
    }