gamemodel.cpp 1.85 KB
#include "gamemodel.h"

GameModel::GameModel(const othello::OthelloGameEngine& game_engine,
                         QObject*                         parent)
  : QAbstractListModel(parent), m_game_engine{game_engine}
{
}

int GameModel::rowCount(const QModelIndex& parent) const
{
  if (parent.isValid()) return 0;
  return int(boardSize());
}

QVariant GameModel::data(const QModelIndex& index, int role) const
{
  if (!index.isValid()) return QVariant();

  const size_t st_row = size_t(boardSize() - index.row() - 1);
  const auto   piece_id = othello::BitPos(st_row);

  const auto occupied = othello::utility::occupied(m_game_engine.board(), piece_id);


  if (role == OccupiedRole)
    return occupied;
  else if (role == PlayerNrRole) {

    if (!occupied)  {

      return QVariant(-1);
    }

    if (othello::utility::occupied(m_game_engine.pieces(othello::PlayerId::One),
                                   piece_id)) {
      return QVariant(uint(othello::PlayerId::One));
    }
    else if (othello::utility::occupied(
               m_game_engine.pieces(othello::PlayerId::Two), piece_id)) {
      return QVariant(uint(othello::PlayerId::Two));
    }
  }
  else if (role == PieceNrRole) {

    return QVariant(int(piece_id.value()));
  }


  return QVariant();
}

int GameModel::boardSize() const { return int(othello::detail::computeBoardSize()); }

uint GameModel::currentPlayer() const {

  return uint(m_game_engine.currentPlayerId());
}

QHash<int, QByteArray> GameModel::roleNames() const
{
  QHash<int, QByteArray> role_names;
  role_names[OccupiedRole] = "occupied";
  role_names[PlayerNrRole] = "playernr";
  role_names[PieceNrRole] =  "piecenr";

  return role_names;
}

void GameModel::update()
{
  beginResetModel();
  endResetModel();
  emit boardSizeChanged(othello::detail::computeBoardSize());
  emit currentPlayerChanged(size_t(m_game_engine.currentPlayerId()));
}