biquadris / scoreboard.cc
scoreboard.cc
Raw
#include "scoreboard.h"
#include "block.h"
#include <vector>
#include <algorithm>
#include "board.h"
#include "subscriptions.h"
using namespace std;

Scoreboard::Scoreboard(int players) :players{players} {
  for (int i = 0; i < players; ++i) {
    scores.push_back(0);
  }
}

void Scoreboard::updateByClearedLine(Board *b) {
  const int lines = b->getLastNumLinesCleared();
  const int level = b->getLevel();
  const int player = b->getBoardId();
  const int score = (level + lines) * (level + lines);
  addScore(player, score);
}

void Scoreboard::updateByDestroyedBlock(Block *b) {
  int player = b->getBoardId();
  int level = b->getLevel();
  int score = (level + 1) * (level + 1);
  addScore(player, score);
}

vector<SubscriptionType> Scoreboard::subType() {
  return vector<SubscriptionType>{ SubscriptionType::BoardLinesCleared,
                                   SubscriptionType::BlockDestroyed };
}

void Scoreboard::notify(Subject *whoNotified, SubscriptionType t) {
  vector<SubscriptionType> subs = subType();
  if (find(subs.begin(), subs.end(), t) != subs.end()) {
    if (t == SubscriptionType::BoardLinesCleared) {
      Board *b = dynamic_cast<Board *>(whoNotified);
      updateByClearedLine(b);
    } else {
      Block *b = dynamic_cast<Block *>(whoNotified);
      updateByDestroyedBlock(b);
    }
  }
}

void Scoreboard::addScore(int player, int score) {
  scores[player] += score; 
  updateHighScore();
  notifyObservers(SubscriptionType::ScoreChange);
}

void Scoreboard::updateHighScore() {
  for (auto score : scores) {
      if (score > highScore) highScore = score;  
  }
}

void Scoreboard::resetScore(int player) { 
  scores[player] = 0;
  notifyObservers(SubscriptionType::ScoreChange);
}

int Scoreboard::getPlayerCount() { return players; }

int Scoreboard::getScore(int player) { return scores[player]; }

int Scoreboard::getHighScore() { return highScore; }

void Scoreboard::setHighScore(int score) { highScore = score; }