nsnake
Classic snake game for the terminal
FruitManager.cpp
1 #include <Entities/FruitManager.hpp>
2 #include <Engine/Helpers/Utils.hpp>
3 #include <Config/Globals.hpp>
4 
6  amount(amount)
7 { }
9 {
10  // If any fruit was eaten by #player, we'll
11  // delete it.
12  for (std::vector<Fruit>::iterator it = this->fruit.begin(); it != this->fruit.end();)
13  {
14  if (player->headHit((*it).x, (*it).y))
15  {
16  // Alright, eaten!
17  it = this->fruit.erase(it);
18  return true;
19  }
20  else
21  ++it;
22  }
23  return false;
24 }
25 void FruitManager::update(Player* player, Board* board)
26 {
27  // Creating enough fruits to fill the #amount quota.
28  int diff = (this->amount - this->fruit.size());
29 
30  if (diff > 0)
31  for (int i = 0; i < (diff); i++)
32  this->addRandomly(board, player);
33 }
35 {
36  return (this->amount);
37 }
38 void FruitManager::add(int x, int y)
39 {
40  this->fruit.push_back(Fruit(x, y));
41 }
42 void FruitManager::addRandomly(Board* board, Player* player)
43 {
44  int newx = 1;
45  int newy = 1;
46 
47  // Creating between the board limits,
48  // making sure it isn't inside player's body.
49  do
50  {
51  newx = Utils::Random::between(1, board->getW() - 2);
52  newy = Utils::Random::between(1, board->getH() - 2);
53 
54  } while (player->bodyHit(newx, newy) ||
55  board->isWall(newx, newy));
56 
57  this->add(newx, newy);
58 }
59 void FruitManager::draw(Window* win)
60 {
61  for (unsigned int i = 0; i < (this->fruit.size()); i++)
62  win->print("$",
63  this->fruit[i].x,
64  this->fruit[i].y,
65  Globals::Theme::fruit);
66 }
67 
void add(int x, int y)
Creates a fruit, adding it at #x, #y.
bool eatenFruit(Player *player)
Tells if the #player has eaten a fruit this frame.
Definition: FruitManager.cpp:8
A single fruit.
void update(Player *player, Board *board)
Updates internal fruits, adding them to the #board and making sure it doesn't touch #player.
A level where the snake runs and eats fruits.
Definition: Board.hpp:32
bool isWall(int x, int y)
Tells if there's a wall at #x #y.
Definition: Board.cpp:36
int getAmount()
Returns the maximum size we can store within this manager.
void addRandomly(Board *board, Player *player)
Creates a fruit randomly within boundaries of #board, making sure that it's not inside #player.
bool bodyHit(int x, int y, bool isCheckingHead=false)
Tells if something at #x and #y collides with any part of the snake.
Definition: Player.cpp:147
FruitManager(int amount)
Creates a Fruit container that has at most #amount fruits at once on the screen.
Definition: FruitManager.cpp:5