-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.cpp
611 lines (528 loc) · 16.4 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
#include <iostream>
#include <list>
#include <vector>
#include <conio.h>
#include <windows.h>
#include <ctime>
#include <fstream>
// Used Things
// 1. Inheritance (Arrow, Bomb, Coin inherited from Object class)
// 2. Runtime Polymorphism
// 3. Function & Operator Overloading
// 4. Virtual Function & Pure Virtual Function
// 5. Diamond Problem and virtually inheritance (between Object class and it’s childs)
// 6. Constructor & Destructor
// 7. Friend Function and Friend Class
// 8. Templates
// 9. Static Member Function & Static Member Variable
// 10. File Handling (Saving & Loading Highest Scores)
// 11. STL (vector, list)
using namespace std;
const int height = 15;
const int width = 80;
long long highest_score[] = {0, 0, 0};
const string DIFFICULTY[] = {"Easy", "Normal", "Hard"};
const string fileName = "highest_score.txt";
// Colors used for printing
const string RESET = "\033[0m";
const string RED = "\033[31m";
const string GREEN = "\033[32m";
const string YELLOW = "\033[33m";
const string MAGENTA = "\033[35m";
const string CYAN = "\033[36m";
const string WHITE = "\033[37m";
// All Bombs Symbol
const int BombCount = 3;
string BOMBS[BombCount] = {"💥", "💀", "🚁"};
// All Coins Symbol
const int CoinsCount = 3;
string COINS[CoinsCount] = {"🟡", "🍏", "💲"};
// All Arrow Symbol
const int ArrowCount = 2;
string ARROWS[ArrowCount] = {"◀", "⚡"};
// Transfer cursor to a specific coordinates
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// Transfer cursor to a (0, 0)
void gotoxy() {
COORD coord;
coord.X = 0;
coord.Y = 0;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
bool getYN(){
char c;
while(true){
c = getch();
if(c == 'y' || c == 'Y') return true;
if(c == 'n' || c == 'N') return false;
}
}
int getMainInput(){
char c;
while(true){
c = getch();
if(c == '1') return 1;
if(c == '2') return 2;
if(c == '3') return 3;
if(c == 'q') return 0; // quit
}
}
// A class to print and update the last points
template<class T>
class LastPoints
{
short counter;
public:
LastPoints() : counter(0){ }
void update(){
// show last point update for 4 sec
if(counter == 40){
clear();
counter = 0;
}else
counter++;
}
// print last points
void set(T data, string color){
clear();
gotoxy(12, 2);
cout << color << data << RESET;
counter = 0;
}
// clear last points
void clear(){
gotoxy(12, 2);
cout << " ";
}
};
class Game;
class Player {
private:
int x, y;
long long score;
bool dead;
public:
LastPoints<string> lastPoints;
static vector<string> plane;
Player() {}
Player(int startX, int startY) : x(startX), y(startY), score(0), dead(false) {}
void die(){
dead = true;
}
void draw() {
gotoxy(x, y);
cout << GREEN << plane[0] << RESET;
gotoxy(x+2, y+1);
cout << CYAN << plane[1] << RESET;
gotoxy(x+2, y-1);
cout << CYAN << plane[2] << RESET;
}
void erase() {
gotoxy(x, y);
cout << " ";
gotoxy(x+2, y+1);
cout << " ";
gotoxy(x+2, y-1);
cout << " ";
}
void moveUp() {
if (y > 5) {
erase();
y--;
}
}
void moveDown() {
if (y < height-1) {
erase();
y++;
}
}
void destroyAnimation(){
string anim[10][3] = {
{"--->", "/", "\\"},
{"--->", "/", "\\"},
{"- -=", "-", "-"},
{"- -=", "-", "-"},
{"- -=", "*", "*"},
{"- -=", "*", "*"},
{"- -=", "*", "*"},
{"- - ", " ", " "},
{" ", " ", " "},
};
for(int i = 0; i < 10; i++){
gotoxy(x, y);
cout << GREEN << anim[i][0] << RESET;
gotoxy(x+2, y+1);
cout << CYAN << anim[i][1] << RESET;
gotoxy(x+2, y-1);
cout << CYAN << anim[i][2] << RESET;
gotoxy(); // take cursor to the corner
Sleep(120);
}
}
// operator overloading via member function
void operator+(int scr){
if(!dead){
score += scr;
}
}
// operator overloading via member function
void operator-(int scr){
if(!dead){
score -= scr;
if(score < 0)
score = 0;
}
}
template<class T>
T isColided(int obj_x, int obj_y){
if(y == obj_y && x + 4 >= obj_x && x <= obj_x){
return 1; // direct hit
}else if((y+1 == obj_y && x + 3 >= obj_x && x+2 <= obj_x) || (y-1 == obj_y && x + 3 >= obj_x && x+2 <= obj_x)){
return 2; // on wings
}
return 0; // no hit
}
friend class Game;
};
vector<string> Player::plane = vector<string>({"===>", "/", "\\"});
class Object {
protected:
int x, y;
string symbol;
public:
Object() {x=0; y=0;}
Object(int x, int y, string symbol) : x(x), y(y), symbol(symbol){}
// draw
friend ostream& operator<<(ostream& out, Object *obj){
gotoxy(obj->x, obj->y);
out << obj->symbol;
return out;
}
void erase() {
gotoxy(x, y);
cout << " ";
}
// virtual function
virtual bool move(){
if (!x) return false;
x--;
return true;
}
// pure virtual function
// return true if the object is colided
virtual bool detectColide(Player *p) = 0;
};
class Arrow: virtual public Object{
public:
Arrow () {}
Arrow(int startX, int startY) : Object(startX, startY, ARROWS[rand() % ArrowCount]) {}
bool detectColide(Player *p){
short c = p->isColided<short>(x, y);
if(c == 1){ // direct hit : DIE
p->die();
return true;
}else if(c == 2){ // wings hit : - (200 - 300)
int r = (200 + rand() % 301);
*p - r;
p->lastPoints.set("-" + to_string(r), RED);
return true;
}
return false;
}
};
class Bomb: virtual public Object{
public:
Bomb () {}
Bomb(int startX, int startY) : Object(startX, startY, BOMBS[rand() % BombCount]) {}
// copy constructor
Bomb(Bomb &b){
x = b.x;
y = b.y-1; // create new bomb at top
symbol = b.symbol; // with same symbol
}
bool detectColide(Player *p){
if(p->isColided<bool>(x, y)){ // direct / wings hit : DIE
p->die();
return true;
}
return false;
}
};
class Coin: virtual public Object{
public:
Coin () {}
Coin(int startX, int startY) : Object(startX, startY, COINS[rand() % CoinsCount]) {}
bool detectColide(Player *p){
short c = p->isColided<short>(x, y);
if(c == 1){ // direct hit : +1000
*p + 1000;
p->lastPoints.set("+1000", GREEN);
return true;
}else if(c == 2){ // Wings hit : + 500-1000
int r = (500 + rand() % 501);
*p + r;
p->lastPoints.set("+" + to_string(r), GREEN);
return true;
}
return false;
}
};
// Mystery Item That can be Arrow, Bomb, Coin or Nothing
class Mystery : public Coin, public Bomb, public Arrow{
public:
Mystery() { }
// default aurguments
Mystery (int startX, int startY, string symbol = "🎃") : Object(startX, startY, symbol) {}
bool move() {
// it disapper early
if (x-3 == 0) return false;
x--;
return true;
}
bool detectColide(Player *p){
switch(rand() % 4){ // acts randomly
case 0:
return Bomb::detectColide(p);
case 1:
return Arrow::detectColide(p);
case 2:
return Coin::detectColide(p);
default:
return false;
}
}
};
class Game {
Player *player;
list<Object*> objects;
int diffLevel; // Difficulty
bool borderState = true; // for border animation
string borderColor;
public:
Game(int diffLevel) {
this->diffLevel = diffLevel;
player = new Player(2, (height+4)/2); // place at vertically center
switch(diffLevel){
case 0:
borderColor = WHITE;
break;
case 1:
borderColor = GREEN;
break;
default:
borderColor = CYAN;
}
system("cls");
gotoxy(25, 1);
cout << "Highest SCORE : " << highest_score[diffLevel];
gotoxy(55, 1);
cout << "Difficulty : " << DIFFICULTY[diffLevel];
gotoxy(5, 1);
cout << "SCORE : ";
}
~Game(){
for (auto it = objects.begin(); it != objects.end(); it++)
delete *it;
delete player;
}
void saveHighScore(){
ofstream fout(fileName);
fout << highest_score[0] << " " << highest_score[1] << " " << highest_score[2];
fout.close();
}
void printScore(){
gotoxy(13, 1);
cout << " ";
gotoxy(13, 1);
cout << player->score;
}
void animateBorder(){
// border animation
cout << borderColor;
if (borderState){
gotoxy(0, 3);
for(int i = 0; i<width/2; i++)
cout << "▂▃";
gotoxy(0, height+1);
for(int i = 0; i<width/2; i++)
cout << "▂▃";
borderState = false;
}else{
gotoxy(0, 3);
for(int i = 0; i<width/2; i++)
cout << "▃▂";
gotoxy(0, height+1);
for(int i = 0; i<width/2; i++)
cout << "▃▂";
borderState = true;
}
cout << RESET;
}
// update frame, return false for gameover
bool operator++() {
for (auto it = objects.begin(); it != objects.end();) {
if((*it)->detectColide(player)){
(*it)->erase();
delete *it;
it = objects.erase(it);
} else {
++it;
}
if (player->dead)
return false; // no next frame
}
// erase & move forward
for (auto it = objects.begin(); it != objects.end();) {
(*it)->erase();
if (!(*it)->move()) {
delete *it;
it = objects.erase(it);
} else {
++it;
}
}
// percentages of arrow, bomb, coin in each difficulty mode
int percentage[3][3] = {
{4, 4, 7},
{5, 9, 4},
{4, 15, 2},
};
// maximum objects on screen in each difficulty mode
int maxObjectInBoard[3] = {20, 30, 40};
// add new objects like arrow, bomb, coin
int h = rand() % (height-4)+4; // random height
if(objects.size() < maxObjectInBoard[diffLevel]){
int r = rand() % (100);
// add arrow
if(r < percentage[diffLevel][0])
objects.push_back(new Arrow(width-1, h));
// add bomb
else if(r < percentage[diffLevel][0] + percentage[diffLevel][1]){
Bomb *b = new Bomb(width-1, h);
objects.push_back(b);
if(diffLevel == 2 && h > 5 && rand() % 5 == 0){ // 20 % chance
// use copy constructor for new bomb of same symbol
objects.push_back(new Bomb(*b));
}
}
// add coins
else if(r < percentage[diffLevel][0] + percentage[diffLevel][1] + percentage[diffLevel][2])
objects.push_back(new Coin(width-1, h));
// Mystery item 1% chance at hard mode
else if(diffLevel == 2 && r < percentage[diffLevel][0] + percentage[diffLevel][1] + percentage[diffLevel][2] + 1){
objects.push_back(new Mystery(width-1, h));
}
}
// draw all objects
for (auto it: objects){
cout << it;
}
// draw player
player->erase();
player->draw();
*player + 1; // add one point
printScore(); // Update score board
animateBorder(); // update border
player->lastPoints.update(); // update last point counter
return true; // next frame avaiable
}
void gameOver() {
player->destroyAnimation();
Sleep(1000);
system("cls");
fflush(stdin);
// Game Over Screen
cout << "\n\n\t\tGame Over! Score : " << GREEN << player->score << RESET << " [" << DIFFICULTY[diffLevel] << " Mode]" << endl;
if(highest_score[diffLevel] < player->score){
cout << "\t\tNew Highest Score! You were ahead by " << player->score - highest_score[diffLevel] << " points!" << endl;
highest_score[diffLevel] = player->score;
saveHighScore(); // save new high score in file
}else{
int z = player->score * 100 / highest_score[diffLevel];
cout << "\t\tHighest Score : " << highest_score[diffLevel] << endl;
cout << "\t\tYou were " << z << " % close to the highest score!" << endl;
}
}
// static Function (Loading Highest Scores from File)
static void loadHighestScore(){
ifstream fin(fileName);
if(!fin){
fin.close();
ofstream fout(fileName);
fout << "0 0 0";
fout.close();
}else{
fin >> highest_score[0] >> highest_score[1] >> highest_score[2];
fin.close();
}
}
// friend function
friend void startAGame(int);
};
// friend function of Game Class
void startAGame(int diffLevel){
Game game(diffLevel);
while (true) {
if (_kbhit()) {
char key = _getch();
if (key == 'w') {
game.player->moveUp();
} else if (key == 's') {
game.player->moveDown();
}
}
// try to update Frame
if(++game == false){
game.gameOver();
break;
}
gotoxy(); // take cursor to the corner
Sleep(100);
}
}
void printFirstScreen(){
system("cls");
cout << "\n\t\t\t\t"<<"🛩️"<< GREEN << " FLY ME " << RESET <<"🛩️"<<"\n";
cout << "\t\t\t"<<"🛩️"<<" A Project by Roll: " << GREEN << "2107050 " << RESET <<"🛩️"<<"\n\n";
cout << CYAN << "\t\t\t\t "<<Player::plane[2]<<"\n" << RESET;
cout << GREEN <<"\t\t\t\t "<< Player::plane[0] <<"\n" << RESET;
cout << CYAN << "\t\t\t\t "<< Player::plane[1] <<"" << RESET;
cout << "\n\tRules: ";
cout << "\n\t\t1. "<<"💥"<<" "<<"💀"<<" "<<"🚁"<<" => Touch them: You " << RED << "DIE" << RESET <<"☠️";
cout << "\n\t\t2. "<<"◀"<<" "<<"⚡"<<" => On wings : Decrease score by (" << RED << "200-300" << RESET <<")";
cout << "\n\t\t3. "<<"◀"<<" "<<"⚡"<<" => Direct hit: You " << RED << "DIE" << RESET <<"☠️";
cout << "\n\t\t4. "<<"🟡"<<" "<<"🍏"<<" "<<"💲"<<" => On wings : Increase score by (" << GREEN << "500-1000" << RESET <<")";
cout << "\n\t\t5. "<<"🟡"<<" "<<"🍏"<<" "<<"💲"<<" => Direct hit: Increase score by " << GREEN << "1000" << RESET;
cout << "\n\t\t6. "<<"🎃"<<" "<<" => "<< YELLOW << "Mystery" << RESET << " Item: Can be " << MAGENTA << "AYTHING" << RESET << " [Hard Mode only]";
cout << "\n\n\tEnter (1 / 2 / 3) to start the Game in (Easy / Normal / Hard) Mode\n";
cout << "\n\t\t Enter 'q' to Quit the Game\n";
cout << "\n\t\t\t Highest Scores :";
cout << "\n\t\t\t Easy : " << highest_score[0];
cout << "\n\t\t\t Normal : " << highest_score[1];
cout << "\n\t\t\t Hard : " << highest_score[2];
cout << endl;
}
int main() {
srand(time(0));
// for printing emojis
SetConsoleOutputCP(CP_UTF8);
Game::loadHighestScore();
printFirstScreen();
int diffLevel;
while(diffLevel = getMainInput()){
do{
startAGame(diffLevel-1);
cout << "\n\n\t\tPlay Again (y/n)?" << endl;
fflush(stdin);
}while(getYN());
printFirstScreen();
}
cout << endl;
return 0;
}