Exemple #1
0
//! [2]
void xandos::select(int index, int player, bool send)
{
    if (0 > index || 8 < index) {
        qDebug() << "XandOs: invalid index ->" << index;
        return;
    }

    m_possibilities[index][8] = 1;
    for (int i = 0; i < 8; i++) {
        // Add the matrix at the selected index to the game matrix
        // multiply the matrix values based on player, if its user than
        // matrix row addition is used, matrix subtraction otherwise for the droid
        m_gameMatrix[i] += m_possibilities[index][i] * player;
        if (0 != m_gameMatrix[i] && m_gameMatrix[i] % 3 == 0) {
            // emit wining signal if any matrix value equals 3
            Q_EMIT won(m_gameMatrix[i] / 3);
            stopDroid();
            return;
        }
    }
    if (noMoreSelections()) {
        // emit tie signal if there are no more choices available
        // since there is only two players (1,-1) that means -2
        // represents a tie
        Q_EMIT won(-2);
        stopDroid();
        return;
    }
    if (send) {
        Q_EMIT sendSelection(index);
    }
}
//! [2]
void xandosdroid::onInvoked(const bb::system::InvokeRequest& request) {
    if (request.action().compare("bb.action.START") == 0) {
        qDebug() << "XandOsDroid : start requested";
        // once the headless is started, communicate back to ui that its ready to play
        connectToServer();
    } else if (request.action().compare("bb.action.STOP") == 0) {
        qDebug() << "XandOsDroid: stop request";
        // terminate headless droid
        terminateDroid();
    } else if (request.action().compare("bb.action.CHOICE") == 0) {
        int choice = QString(request.data()).toInt();
        qDebug() << "XandOsDroid: received user choice: " << choice;
        // mark the user selection in the grid matrix and update the
        // game matrix state
        select(choice, 1);
        // verify there are still moves available
        if (availableChoices().isEmpty()) {
            qDebug() << "XandOsDroid: game over!";
            terminateDroid();
        }
        // Check whether you have any two in a row sequences
        int nextM = nextMove(-2);
        // If no, than block the user based on his possible selections for
        // a consecutive sequence
        if (-1 == nextM) {
            nextM = nextMove(1);
        }
        qDebug() << "XandOsDroid: droid selection: " << nextM;
        // send your next selection to the UI.
        sendSelection(nextM);

    } else {
        qDebug() << "XandOsDroid : unknown service request "
                << request.action();
    }
}