-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.cpp
151 lines (137 loc) · 3.12 KB
/
Game.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include "Game.h"
Game::Game(QWidget *parent) : QWidget(parent)
{
reset();
}
void Game::reset()
{
initObjects();
timer = new QTimer(this);
timer->start(timestamp);
connect(timer, SIGNAL(timeout()), this, SLOT(step()));
}
void Game::resetSlot()
{
endScreen->close();
disconnect(endScreen, SIGNAL(playAgain()), this, SLOT(resetSlot()));
reset();
}
void Game::initObjects()
{
board = new GameBoard(this);
loadPoints();
pacman = new Pacman(board, 14, 23);
initGhosts();
board->show();
}
void Game::loadPoints()
{
for (int i = 0; i < grid_height; i++)
{
for (int j = 0; j < grid_width; j++)
{
if (matrix[i][j] == super_point)
{
Point *p = new Point(board, j, i, true);
points.append(p);
}
else if (matrix[i][j] == point)
{
Point *p = new Point(board, j, i, false);
points.append(p);
}
}
}
}
void Game::initGhosts()
{
Pinky *pinky = new Pinky(board, 13, 13, pacman);
ghosts.append(pinky);
Blinky *blinky = new Blinky(board, 13, 13, pacman);
ghosts.append(blinky);
Clyde *clyde = new Clyde(board, 14, 14, pacman);
ghosts.append(clyde);
Inky *inky = new Inky(board, 14, 14, pacman, blinky);
ghosts.append(inky);
}
void Game::eatPoint()
{
for (int i = points.size() - 1; i >= 0; i--)
{
if (pacman->canEatPoint(*points.at(i)))
{
if (points.at(i)->isSuper)
{
for (Ghost *ghost : ghosts)
{
ghost->scare();
ghost->reverse();
}
}
delete points.at(i);
points.remove(i);
break;
}
}
}
void Game::showEndScreen(QString str)
{
disconnect(timer, SIGNAL(timeout()), this, SLOT(step()));
endScreen = new EndScreen(this, str, pacman->getScore());
connect(endScreen, SIGNAL(playAgain()), this, SLOT(resetSlot()));
endScreen->show();
board->close();
}
void Game::checkResult()
{
if (points.size() == 0)
{
showEndScreen(QString("You won!"));
return;
}
if (pacman->isDead())
{
showEndScreen(QString("You lost!"));
return;
}
}
void Game::step()
{
pacman->makeMove();
checkCollisions();
moveGhosts();
checkCollisions();
eatPoint();
checkResult();
}
void Game::checkCollisions()
{
for (int i = 0; i < ghosts.size(); i++)
{
if (pacman->collidesWith(*ghosts.at(i)))
{
if (ghosts.at(i)->isScared)
{
ghosts.at(i)->goToInitialPosition();
ghosts.at(i)->finishScare();
pacman->eatGhost();
}
else
{
for (Ghost *ghost : ghosts)
{
ghost->goToInitialPosition();
}
pacman->goToInitialPosition();
pacman->kill();
}
}
}
}
void Game::moveGhosts()
{
for (Ghost *ghost : ghosts)
{
ghost->makeMove();
}
}