#include "xandos.hpp"
#include <bb/system/InvokeManager>
#include <bb/system/InvokeRequest>
#include <bb/system/InvokeTargetReply>
#include <bb/cascades/ImageView>
#include <bb/cascades/Application>
#include <QDebug>
#include <QtNetwork/QTcpSocket>
int xandos::m_possibilities[9][9] = { { 1, 1, 0, 0, 1, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0, 1, 1, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0 }, { 1, 0, 1, 0, 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 1, 0, 0, 0 }, { 1, 0, 0, 1, 0, 0, 1, 0, 0 } };
xandos::xandos(bb::cascades::Application* app, QObject *parent)
: QObject(parent)
, m_size(sizeof(m_possibilities) / sizeof(m_possibilities[0]))
, m_gameMatrix({ 0, 0, 0, 0, 0, 0, 0, 0 })
, m_invokeManager(new bb::system::InvokeManager(this))
, m_app(app)
{
}
xandos::~xandos()
{
}
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++) {
m_gameMatrix[i] += m_possibilities[index][i] * player;
if (0 != m_gameMatrix[i] && m_gameMatrix[i] % 3 == 0) {
Q_EMIT won(m_gameMatrix[i] / 3);
stopDroid();
return;
}
}
if (noMoreSelections()) {
Q_EMIT won(-2);
stopDroid();
return;
}
if (send) {
Q_EMIT sendSelection(index);
}
}
void xandos::resetGame()
{
for (int i = 0; i < m_size; i++) {
m_possibilities[i][8] = 0;
if (0 < i) {
m_gameMatrix[i - 1] = 0;
}
}
}
void xandos::startDroid()
{
qDebug() << "requesting to start droid";
bb::system::InvokeRequest request;
request.setTarget("com.example.xandos.droid");
request.setAction("bb.action.START");
request.setMimeType("text/plain");
bb::system::InvokeTargetReply *reply = m_invokeManager->invoke(request);
if (!reply) {
qDebug() << "failed to start droid: " << reply->errorCode();
reply->deleteLater();
}
}
void xandos::stopDroid()
{
qDebug() << "XandOs: requesting to terminate droid";
bb::system::InvokeRequest request;
request.setTarget("com.example.xandos.droid");
request.setAction("bb.action.STOP");
bb::system::InvokeTargetReply *reply = m_invokeManager->invoke(request);
if (!reply) {
qWarning() << "failed to stop droid: " << reply->errorCode();
reply->deleteLater();
}
}
void xandos::droidSelection(const QString choice)
{
if (-1 == choice.toInt()) {
qDebug() << "XandOs: emit droid ready";
Q_EMIT droidReady();
return;
}
bb::cascades::ImageView * image = m_app->findChild<bb::cascades::ImageView*>(choice);
if (image) {
image->setImageSource(QUrl("asset:///images/o.png"));
select(choice.toInt(), -1, false);
} else {
qDebug() << "XandOs: failed to find ImageView: " << choice;
}
}
bool xandos::noMoreSelections()
{
for (int i = 0; i < m_size; i++) {
if (0 == m_possibilities[i][8]) {
return false;
}
}
return true;
}