robots/src/GameState.cpp

150 lines
3.4 KiB
C++
Executable File

/**
* Copyright (C) David Wolfe, 1999. All rights reserved.
* Ported to Qt and adapted for TDDD86, 2015.
* Updated for TDDD86, 2021.
*/
#include "GameState.h"
#include "constants.h"
#include "utilities.h"
#include <iostream>
GameState::GameState(int numberOfRobots) {
for (int i = 0; i < numberOfRobots; i++) {
auto *robot = new Robot();
while (!isEmpty(*robot)) {
delete robot;
robot = new Robot();
}
units.push_back(robot);
}
teleportHero();
}
GameState::~GameState(){
clearUnits();
}
void GameState::clearUnits(){
for (Unit *unit: units)
delete unit;
units.clear();
}
GameState &GameState::operator=(const GameState &other) {
if (this == &other)
return *this;
clearUnits();
for (const Unit *const unit : other.units)
units.push_back(unit->clone());
hero = other.hero;
return *this;
}
GameState::GameState(const GameState &other) : hero(other.hero) {
clearUnits();
for (const Unit *const unit : other.units)
units.push_back(unit->clone());
}
GameState &GameState::operator=(GameState &&other) noexcept {
if (this == &other)
return *this;
clearUnits();
hero = std::move(other.hero);
units = std::move(other.units);
other.units.clear();
return *this;
}
GameState::GameState(GameState &&other) noexcept : units(std::move(other.units)), hero(std::move(other.hero)) {
other.units.clear();
}
void GameState::draw(QGraphicsScene *scene) const {
scene->clear();
hero.draw(scene);
for (const Unit *const unit : units)
unit->draw(scene);
}
void GameState::teleportHero() {
do
hero.teleport();
while (!isEmpty(hero));
}
void GameState::moveRobots() {
for (Unit *const unit : units)
unit->moveTowards(hero.asPoint());
}
void GameState::updateCrashes() {
for (unsigned int i = 0; i < units.size(); i++){
Unit *u1 = units[i];
for (unsigned j = i + 1; j < units.size(); ++j) {
Unit *u2 = units[j];
if (!u1->at(*u2))
continue;
if (u1->isAlive())
u1->doCrash();
if (u2->isAlive())
u2->doCrash();
}
}
}
int GameState::countToBeJunked() const {
int numberDestroyed = 0;
for (const Unit *const unit: units)
if (unit->isToBeJunked())
numberDestroyed++;
return numberDestroyed;
}
void GameState::junkTheCrashed() {
for (unsigned int i = 0; i < units.size(); i++) {
Unit *unit = units[i];
if (!unit->isToBeJunked())
continue;
auto *junk = new Junk(unit->asPoint());
delete unit;
units[i] = junk;
}
}
bool GameState::someRobotsAlive() const {
for (const Unit *const unit : units)
if (unit->isAlive()) // Only robots can return true here
return true;
return false;
}
bool GameState::heroDead() const {
for (const Unit *const unit : units)
if (hero.at(*unit))
return true;
return false;
}
void GameState::moveHeroTowards(const Point &dir) { hero.moveTowards(dir); }
Point GameState::getHeroAsPoint() const { return hero.asPoint(); }
/*
* Free of robots and junk
*/
bool GameState::isEmpty(const Unit &unit) const {
for (const Unit *const iterUnit : units)
if (iterUnit->at(unit))
return false;
return true;
}