Last active
September 27, 2016 18:18
-
-
Save itayB/ff20be2c09153bbfdba5594e3ff32f0b to your computer and use it in GitHub Desktop.
Snake game - Object Oriented Design
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <list> | |
| #include <unistd.h> | |
| using namespace std; | |
| enum Move { | |
| UP, | |
| RIGHT, | |
| DOWN, | |
| LEFT | |
| }; | |
| class Point { | |
| int x; | |
| int y; | |
| public: | |
| Point(int x, int y) { | |
| this->x = x; | |
| this->y = y; | |
| } | |
| }; | |
| class Snake { | |
| list<Point> body; | |
| public: | |
| // Constructor | |
| Snake() { | |
| body.push_front(Point(0,3)); | |
| body.push_back(Point(0,0)); | |
| } | |
| Point getHeadPoint() { | |
| return *body.begin(); | |
| } | |
| }; | |
| class Board { | |
| public: | |
| void refreshDisplay() { | |
| // print to screen | |
| } | |
| }; | |
| class Game { | |
| private: | |
| Board board; | |
| Snake snake; | |
| Point food; | |
| bool gameOver; | |
| int score; | |
| public: | |
| // Constructor | |
| Game() { | |
| gameOver = false; | |
| score = 0; | |
| raffleNewFoodPoint(); | |
| } | |
| // Destructor | |
| virtual ~Game() { | |
| } | |
| // Getters/Setters | |
| // Other methods | |
| void raffleNewFoodPoint() { | |
| // get num of empty cells by subtract N*M - snake length; | |
| // and calc new point from that | |
| } | |
| Move getNextMove() { | |
| return (Move)(rand() % 3); | |
| } | |
| bool isLegalMove() { | |
| Point snakeHead = snake.getHeadPoint(); | |
| } | |
| bool isLegalMove() { | |
| return true; | |
| } | |
| void play() { | |
| while (!gameOver) { | |
| // get user move | |
| Move next = getNextMove(); | |
| // not crash in borders and in snake body/tail | |
| if (!isLegalMove(next)) { | |
| gameOver = true; | |
| break; | |
| } | |
| if (board.isEatingFood(next)) { | |
| score += 100; // mighted be double by the length of the snake - which is harder | |
| raffleNewFood = true; | |
| } | |
| board.updateSnakeMove(next); | |
| if (raffleNewFood) { | |
| food = board.raffleNewFoold(); | |
| raffleNewFood = false; | |
| } | |
| // refresh board display | |
| board.refreshDisplay(); | |
| sleep(1); | |
| } | |
| cout << "Game over :(\nYour Score: " << score << endl; | |
| } | |
| }; | |
| int main() { | |
| Game game; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment