forked from devbean/snake-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgamecontroller.cpp
127 lines (106 loc) · 2.79 KB
/
gamecontroller.cpp
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <QEvent>
#include <QGraphicsScene>
#include <QKeyEvent>
#include <QMessageBox>
#include "gamecontroller.h"
#include "food.h"
#include "snake.h"
GameController::GameController(QGraphicsScene &scene, QObject *parent) :
QObject(parent),
scene(scene),
snake(new Snake(*this)),
isPause(false)
{
timer.start( 1000/33 );
Food *a1 = new Food(0, -50);
scene.addItem(a1);
scene.addItem(snake);
scene.installEventFilter(this);
resume();
}
GameController::~GameController()
{
}
void GameController::snakeAteFood(Food *food)
{
scene.removeItem(food);
addNewFood();
}
//void GameController::snakeHitWall(Snake *snake, Wall *wall)
//{
//}
void GameController::snakeAteItself()
{
QTimer::singleShot(0, this, SLOT(gameOver()));
}
void GameController::handleKeyPressed(QKeyEvent *event)
{
if (!isPause)
switch (event->key()) {
case Qt::Key_Left:
snake->setMoveDirection(Snake::MoveLeft);
break;
case Qt::Key_Right:
snake->setMoveDirection(Snake::MoveRight);
break;
case Qt::Key_Up:
snake->setMoveDirection(Snake::MoveUp);
break;
case Qt::Key_Down:
snake->setMoveDirection(Snake::MoveDown);
break;
case Qt::Key_Space:
pause();
break;
}
else resume();
}
void GameController::addNewFood()
{
int x, y;
do {
x = (int)(qrand() % 200) / 10 - 10;
y = (int)(qrand() % 200) / 10 - 10;
x *= 10;
y *= 10;
} while (snake->shape().contains(snake->mapFromScene(QPointF(x + 5, y + 5))));
Food *food = new Food(x, y);
scene.addItem(food);
}
void GameController::gameOver()
{
disconnect(&timer, SIGNAL(timeout()), &scene, SLOT(advance()));
if (QMessageBox::Yes == QMessageBox::information(NULL,
tr("Game Over"), tr("Again?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes)) {
connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance()));
scene.clear();
snake = new Snake(*this);
scene.addItem(snake);
addNewFood();
} else {
emit closeGameWindow();
}
}
void GameController::pause()
{
disconnect(&timer, SIGNAL(timeout()),
&scene, SLOT(advance()));
isPause = true;
}
void GameController::resume()
{
connect(&timer, SIGNAL(timeout()),
&scene, SLOT(advance()));
isPause = false;
}
bool GameController::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
handleKeyPressed((QKeyEvent *)event);
return true;
} else {
return QObject::eventFilter(object, event);
}
}