/** * Copyright (C) David Wolfe, 1999. All rights reserved. * Ported to Qt and adapted for TDDD86, 2015. */ #include "GameState.h" #include "utilities.h" #include "constants.h" GameState::GameState(){} GameState::GameState(int numberOfRobots) { for (int i = 0; i < numberOfRobots; i++) { Robot *robot = new Robot; while (!isEmpty(*robot)) { robot->teleport(); } robots.push_back(robot); } teleportHero(); } GameState::GameState(const GameState& other) { for (const auto& robot : other.robots) { robots.push_back(robot->clone()); } hero = other.hero; } GameState::~GameState() { for (const auto& robot : robots) { delete robot; } robots.clear(); } GameState& GameState::operator=(const GameState& other) { if (this == &other) return *this; for (const auto& robot : robots) { delete robot; } robots.clear(); for (const auto& robot : other.robots) { robots.push_back(robot->clone()); } hero = other.hero; return *this; } void GameState::draw(QGraphicsScene* scene) const { scene->clear(); for (int i = 0; i < robots.size(); i++) { robots[i]->draw(scene); } hero.draw(scene); } void GameState::teleportHero() { do { hero.teleport(); } while (!isEmpty(hero)); } void GameState::moveRobots() { for (int i = 0; i < robots.size(); i++) { robots[i]->moveTowards(hero); } } int GameState::countCollisions() { int numberDestroyed = 0; for (int i = 0; i < robots.size(); i++) { if (robots[i]->alive()) { if (countRobotsAt(*robots[i]) > 1 || junkAt(*robots[i])) { numberDestroyed++; Junk *junk = new Junk(*robots[i]); delete robots[i]; robots[i] = junk; } } } return numberDestroyed; } bool GameState::anyRobotsLeft() const { for (const auto& robot : robots) { if (robot->alive()) { return true; } } return false; } bool GameState::heroDead() const { return !isEmpty(hero); } bool GameState::isSafe(const Unit& unit) const { for (int i = 0; i < robots.size(); i++) { if (robots[i]->attacks(unit)) { return false; } } return !junkAt(unit); } void GameState::moveHeroTowards(const Unit& dir) { hero.moveTowards(dir); } Hero GameState::getHero() const { return hero; } /* * Free of robots and junk only */ bool GameState::isEmpty(const Unit& unit) const { return countRobotsAt(unit) == 0; } /* * Is there junk at unit? */ bool GameState::junkAt(const Unit& unit) const { for (const auto& robot : robots) { if (robot->at(unit) && !robot->alive()) { return true; } } return false; } /* * How many robots are there at unit? */ int GameState::countRobotsAt(const Unit& unit) const { int count = 0; for (const auto& robot : robots) { if (robot->at(unit) && robot->alive()) { count++; } } return count; }