Browse Source

implement lesson07

lesson07
Constantin Fürst 8 months ago
parent
commit
1cb91031f7
  1. 21
      LESSONS.md
  2. 42
      components/Snake.cpp
  3. 3
      components/Snake.h

21
LESSONS.md

@ -137,3 +137,24 @@ Our snake seems invincible for now and can't eat. Run into a wall - nothing will
Once you're ready, you can _git merge lesson07_. Once you're ready, you can _git merge lesson07_.
--- ---
## Lesson 07
#### Prequisites
None
#### Files
- _components/Snake.cpp_
- _components/Snake.h_
- _main.cpp_
#### Task
The snake just learned to grow by itself! How?
1) See the changes to _components/Snake.*_ and try to understand the new code which allows the snake to grow.
2) Play around with this in _main.cpp_.
Once you're ready, you can _git merge lesson08_.
---

42
components/Snake.cpp

@ -106,3 +106,45 @@ bool Snake::hasCrashedWall() const {
(head.getX() < GAME_LEFT_WALL_X) || (head.getX() < GAME_LEFT_WALL_X) ||
(head.getX() > GAME_RIGHT_WALL_X); (head.getX() > GAME_RIGHT_WALL_X);
} }
uint32_t Snake::getSize() const {
return snake_.size();
}
void Snake::incSize(){
const auto tail = std::prev(snake_.end());
const uint32_t tailX = tail->getX();
const uint32_t tailY = tail->getY();
const auto prev = std::prev(tail);
const uint32_t prevX = prev->getX();
const uint32_t prevY = prev->getY();
if (prevY == tailY){
// if the two last parts are on the same 'height' (horizontal tail direction)
if (prevX < tailX) {
// if the tail continues to the left:
// add one part to the right of the tail
snake_.push_back(Point{tailY, tailX + 1, SNAKE_BODY_CHAR});
}
else {
// if the tail continues to the right:
// add one part to the left of the tail
snake_.push_back(Point{tailY, tailX - 1, SNAKE_BODY_CHAR});
}
}
else {
// if the two last parts are on the same 'width' (vertical tail direction)
if (prevY < tailY) {
// if the tail continues to the upper side:
// add one part facing down
snake_.push_back(Point{tailY + 1, tailX, SNAKE_BODY_CHAR});
}
else {
// if the tail continues to the lower side:
// add one part facing up
snake_.push_back(Point{tailY - 1, tailX, SNAKE_BODY_CHAR});
}
}
}

3
components/Snake.h

@ -28,4 +28,7 @@ public:
bool isBitten() const; bool isBitten() const;
bool hasBitSnack(uint32_t snackY, uint32_t snackX) const; bool hasBitSnack(uint32_t snackY, uint32_t snackX) const;
bool hasCrashedWall() const; bool hasCrashedWall() const;
uint32_t getSize() const;
void incSize();
}; };
Loading…
Cancel
Save