-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.cpp
More file actions
106 lines (95 loc) · 2.25 KB
/
SnakeGame.cpp
File metadata and controls
106 lines (95 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <SDL2_ttf/SDL_ttf.h>
#include "SnakeGame.h"
SnakeGame::SnakeGame():
board_(new SnakeBoard),
paused_(false),
time_(SDL_GetTicks()),
score_(0)
{
srand(time(NULL));
board_->draw();
}
SnakeGame::~SnakeGame()
{
delete board_;
}
void SnakeGame::loop()
{
Snake::Direction d = Snake::DIRECTION_NONE;
do
{
if (!paused_ && SDL_GetTicks() > time_ + DELAY)
{
if (d != Snake::DIRECTION_NONE)
{
board_->setSnakeDirection(d);
}
update();
if (board_->isGameOver())
{
gameOver();
}
time_ = SDL_GetTicks();
}
} while(checkUserInput(d));
}
bool SnakeGame::checkUserInput(Snake::Direction &d)
{
SDL_Event e;
if (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_KEYDOWN:
{
if (!paused_)
{
switch (e.key.keysym.sym)
{
case SDLK_UP:
d = Snake::DIRECTION_UP;
break;
case SDLK_DOWN:
d = Snake::DIRECTION_DOWN;
break;
case SDLK_LEFT:
d = Snake::DIRECTION_LEFT;
break;
case SDLK_RIGHT:
d = Snake::DIRECTION_RIGHT;
break;
case SDLK_p:
paused_ = true;
break;
}
}
// If the game is paused, ignore all user input except unpause
else
{
paused_ = e.key.keysym.sym != SDLK_p;
}
}
break;
case SDL_QUIT:
return false;
default:
break;
}
}
return true;
}
void SnakeGame::gameOver()
{
board_->displayGameOverMsg();
board_->reset();
}
void SnakeGame::update()
{
if (board_->snakeAte())
{
board_->feedSnake();
score_++;
}
board_->advanceSnake();
board_->draw();
}