-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.cpp
803 lines (578 loc) · 17.7 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#include "Game.h"
/*----------------------------------------------------------------------------------------------*/
/* First function that is called on the object
* Basically direct the player to the game/insturctions/exit
*/
void Game::init() {
getLevels();
char choice;
bool singleLevelChosen = false;
while (true) {
bool won = true;
int currentLevel = 0;
printMenu(choice);
if (choice == '1')
{
system("cls");
if (levelNames.size() == 0) {
cout << banner;
cout << "Sorry!\nIt appears there are available .screen files in the current directory.\n";
cout << "Press any button to go back to main screen\n";
_getch();
continue;
}
if (!singleLevelChosen)
{
levelNames.clear();
getLevels();
}
else {
singleLevelChosen = false;
}
Player player;
// Start Game:
while (currentLevel < levelNames.size() && levelNames.size() > 0) {
try {
board2 = new Board(levelNames[currentLevel]);
}
catch (Error& err) {
string nameOfLevel = levelNames[currentLevel];
std::size_t slash = nameOfLevel.find_last_of("\\"); // find last slash in file path
std::size_t dot = nameOfLevel.find_last_of(".screen"); // find where ending .screen
int a = nameOfLevel.substr(slash + 1).length() - 7; // get substring len - ".screen"
nameOfLevel = nameOfLevel.substr(slash + 1, a); // file name
cout << nameOfLevel << endl << err.getMsg() << endl;
cout << "Press any key to continue... " << endl;
_getch();
system("cls");
currentLevel++;
continue;
}
// Else, Board was legal, let's play KENNYYYY
for (int i = 0; i < terminal_Size_X; i++)
{
for (int j = 0; j < terminal_Size_Y; j++)
{
board[i][j] = board2->getChar(i, j);
}
}
player.setPosition(board2->getPlayerStartPos());
player.zeroFood();
if (saveMode) {
steps.open(fileNameSteps(levelNames[currentLevel]), std::ios::out | std::ofstream::trunc);
result.open(fileNameResult(levelNames[currentLevel]), std::ios::out | std::ofstream::trunc);
}
won = startGame(player);
delete board2;
if (won) {
// Load next Stage
currentLevel++;
if (saveMode) {
steps.close();
result.close();
}
}
else { // Lost
printMessage(LOST);
if (saveMode) {
steps.close();
result.close();
}
break;
}
}
if (won)
printMessage(WON);
}
else if (choice == '2') {
system("cls");
char temp;
setTextColor(Color::LIGHTGREY);
cout << banner;
cout << "Hello what difficulty would you like to play?\n\n";
cout << "Deafult difficulty is BEST\n";
cout << "a) BEST\n";
cout << "b) GOOD\n";
cout << "c) NOVICE\n";
temp = _getch();
temp = tolower(temp);
if (temp == 'a' || temp == 'b' || temp == 'c')
{
setDifficulty(temp);
}
else {
cout << "invalid option!" << endl;
cout << "press any key to return to main menu" << endl;
_getch();
}
}
else if (choice == '3') {
system("cls");
setTextColor(Color::LIGHTGREY);
cout << banner;
cout << "Do you want to play the game with colors? \nn counts as a no, any other key pressed would count as a Yes. " << endl;
char temp = _getch();
if (tolower(temp) != 'n')
withColor = true;
else
withColor = false;
}
else if (choice == '4') {
levelNames.clear();
getLevels();
system("cls");
cout << banner;
cout << "Select a level you wish to play by entering it's index (1,2...)\n";
for (size_t i = 0; i < levelNames.size(); i++)
{
std::size_t slash = levelNames[i].find_last_of("\\"); // find last slash in file path
std::size_t dot = levelNames[i].find_last_of(".screen"); // find where ending .screen
int a = levelNames[i].substr(slash + 1).length() - 7; // get substring len - ".screen"
cout << i +1 << ". " << levelNames[i].substr(slash + 1, a) << endl; // file name
}
string userInput;
std::getline(cin, userInput);
if (!checkIfInt(userInput))
{
cout << "There is no such level\n";
cout << "Press any key to return to main menu\n";
_getch();
continue;
}
int selectedLevel = std::stoi(userInput);
if (selectedLevel >= 1 && selectedLevel <= levelNames.size())
{
selectedLevel--;
}
else {
cout << "There is no such level\n";
cout << "Press any key to return to main menu\n";
_getch();
continue;
}
string selectedLevelPath = levelNames[selectedLevel];
levelNames.clear();
levelNames.push_back(selectedLevelPath);
singleLevelChosen = true;
}
else if (choice == '8') {
instructions();
}
else if (choice == '9') {
return;
}
}
}
/*----------------------------------------------------------------------------------------------*/
/* pacman_*.screen
* lexicografical order
*/
void Game::getLevels() {
std::string path = fs::current_path().string();
for (const auto& entry : fs::directory_iterator(path)) {
if (std::filesystem::path(entry).extension() == ".screen") {
levelNames.push_back(entry.path().string());
}
}
}
/*----------------------------------------------------------------------------------------------*/
/* Prints the Starting Menu of the game
* Will print until the user chooses valid input
*/
void Game::printMenu(char& choice) {
bool check = false;
system("cls");
setTextColor(Color::LIGHTGREY);
cout << banner;
cout << "Welcome to pacman game :)" << endl;
cout << "Please select an Option from the screen:" << endl;
cout << "1. Start Game" << endl;
cout << "2. Select Game Difficulty" << endl;
cout << "3. Select Color Mode" << endl;
cout << "4. Select a Specific level" << endl;
cout << "8. Present instructions and keys" << endl;
cout << "9. Exit" << endl;
choice = _getch();
if (choice >= '1' && choice <= '9') check = true;
while (!check) {
system("cls");
cout << banner;
cout << "Welcome to pacman game :)" << endl;
cout << "Please select an Option from the screen:" << endl;
cout << "1. Start Game" << endl;
cout << "2. Select Game Difficulty" << endl;
cout << "3. Select Color Mode" << endl;
cout << "4. Select a Specific level" << endl;
cout << "8. Present instructions and keys" << endl;
cout << "9. Exit" << endl;
choice = _getch();
if (choice >= '1' && choice <= '9')
check = true;
}
}
/*----------------------------------------------------------------------------------------------*/
/* Prints the instructions of the game
*/
void Game::instructions() {
system("cls");
setTextColor(Color::LIGHTGREY);
cout << banner;
cout << "PACMAN GAME\n"
" \n"
" Move left: " << "a" << "\n"
" Move right: " << "d" << "\n"
" Move up: " << "w" << "\n"
" Move down: " << "x" << "\n"
" Stop move: " << "s" << "\n"
"\n"
" You are PACMAN. You look like: " << '@' << "\n"
" Collect all the dots. They look like: " << FOOD << "\n"
" Avoid the ghosts. They look like: " << "&" << "\n"
"\n"
" Good luck!\n\n"
" Press any key to return to Main Menu... \n"
"\n\n\n";
_getch();
}
/*----------------------------------------------------------------------------------------------*/
/* Function that runs the actual game loop/logic of the game
*/
bool Game::startGame(Player& player) {
long int gameLoops = 1;
system("cls");
printBoard2();
bool continueGame = false;
bool MoveGhost = false;
int MoveFruit = 0;
int FruitSpawn = rand() % Fruit_Spawn_Rate;
bool lostGame = false;
bool wonLevel = false;
vector <Ghost*> ghosts;
if (difficultyLevel == BEST) {
for (int i = 0; i < board2->getGhostNum(); i++) {
ghosts.push_back(new Ghost_Expert(board2->getGhostsStartPos()[i]));
}
}
else if (difficultyLevel == GOOD) {
ghosts.push_back(new Ghost_Expert(board2->getGhostsStartPos()[0]));
for (int i = 1; i < board2->getGhostNum(); i++) {
ghosts.push_back(new Ghost_Intermediate(board2->getGhostsStartPos()[i]));
}
}
else { //difficultyLevel == NOVICE
ghosts.push_back(new Ghost_Intermediate(board2->getGhostsStartPos()[0]));
for (int i = 1; i < board2->getGhostNum(); i++) {
ghosts.push_back(new Ghost_Novice(board2->getGhostsStartPos()[i]));
}
}
Fruit fruit(0, 0);
if (ghosts.size() > 0)
{
fruit.setPosition(ghosts[0]->getPosition());
}
else {
fruit.setPosition(player.getPosition());
}
char ch = STAY;
char temp = STAY;
do {
printStats(player.getLives(), player.getPoints(), player.getFood());
hideCursor();
if (_kbhit()) {
ch = _getch();
}
if (ch == 27) {
system("cls");
bool esc = printMessage(PAUSE);
ch = tolower(temp);
if (esc) {
return false;
}
printBoard2();
}
moveFruit(fruit, MoveFruit);
//write fruit move
movePlayer(player, ch, temp);
//write player move to file
Sleep(SPEED);
if (_kbhit()) {
ch = _getch();
}
hideCursor();
if(withColor)
setTextColor(Color::YELLOW);
player.draw();
moveGhosts(ghosts, MoveGhost, player.getPosition());
//write ghost moves to file
if (!fruit.getAlive()) {
fruit.Delete(board);
FruitSpawn = rand() % Fruit_Spawn_Rate;
if (FruitSpawn == 0) {
fruit.setAlive(ALIVE,board);
findFruitSpawnPoint(fruit, player, ghosts);
if (saveMode)
steps << "Fruit new Position: X: " << fruit.getPosition().getX() << ",Y: " << fruit.getPosition().getY();
}
}
if (checkCollision(player, ghosts))
{
if (saveMode)
result << "Pacman died: " << gameLoops << endl;
if (player.getLives() > 1)
{
respawn(player, ghosts);
}
else {
lostGame = true;
}
}
checkFruitCollision(player, ghosts, fruit);
if (player.getFood() == board2->getMaxFood())
{
wonLevel = true;
if(saveMode)
result << "Pacman Finished the Screen: " << gameLoops << endl;
}
steps << endl;
gameLoops++;
} while (!lostGame && !wonLevel);
// free ghost memory:
for (int i = 0; i < ghosts.size(); i++) {
delete ghosts[i];
}
if (lostGame) {
return false;
}
return true;
// go to next screen.......................
}
/*----------------------------------------------------------------------------------------------*/
/* Prints in the side of the screen the Player's lives and points
*
* the LEGENDDD
* 3 rows X 20 cols
*/
void Game::printStats(int lives = 3, int points = 0, int food = 0) {
board2->getLegendPos();
setTextColor(Color::LIGHTGREY);
gotoxy(board2->getLegendPos().getX(), board2->getLegendPos().getY());
cout << "Lives: " << lives;
gotoxy(board2->getLegendPos().getX(), board2->getLegendPos().getY() + 1);
cout << "Points: " << points;
gotoxy(board2->getLegendPos().getX(), board2->getLegendPos().getY() + 2);
cout << "Food: " << food;
}
/*----------------------------------------------------------------------------------------------*/
/* Moves the Pacman
*/
void Game:: movePlayer(Player& player, char ch, char& temp) {
ch = tolower(ch);
if (ch == UP || ch == DOWN || ch == RIGHT || ch == LEFT)
{
temp = ch;
player.move(ch, board, withColor,board2->getSecretPathWays());
}
else if (ch == STAY) {
temp = ch;
}
else {
player.move(tolower(temp), board, withColor, board2->getSecretPathWays());
}
if (saveMode)
steps << "Pacman: " << temp << " ";
}
/*----------------------------------------------------------------------------------------------*/
/* Prints the board
*/
void Game::printBoard2() {
for (int row = 0; row < board2->getBoardRows(); row++) {
for (int col = 0; col < board2->getBoardCols(); col++) {
if (withColor) {
if (board[row][col] == FOOD)
setTextColor(Color::LIGHTGREY);
else
setTextColor(Color::BLUE);
}
cout << board[row][col];
}
cout << endl;
}
}
/*----------------------------------------------------------------------------------------------*/
/* Moves the ghosts
*/
void Game::moveGhosts(vector<Ghost*>& ghosts, bool& moveTurn, GameObject pacmanPos) {
// Movement of the Ghosts is half of the movement of Pacman
moveTurn = !moveTurn;
if (moveTurn) {
for (int i = 0; i < ghosts.size(); i++) {
ghosts[i]->move(board, pacmanPos,ghosts);
if (saveMode)
steps << "Ghost" << i << ": " << ghosts[i]->getDirection() << " ";
}
}
Color arr[4] = { Color::RED , Color::MAGENTA, Color::CYAN, Color::BROWN };
for (int i = 0; i < ghosts.size(); i++) {
if (withColor)
setTextColor(arr[i]);
ghosts[i]->draw();
}
}
/*----------------------------------------------------------------------------------------------*/
/* moveFruit moves the fruit on the board if it is time for him to move
*/
void Game:: moveFruit(Fruit& fruit, int& moveTurn) {
fruit.Delete(board);
if (fruit.getAlive()) {
// Movement of the Fruit is half of the movement of Ghost
moveTurn = (moveTurn + 1) % 4;
if (moveTurn == 1) {
fruit.move(board);
if (saveMode)
steps << "Fruit: " << fruit.getDirection() << " ";
}
if (withColor)
setTextColor(Color::GREEN);
fruit.draw();
}
else // fruit is DEAD
fruit.Delete(board);
}
/*----------------------------------------------------------------------------------------------*/
/* Checks if player and ghosts have the same x,y position (if collision)
*/
bool Game::checkCollision(Player player, vector<Ghost*> ghosts) {
for (int i = 0; i < ghosts.size(); i++) {
if (player.getX() == ghosts[i]->getX() && player.getY() == ghosts[i]->getY())
{
return true;
}
}
return false;
}
/*----------------------------------------------------------------------------------------------*/
/* Returns player and ghosts to their original positions, and substracts 1 point from player's lives \
*/
void Game::respawn(Player& player, vector<Ghost*>& ghosts) {
player.setLives(player.getLives() - 1); //minus one life
player.Delete();
for (int i = 0; i < ghosts.size(); i++) {
ghosts[i]->Delete(board);
}
//player starting position
player.setX(board2->getPlayerStartPos().getX());
player.setY(board2->getPlayerStartPos().getY());
//ghosts starting position
for (int i = 0; i < ghosts.size(); i++) {
ghosts[i]->setX(board2->getGhostsStartPos()[i].getX());
ghosts[i]->setY(board2->getGhostsStartPos()[i].getY());
}
}
/*----------------------------------------------------------------------------------------------*/
/* findFruitSpawnPoint finds a position on the board where the fruit can "safley" spawn.
*/
void Game:: findFruitSpawnPoint(Fruit& fruit, Player player, vector<Ghost*> ghosts) {
int newX;
int newY;
bool OK = false;
do {
newX = rand() % board2->getBoardCols();
newY = rand() % board2->getBoardRows();
//if (board[newY][newX] == ' ' || board[newY][newX] == FOOD)
if(board2->getChar(newY,newX) == FOOD)
OK = true;
else
OK = false;
if (newX == player.getX() && newY == player.getY())
OK = false;
for (int i = 0; i < ghosts.size(); i++) {
if (newX == ghosts[i]->getX() && newY == ghosts[i]->getY())
OK = false;
}
} while (!OK);
fruit.setX(newX);
fruit.setY(newY);
}
/*----------------------------------------------------------------------------------------------*/
/* Checks if player and ghosts have the same x,y position (if collision)
*/
void Game:: checkFruitCollision(Player& player, vector<Ghost*> ghosts, Fruit& fruit) {
if (fruit.getAlive() && player.getX() == fruit.getX() && player.getY() == fruit.getY())
{
for (int i = 0; i < fruit.getValue(); i++) {
player.addAPoint();
}
fruit.setAlive(DEAD,board);
}
for (int i = 0; i < ghosts.size(); i++) {
if (fruit.getAlive() && fruit.getX() == ghosts[i]->getX() && fruit.getY() == ghosts[i]->getY())
{
fruit.setAlive(DEAD,board);
}
}
}
/*----------------------------------------------------------------------------------------------*/
/* Prints a message if the user WON/LOST/PAUSED the game
*/
bool Game::printMessage(State state) {
if (withColor)
setTextColor(Color::YELLOW);
else
setTextColor(Color::LIGHTGREY);
system("cls");
if (state == WON) {
cout << congrats;
}
else if (state == LOST) {
cout << youLost;
}
else { // state == PAUSE
cout << paused;
cout << "TO END GAME PRESS E\n";
char ch = ' ';
do {
if (_kbhit()) {
ch = _getch();
}
} while (ch != 27 && tolower(ch) != 'e');
system("cls");
if (tolower(ch) == 'e')
return true;
else {
return false; // Unpause Game
}
}
cout << "Press any key to go back to the Main Menu... " << endl;
_getch(); // Waits until the User presses the keyboard
system("cls");
return false;
}
/*----------------------------------------------------------------------------------------------*/
/* char Difficulty GETTER
*/
char Game::getDifficulty() const {
return this->difficultyLevel;
}
/*----------------------------------------------------------------------------------------------*/
/* Difficulty SETTER
*/
void Game::setDifficulty(char diff) {
this->difficultyLevel = diff;
}
/*----------------------------------------------------------------------------------------------*/
// Save
/*----------------------------------------------------------------------------------------------*/
string Game::fileNameSteps(string fileName) {
std::size_t slash = fileName.find_last_of("\\"); // find last slash in file path
std::size_t dot = fileName.find_last_of(".screen"); // find where ending .screen
int a = fileName.substr(slash + 1).length() - 7; // get substring len - ".screen"
return fileName.substr(slash + 1, a) + ".steps"; // file name
}
/*----------------------------------------------------------------------------------------------*/
string Game::fileNameResult(string fileName) {
std::size_t slash = fileName.find_last_of("\\"); // find last slash in file path
std::size_t dot = fileName.find_last_of(".screen"); // find where ending .screen
int a = fileName.substr(slash + 1).length() - 7; // get substring len - ".screen"
return fileName.substr(slash + 1, a) + ".result"; // file name
}
/*----------------------------------------------------------------------------------------------*/