samedi 30 mai 2020

Can't figure out why this conditional statement is only executing once. Perhaps rand()?

Can't figure this out. To begin, I'm calling srand(time(NULL)); in main. Working on implementing the game snake and I'm having trouble getting the apple to randomly appear in another part of the game map. When the snakehead equals the apple (using x, y coordinates), the statement that I've indicated below should execute. It works the first time, but (through testing with various print statements) seems to only be executed once. The initial apple position is hardcoded and thus not set by the (rand() % 18) + 1. It seems to not work when the new coordinates for the apple are set by rand(). Can't figure out why.

void SnakeGame::main_loop()
{
     while (keyboard_input != 113) // q to quit 
    {
        usleep(0.2 * 1000000);
        keyboard_input = wgetch(snake_window);
        this->input_handler();

        if (snake_direction == UP)          { yPos--; }
        else if (snake_direction == DOWN)   { yPos++; } 
        else if (snake_direction == LEFT)   { xPos--; } 
        else if (snake_direction == RIGHT)  { xPos++; } 
        this->snake->move(xPos, yPos);

        if (xPos == xApple && yPos == yApple) // <--- THIS STATEMENT
        {   
            this->getNextApple();
            this->incrementScore();
        }
        draw_field();
    }
}

void SnakeGame::getNextApple()
{
    int xNew;
    int yNew;
    while (1)
    {
        xNew = (rand() % 18) + 1;
        yNew = (rand() % 18) + 1;
        if ( (xNew != this->xPos && yNew != this->yPos) && (this->snake->is_snake(xNew, yNew) == false) )
        {
            break;
        }
    }
    this->xApple = xNew;
    this->yApple = yNew;
}

Been trying to figure this out all day. Any thoughts would be welcome.




Aucun commentaire:

Enregistrer un commentaire