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.

83 lines
1.7 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. }