guiapplication.cpp 2.62 KB
#include "guiapplication.h"

// othello game library
#include <orangemonkey_ai.h>


// qt
#include <QQmlContext>
#include <QQuickItem>
#include <QQuickWindow>
#include <QTimer>
#include <QDebug>
#include <QThread>

// stl
#include <chrono>
using namespace std::chrono_literals;


GuiApplication::GuiApplication(int& argc, char** argv)
  : QGuiApplication(argc, argv),
    m_game_engine{}, m_model{m_game_engine}, m_app{}
{

  m_app.rootContext()->setContextProperty("gamemodel", &m_model);

  m_app.load(QUrl("qrc:/qml/gui.qml"));

  auto* root_window = qobject_cast<QQuickWindow*>(m_app.rootObjects().first());
  if (root_window) {

    connect(root_window, SIGNAL(endGameAndQuit()), this,
            SLOT(endGameAndQuit()));

    connect(root_window, SIGNAL(boardClicked(int)), this,
            SLOT(boardClicked(int)));

    connect(root_window, SIGNAL(initNewHumanGame()), this,
            SLOT(initNewHumanGame()));

    connect(root_window, SIGNAL(initNewGameVsOrangeMonkeyAI()), this,
            SLOT(initNewGameVsOrangeMonkeyAI()));

    connect(this, &GuiApplication::gameEnded, this,
            &GuiApplication::endOfGameActions);

    connect(this, &GuiApplication::enqueueNextTurn, this,
            &GuiApplication::startNextTurn);

    connect(this, SIGNAL(displayFinalScores(int,int)),
            root_window, SIGNAL(displayFinalScores(int,int)));
  }
}

void GuiApplication::endOfTurn()
{
    m_model.update();
    if (m_game_engine.legalMovesCheck())

    emit enqueueNextTurn();
}

void GuiApplication::startNextTurn()
{
   if (m_game_engine.currentPlayerType() == othello::PlayerType::AI){
        m_game_engine.think(20s);
        endOfTurn();
    }

}

void GuiApplication::boardClicked(int pos)
{
    if (m_game_engine.currentPlayerType() == othello::PlayerType::AI){
        return;
    }
    auto success = m_game_engine.performMoveForCurrentHuman(othello::BitPos{pos});
    if (!success)
        return;

    endOfTurn();
}

void GuiApplication::initNewHumanGame()
{
    m_game_engine.initPlayerType<othello::HumanPlayer, othello::PlayerId::One>();
    m_game_engine.initPlayerType<othello::HumanPlayer, othello::PlayerId::Two>();
    m_game_engine.initNewGame();
    m_model.update();
    emit enqueueNextTurn();
}

void GuiApplication::initNewGameVsOrangeMonkeyAI()
{
    m_game_engine.initPlayerType<othello::HumanPlayer, othello::PlayerId::One>();
    m_game_engine.initPlayerType<othello::monkey_ais::OrangeMonkeyAI, othello::PlayerId::Two>();
    m_game_engine.initNewGame();
    m_model.update();
    emit enqueueNextTurn();
}

void GuiApplication::endGameAndQuit() { QGuiApplication::quit(); }


void GuiApplication::endOfGameActions()
{
}