GameBoard.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /******************************************************************************
  2. * M5Snake : Game board management *
  3. * ------------------------------- *
  4. * Manage the game board (storage in memory and display *
  5. * Author: Olivier Staquet *
  6. * Last version available on https://github.com/ostaquet/M5Snake *
  7. *****************************************************************************/
  8. #ifndef _GAMEBOARD_H_
  9. #define _GAMEBOARD_H_
  10. #include <Arduino.h>
  11. #include <M5Stack.h>
  12. #define LCD_WIDTH 320
  13. #define LCD_HEIGHT 240
  14. #define BLOCK_SIZE 16
  15. #define BLOCK_STATUS_EMPTY 0x00 // Empty block
  16. #define BLOCK_STATUS_HEAD 0x01 // Head of the snake
  17. // All values between 2 and 511 // Body of the snake, greatest value = tail
  18. #define BLOCK_STATUS_CHERRY 0x200 // Cherry to increase the size of the snake
  19. #define DIRECTION_UP 0x01
  20. #define DIRECTION_RIGHT 0x02
  21. #define DIRECTION_DOWN 0x03
  22. #define DIRECTION_LEFT 0x04
  23. class GameBoardClass {
  24. public:
  25. // Initialize
  26. void begin(uint8_t game_cycles = 4);
  27. // Refresh display
  28. void refresh();
  29. // Start the snake
  30. void startSnake();
  31. // Make the snake move on the board
  32. // Return boolean true if OK, false if game over
  33. bool moveSnake();
  34. // Set direction
  35. void setDirection(uint8_t direction);
  36. // Add a ramdom cherry on the board
  37. void addCherry();
  38. // Get the max score
  39. uint16_t getMaxScore();
  40. private:
  41. // Variables
  42. // Current direction
  43. uint8_t current_direction = 0x00;
  44. uint8_t current_head_x = 0x00;
  45. uint8_t current_head_y = 0x00;
  46. // Cycles
  47. uint8_t max_game_cycles = 4;
  48. uint8_t current_game_cycle = 0;
  49. // Keep track of the size of the board
  50. uint8_t board_width = LCD_WIDTH / BLOCK_SIZE;
  51. uint8_t board_height = LCD_HEIGHT / BLOCK_SIZE;
  52. // Game board in memory
  53. uint16_t board_data[LCD_WIDTH / BLOCK_SIZE][LCD_HEIGHT / BLOCK_SIZE];
  54. // Track change of the game board to optimize refresh
  55. uint8_t board_changes[LCD_WIDTH / BLOCK_SIZE][LCD_HEIGHT / BLOCK_SIZE];
  56. // Internal functions
  57. // Set a value in a cell
  58. void setCell(uint8_t x, uint8_t y, uint16_t status);
  59. // Draw a cell with the change indicated
  60. void drawChange(uint8_t x, uint8_t y);
  61. // Remove the tail of the snake (put the biggest cell at blank)
  62. void removeTail();
  63. };
  64. extern GameBoardClass GameBoard;
  65. #endif // _GAMEBOARD_H_