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.

107 lines
2.5 KiB

  1. #include "Snake.h"
  2. #include <iostream>
  3. Snake::Snake(uint32_t headY, uint32_t headX)
  4. :direction_{LEFT}
  5. {
  6. snake_.push_back(Point{headY, headX, '>'});
  7. for (uint32_t i = 1; i <= SNAKE_DEFAULT_SIZE; i++) {
  8. snake_.push_back(Point{headY, headX + i, SNAKE_BODY_CHAR});
  9. }
  10. }
  11. void Snake::updateHead() {
  12. switch (direction_) {
  13. case UP:
  14. snake_.front().moveUp();
  15. break;
  16. case DOWN:
  17. snake_.front().moveDown();
  18. break;
  19. case LEFT:
  20. snake_.front().moveLeft();
  21. break;
  22. case RIGHT:
  23. snake_.front().moveRight();
  24. break;
  25. default:
  26. std::cerr << "[x] This direction does not exist" << std::endl;
  27. // OOPS!
  28. }
  29. }
  30. void Snake::printSnake() const {
  31. // TODO: for each point in snake_ call point.print()
  32. Graphics::get().refreshScreen();
  33. }
  34. void Snake::move() {
  35. auto head = snake_.begin();
  36. auto second = std::next(snake_.begin());
  37. // TODO: the current tail of our snake shoudl be hidden
  38. // TODO: each element, from the tail to the second-to-head
  39. // should move to the position of the element before it
  40. // update the previous to head node
  41. // by copying from head and setting
  42. // the image to be body instead of head
  43. *second = *head;
  44. second->setImg(SNAKE_BODY_CHAR);
  45. updateHead();
  46. printSnake();
  47. }
  48. void Snake::moveUp(){
  49. snake_.front().setImg('v');
  50. direction_ = UP;
  51. move();
  52. }
  53. void Snake::moveDown(){
  54. snake_.front().setImg('^');
  55. direction_ = DOWN;
  56. move();
  57. }
  58. void Snake::moveLeft(){
  59. snake_.front().setImg('>');
  60. direction_ = LEFT;
  61. move();
  62. }
  63. void Snake::moveRight(){
  64. snake_.front().setImg('<');
  65. direction_ = RIGHT;
  66. move();
  67. }
  68. bool Snake::isBitten() const {
  69. const Point& head = snake_.front();
  70. // TODO: return true if any point of the snake has the same position as the head
  71. // remember to skip the head as the snake is not flexible enough to bite off its own head
  72. return false;
  73. }
  74. bool Snake::hasBitSnack(uint32_t snackY, uint32_t snackX) const {
  75. const Point& head = snake_.front();
  76. // TODO: return true if the heads position is on the same coordinates as snack
  77. // and return false otherwise
  78. }
  79. bool Snake::hasCrashedWall() const {
  80. const Point& head = snake_.front();
  81. return (head.getY() < GAME_TOP_WALL_Y) ||
  82. (head.getY() > GAME_BOTTOM_WALL_Y) ||
  83. (head.getX() < GAME_LEFT_WALL_X) ||
  84. (head.getX() > GAME_RIGHT_WALL_X);
  85. }