nsnake
Classic snake game for the terminal
FruitManager.cpp
1 #include <Game/FruitManager.hpp>
2 #include <Misc/Utils.hpp>
3 
5  amount(amount)
6 { }
8 {
9  // If any fruit was eaten by #player, we'll
10  // delete it.
11  for (std::vector<Fruit>::iterator it = this->fruit.begin(); it != this->fruit.end();)
12  {
13  if (player->headHit((*it).x, (*it).y))
14  {
15  // Alright, eaten!
16  it = this->fruit.erase(it);
17  return true;
18  }
19  else
20  ++it;
21  }
22  return false;
23 }
24 void FruitManager::update(Player* player, Board* board)
25 {
26  // Creating enough fruits to fill the #amount quota.
27  int diff = (this->amount - this->fruit.size());
28 
29  if (diff > 0)
30  for (int i = 0; i < (diff); i++)
31  this->addRandomly(board, player);
32 }
34 {
35  return (this->amount);
36 }
37 void FruitManager::add(int x, int y)
38 {
39  this->fruit.push_back(Fruit(x, y));
40 }
41 void FruitManager::addRandomly(Board* board, Player* player)
42 {
43  int newx = 1;
44  int newy = 1;
45 
46  // Creating between the board limits,
47  // making sure it isn't inside player's body.
48  do
49  {
50  newx = Utils::Random::between(1, board->getW() - 2);
51  newy = Utils::Random::between(1, board->getH() - 2);
52 
53  } while (player->bodyHit(newx, newy) ||
54  board->isWall(newx, newy));
55 
56  this->add(newx, newy);
57 }
58 void FruitManager::draw(Window* win)
59 {
60  for (unsigned int i = 0; i < (this->fruit.size()); i++)
61  win->print("$",
62  this->fruit[i].x,
63  this->fruit[i].y,
64  Colors::pair(COLOR_RED, COLOR_DEFAULT, true));
65 }
66 
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:7
A single fruit.
A segment of the terminal screen (2D char matrix).
Definition: Window.hpp:16
void update(Player *player, Board *board)
Updates internal fruits, adding them to the #board and making sure it doesn&#39;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&#39;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&#39;s not inside #player...
int between(int min, int max)
Random number between min and max.
Definition: Utils.cpp:48
void print(std::string str, int x, int y, ColorPair pair=0)
Shows text #str at #x #y on the window with color #pair.
Definition: Window.cpp:94
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:146
FruitManager(int amount)
Creates a Fruit container that has at most #amount fruits at once on the screen.
Definition: FruitManager.cpp:4