Coordinator v2

Dependencies:   NerfUSXbee PinDetect EthernetInterface JSON MFRC522 WebSocketClient mbed-rtos mbed

src/GameCoordinator.cpp

Committer:
Ismael Balafrej
Date:
2017-04-11
Revision:
2:019d8848cf7e
Parent:
1:e1c5259b7d9a
Child:
3:501120a68c11

File content as of revision 2:019d8848cf7e:

#include "GameCoordinator.hpp"

GameCoordinator gameCoordinator;

//TODO: move that to .cpp 
GameCoordinator::GameCoordinator()
{
    //Adding all the game modes to the game_modes vector
    //TODO: can we avoid new operator ?
    ReflexMode *reflex_mode = new ReflexMode(&targets);
    SpeedMode *speed_mode = new SpeedMode(&targets);
    game_modes.push_back(reflex_mode);
    game_modes.push_back(speed_mode);

    //Starting internal thread
    Tget_next_round = Thread(osPriorityNormal, 1020);
    Tget_next_round.start(this, &GameCoordinator::get_next_round);
}

void GameCoordinator::start_game(ServerData *configs)
{
    current_game = game_modes[configs->game_id];
    target_timeout = configs->max_reflex_time;
    number_of_targets = configs->number_of_target;
    current_game->reset();
    timer.reset();
    timer.start();
    ticker.attach(callback(this, &GameCoordinator::ticker_callback), current_game->getTimeBetweenTargets() / 1000.0);
}

void GameCoordinator::stop_game()
{
    ticker.detach();
    LPC_TIM3->TC = 0;
    timer.stop();
    ServerEvent stats;
    stats.data = current_game->GetStats();
    stats.data.gameLength = timer.read_ms();
    if (stats.data.targets != 0)
    {
        stats.data.averageReflexTime = stats.data.gameLength / stats.data.targets;
    }
    
    strcpy(stats.event, "report");
    if (on_game_finish != NULL)
    {
        on_game_finish(stats);
    }
}

void GameCoordinator::ticker_callback()
{
    Tget_next_round.signal_set(0x1);
}

//Thread
void GameCoordinator::get_next_round()
{
    while (1)
    {
        Thread::signal_wait(0x1);
        Target *nextTarget = current_game->GetNextTarget();
        if (nextTarget == NULL || number_of_targets-- <= 0)
        {
            stop_game();
        } 
        else
        {
            //TODO: how to select enemy or ally ? rand() % 2
            nextTarget->rise(0, target_timeout);
        }
        Thread::yield();
    }
}

void GameCoordinator::target_hit(int time_taken)
{
    current_game->OnTargetHit(time_taken);
}

void GameCoordinator::target_miss()
{
    current_game->OnTargetMiss();
}