Space Walk board game
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

75 lines
1.8 KiB

  1. #include <algorithm>
  2. #include "board.h"
  3. #include "spaceship.h"
  4. Board::Board() {
  5. // Reserve 0 SpaceShips of memory for each planet
  6. for (unsigned char i = 0; i < BOARD_SIZE; i++) {
  7. this->planets[i] = new std::vector<SpaceShip *>(0);
  8. }
  9. }
  10. Board::~Board() {
  11. for (auto planet : this->planets) {
  12. delete planet;
  13. }
  14. }
  15. SpaceShip *Board::getShip(unsigned char planet, unsigned char pos) {
  16. if (planet >= BOARD_SIZE || pos >= this->planets[planet]->size()) {
  17. return new SpaceShip;
  18. }
  19. return this->planets[planet]->at(pos);
  20. }
  21. std::vector<SpaceShip *> *Board::getShips(unsigned char planet) {
  22. if (planet >= BOARD_SIZE) {
  23. return nullptr;
  24. }
  25. return this->planets[planet];
  26. }
  27. bool Board::setShip(unsigned char planet, SpaceShip *ship) {
  28. if (planet >= BOARD_SIZE) {
  29. return false;
  30. }
  31. // Insert if the ship doesn't already exist on a planet
  32. if (ship->getPlanet() == PLANET_UNSET) {
  33. ship->setPlanet(planet);
  34. this->planets[planet]->push_back(ship);
  35. this->sortPlanet(planet);
  36. }
  37. return true;
  38. }
  39. bool Board::moveShip(unsigned char planet, SpaceShip *ship) {
  40. char shipPlanet = ship->getPlanet();
  41. if (planet >= BOARD_SIZE || shipPlanet == -1 || shipPlanet == planet) {
  42. return false;
  43. }
  44. auto tmp = this->planets[(unsigned char)shipPlanet];
  45. // Move ship to the end of the vector and then erase the last element
  46. // (Erase-remove idiom)
  47. tmp->erase(std::remove(tmp->begin(), tmp->end(), ship), tmp->end());
  48. ship->setPlanet(planet);
  49. this->planets[planet]->push_back(ship);
  50. this->sortPlanet(planet);
  51. return true;
  52. }
  53. void Board::sortPlanet(unsigned char planet) {
  54. // Sort all ships on the planet, using function/functor/lambda
  55. std::sort(this->planets[planet]->begin(), this->planets[planet]->end(),
  56. [](SpaceShip *s1, SpaceShip *s2) -> bool {
  57. return s1->getSize() > s2->getSize();
  58. });
  59. }