r/cpp_questions • • 6d ago

OPEN I have trouble with testing my Controller module

I'm coding the classic Snake game using Cpp + Qt. Right now, one of my modules is a GameController, that conects the other classes (snake, apple and board), for the game loop:

/* the class atributes: 
private: 
  std::unique_ptr<Board> game_board; 
  Snake game_snake; 
  Apple game_apple; 
  int score; 
  Snake::direction key_pressed; 
  QTimer *timer; */

GameController::GameController(std::unique_ptr<Board> next_board):game_board{std::move(next_board)}, game_snake(calculate_snake_initial_position(game_board->getInitialPosition())), game_apple(calculate_apple_position()),score{0} { timer = new QTimer(this); connect(timer,&QTimer::timeout,this,&GameController::GameTick); 
key_pressed = Snake::left; 
}

  QPoint GameController::calculate_apple_position()
    {
        QList<QPoint> free_cells = game_board->getValidPositions();
        QPoint new_coordinates;
        bool found;

        do{
            std::srand(std::time(0));
            int random_value = std::rand();

            new_coordinates.setX(free_cells[random_value % free_cells.size()].x());
            new_coordinates.setY(free_cells[random_value % free_cells.size()].y());

            found = game_snake.is_occupied(new_coordinates);
        }while(!found);

        game_board->occupyCell(new_coordinates); 
    }

    QList<QPoint> GameController::calculate_snake_initial_position(QPoint head)
    {
        QList<QPoint> snake_body;
        snake_body.push_back(head);

        game_board->occupyCell(head);

        for(int i = 0; i < 3; i++){
            head.setX(head.x()+1);
            snake_body.push_back(head);
            game_board->occupyCell(head);
        }

        return snake_body;
    }

    void GameController::end_game(bool ending_status)
    {
        stop_timer();

        emit game_finalized(ending_status);
    }


    bool GameController::key_validation(int key)
    {
        bool right_key = false;

        if(key == Qt::Key_W || Qt::Key_Up){
            key_pressed = Snake::up;
            right_key = true;
        }
        else if(key == Qt::Key_A || Qt::Key_Left){
            key_pressed = Snake::left;
            right_key = true;
        }
        else if(key == Qt::Key_S || Qt::Key_Down){
            key_pressed = Snake::down;
            right_key = true;
        }
        else if(key == Qt::Key_D || Qt::Key_Right){
            key_pressed = Snake::right;
            right_key = true;
        }

        return right_key;
    }

    void GameController::start_timer()
    {
        timer->start(300);
    }

    void GameController::stop_timer()
    {
        timer->stop();
    }

    void GameController::GameTick(){


        if(game_board->getValidPositions().empty()) 
        {
            end_game(true);
        }
        else if(game_board->colisionedWithBoard(game_snake.head()))
        {
            end_game(false);
        }
        else
        {
            bool crece = false;
            if(game_snake.is_occupied(game_apple.position())) 
            {
                game_apple.position(calculate_apple_position());
                game_board->occupyCell(game_apple.position());
                emit apple_render_requested(game_apple);

                score+=10;
                emit score_render_requested(score);

                crece = true;
            }
            game_snake.move(key_pressed,crece);
            game_board->occupyCell(game_snake.head());
            if(!crece) game_board->freeCell(game_snake.tail());
            emit snake_render_requested(game_snake);
        }
    }

However, now I'm writing the tests and I realized that I don't have a way to really test it. If I want to test if the new apple position is generated correctly, I can't access the board or the apple to do so. I can check if its inside the permited board space by hardcoding it, but I think it is a bad practice. The same goes for snake position, the key validation, constructor...

The one that seems fine is the GameTick, has I just need to check if It throws signals correctly.

My first guess is to refactor the code, or move it to their respective classes, but I don't want to do the latter unless is the only way, has I want them to be isolated from each other in order to keep coupling as low as possible.

2 Upvotes

2 comments sorted by

2

u/hadrabap 6d ago

You want to open your composition in such a way where all the resources (objects used by your controller) are instantiated externally and passed to the controller by ref or pointer ready-made to be used. Your tests will create these resources, and as they're the owners they'll have access to them.

2

u/heyheyhey27 6d ago

Quick and dirty option: add private: friend class MyTestSuite; then in your tests define a class MyTestSuite. It will be able to read private data from the main class

A nicer alternative is to add getters. Objects should have safe public getters to any data that may be relevant to outsiders. This helps with unit-tests, though not with tests that need to read internal state.

Another tool is asserts. assert(b) will crash debug builds when b is false. This helps ensure that vital assumptions are valid, but should not be used for user-facing code since it's debug-only and always produces a hard crash.

A common high-effort solution for game/UI tests is to refactor the control code into an interface, which test code can implement to pretend to be a user. You feed hard-coded control inputs and check what happens. This can also be used to skip the rendering of a game for "headless" test runs.

Something else you need to do for tests is offer an alternative to std::srand(std::time(0)) which is repeatable, either a seed or a hard-coded initial state.