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.

78 lines
1.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. // update the previous to head node
  38. // by copying from head and setting
  39. // the image to be body instead of head
  40. *second = *head;
  41. second->setImg(SNAKE_BODY_CHAR);
  42. updateHead();
  43. printSnake();
  44. }
  45. void Snake::moveUp(){
  46. snake_.front().setImg('v');
  47. direction_ = UP;
  48. move();
  49. }
  50. void Snake::moveDown(){
  51. snake_.front().setImg('^');
  52. direction_ = DOWN;
  53. move();
  54. }
  55. void Snake::moveLeft(){
  56. snake_.front().setImg('>');
  57. direction_ = LEFT;
  58. move();
  59. }
  60. void Snake::moveRight(){
  61. snake_.front().setImg('<');
  62. direction_ = RIGHT;
  63. move();
  64. }