-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspaceInvaders.cpp
More file actions
968 lines (839 loc) · 30.9 KB
/
spaceInvaders.cpp
File metadata and controls
968 lines (839 loc) · 30.9 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
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
#include <iostream>
#include <string>
#include <conio.h> // For _kbhit() and _getch()
#include <windows.h> // For Windows API functions (colors, cursor)
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <thread>
#include <fstream>
#include <iomanip> // For setw()
using namespace std;
// --- Game Constants ---
const int SCREEN_WIDTH = 100;
const int SCREEN_HEIGHT = 40;
const int MAX_ENEMIES = 9;
const int ENEMY_SPACING = 15;
const int NUM_BARRIERS = 3;
const int MAX_LEADERBOARD_ENTRIES = 100;
// --- Color Definitions ---
#define RESET "\033[0m"
#define TURQUOISE "\033[1;36m"
#define PURPLE "\033[35m"
#define YELLOW "\033[1;33m"
#define GREEN "\033[1;92m"
#define RED "\033[1;31m"
#define GRAY "\033[1;90m"
#define SILVER "\033[1;97m"
#define BRONZE "\033[0;33m"
// --- Struct Definitions ---
// Player data structure
struct Player {
int x, y;
const char* design[2];
int width;
int lives;
int score;
string username;
};
// Bullet data structure
struct Bullet {
int x, y;
bool isActive;
};
// Enemy data structure
struct Enemy {
int x, y;
bool active;
const char* design[3];
Bullet bullet;
unsigned long lastShotTime;
int shootCooldown;
};
// Spaceship (UFO) data structure
struct Spaceship {
int x, y;
bool active;
const char* design[3];
Bullet bullet;
unsigned long respawnTime;
};
// Barrier data structure
struct Barrier {
int x, y;
int width;
int height;
bool active;
bool blocks[6][4]; // Represents individual blocks of the barrier
};
// --- Function Prototypes ---
// Console & UI Utilities
void gotoxy(int x, int y);
void showConsoleCursor(bool showFlag);
void clearScreen();
void drawBoundary();
void printLogo();
// Menu & Game Flow
int mainMenu();
int pauseMenu();
void howToPlay();
void newGame();
void gameOverScreen(int score);
void winScreen(int score);
// Leaderboard
void showLeaderboard();
void loadLeaderboard(Player leaderboard[], int& count);
void savePlayerData(const Player& player);
void bubbleSort(Player leaderboard[], int count);
// Drawing Functions
void drawPlayer(const Player& player);
void erasePlayer(const Player& player);
void drawEnemies(const Enemy enemies[]);
void eraseEnemies(const Enemy enemies[]);
void drawSpaceship(const Spaceship& spaceship);
void eraseSpaceship(const Spaceship& spaceship);
void drawBarrier(const Barrier& barrier);
void drawLives(int lives);
void drawScore(int score);
// Game Logic & Movement
void movePlayer(Player& player, char direction);
void shootBullet(Player& player, Bullet& bullet);
void moveBullet(Bullet& bullet);
void moveEnemies(Enemy enemies[], int& direction);
void enemyShoot(Enemy enemies[]);
void moveEnemyBullets(Enemy enemies[]);
void spawnSpaceship(Spaceship& spaceship, unsigned long& lastSpawnTime);
void moveSpaceship(Spaceship& spaceship);
void checkAndRemoveSpaceship(Spaceship& spaceship);
void moveSpaceshipBullet(Spaceship& spaceship);
// Collision Detection
bool checkCollisionWithEnemies(Bullet& bullet, Enemy enemies[], int& score);
bool checkCollisionWithPlayer(Player& player, Enemy enemies[]);
bool checkCollisionWithSpaceship(Bullet& bullet, Spaceship& spaceship, int& score);
bool checkBulletCollisionWithBarrier(Bullet& bullet, Barrier& barrier);
bool checkPlayerHit(Player& player, Enemy enemies[], Spaceship& spaceship);
bool checkEnemyCollisionWithBarrier(Enemy enemies[], Barrier barriers[]);
bool allEnemiesDestroyed(const Enemy enemies[]);
// --- Main Function ---
int main() {
SetConsoleOutputCP(CP_UTF8); // Enable UTF-8 characters for box drawing
srand(static_cast<unsigned int>(time(0)));
showConsoleCursor(false);
while (true) {
int choice = mainMenu();
switch (choice) {
case 0:
newGame();
break;
case 1:
showLeaderboard();
break;
case 2:
howToPlay();
break;
case 3:
clearScreen();
cout << RED << "\n Thanks for playing!\n" << RESET;
Sleep(1500);
return 0;
}
}
return 0;
}
// --- Console & UI Utilities ---
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void showConsoleCursor(bool showFlag) {
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(out, &cursorInfo);
cursorInfo.bVisible = showFlag;
SetConsoleCursorInfo(out, &cursorInfo);
}
void clearScreen() {
system("cls");
}
void drawBoundary() {
gotoxy(0, 0);
cout << "╔";
for (int i = 1; i < SCREEN_WIDTH - 1; i++) cout << "═";
cout << "╗";
for (int i = 1; i < SCREEN_HEIGHT - 1; i++) {
gotoxy(0, i);
cout << "║";
gotoxy(SCREEN_WIDTH - 1, i);
cout << "║";
}
gotoxy(0, SCREEN_HEIGHT - 1);
cout << "╚";
for (int i = 1; i < SCREEN_WIDTH - 1; i++) cout << "═";
cout << "╝";
}
void printLogo() {
string spaceInvaderText[] = {
" _ _ ",
" ___ _ __ __ _ ___ ___ (_)_ ____ ____ _ __| | ___ _ __ ___ ",
" / __| '_ \\ / _` |/ __/ _ \\ | | '_ \\ \\ / / _` |/ _` |/ _ \\ '__/ __|",
" \\__ \\ |_) | (_| | (_| __/ | | | | \\ V / (_| | (_| | __/ | \\__ \\",
" |___/ .__/ \\__,_|\\___\\___| |_|_| |_|\\_/ \\__,_|\\__,_|\\___|_| |___/",
" |_| "};
gotoxy(2, 2);
for (int i = 0; i < 6; i++) {
gotoxy(2, 2 + i);
cout << PURPLE << spaceInvaderText[i] << RESET;
}
}
// --- Menu & Game Flow ---
int mainMenu() {
clearScreen();
printLogo();
string menuItems[] = {" New Game ", " Leaderboard ", " How to Play ", " Exit "};
int selectedOption = 0;
char key;
while (true) {
for (int i = 0; i < 4; i++) {
int y_pos = 10 + i * 3;
string textColor = (i == selectedOption) ? TURQUOISE : YELLOW;
gotoxy(28, y_pos);
cout << PURPLE << "┌────────────────────────┐" << RESET;
gotoxy(28, y_pos + 1);
cout << PURPLE << "│" << RESET << textColor << menuItems[i] << RESET << PURPLE << "│" << RESET;
gotoxy(28, y_pos + 2);
cout << PURPLE << "└────────────────────────┘" << RESET;
}
key = _getch();
if (key == 224) { // Arrow keys
key = _getch();
}
switch (toupper(key)) {
case 'W':
case 72: // Up arrow
selectedOption = (selectedOption > 0) ? selectedOption - 1 : 3;
break;
case 'S':
case 80: // Down arrow
selectedOption = (selectedOption < 3) ? selectedOption + 1 : 0;
break;
case 13: // Enter
return selectedOption;
}
}
}
int pauseMenu() {
string options[] = {" Resume ", " Restart ", " Main Menu "};
int selected = 0;
while (true) {
// Draw a semi-transparent pause box
gotoxy(30, 15); cout << GRAY << "╔══════════════════════════════════╗" << RESET;
for(int i=0; i<9; ++i) {
gotoxy(30, 16+i); cout << GRAY << "║ ║" << RESET;
}
gotoxy(30, 25); cout << GRAY << "╚══════════════════════════════════╝" << RESET;
gotoxy(42, 16); cout << YELLOW << "PAUSED" << RESET;
for (int i = 0; i < 3; i++) {
string prefix = (i == selected) ? " >> " : " ";
string suffix = (i == selected) ? " << " : " ";
string color = (i == selected) ? TURQUOISE : YELLOW;
gotoxy(34, 19 + i * 2);
cout << color << prefix << options[i] << suffix << RESET;
}
char key = _getch();
if (key == 224) key = _getch();
switch (toupper(key)) {
case 'W': case 72: // Up
selected = (selected > 0) ? selected - 1 : 2;
break;
case 'S': case 80: // Down
selected = (selected < 2) ? selected + 1 : 0;
break;
case 13: // Enter
return selected;
}
}
}
void howToPlay() {
clearScreen();
drawBoundary();
gotoxy(42, 4); cout << TURQUOISE << "HOW TO PLAY" << RESET;
// Objective
gotoxy(4, 8); cout << YELLOW << "OBJECTIVE:" << RESET;
gotoxy(6, 10); cout << "Destroy all incoming aliens before they reach your planet!";
// Controls
gotoxy(4, 14); cout << YELLOW << "CONTROLS:" << RESET;
gotoxy(6, 16); cout << TURQUOISE << "'A' / 'D'" << RESET << " or " << TURQUOISE << "Left/Right Arrows" << RESET << ": Move your ship.";
gotoxy(6, 18); cout << TURQUOISE << "'Spacebar'" << RESET << ": Fire your laser.";
gotoxy(6, 20); cout << TURQUOISE << "'ESC'" << RESET << ": Pause the game.";
// Scoring
gotoxy(4, 24); cout << YELLOW << "SCORING:" << RESET;
gotoxy(6, 26); cout << GREEN << "Top Row Alien:" << RESET << " 30 Points";
gotoxy(6, 28); cout << GREEN << "Middle Row Alien:" << RESET << " 20 Points";
gotoxy(6, 30); cout << GREEN << "Bottom Row Alien:" << RESET << " 10 Points";
gotoxy(6, 32); cout << RED << "Mystery Ship:" << RESET << " 50-200 Points";
gotoxy(30, 36);
cout << "Press any key to return to the main menu...";
_getch();
}
void newGame() {
clearScreen();
// --- Player Initialization ---
string playerName;
cout << YELLOW << "\n\n Enter your name: " << RESET;
showConsoleCursor(true);
cin >> playerName;
showConsoleCursor(false);
// --- Game Variable Initialization ---
const char* playerDesign[] = {" ▄ ", "███"};
Player player = {SCREEN_WIDTH / 2, SCREEN_HEIGHT - 4, {playerDesign[0], playerDesign[1]}, 3, 3, 0, playerName};
Bullet bullet = {0, 0, false};
const char* enemyDesign1[] = {" ▄█▄ ", "█████", "█ █ █"};
const char* enemyDesign2[] = {" ███ ", "█▄█▄█", " ▀ ▀ "};
const char* enemyDesign3[] = {"▀▄█▄▀", " ███ ", "█ █"};
Enemy enemies[MAX_ENEMIES] = {
{15, 10, true, {enemyDesign1[0], enemyDesign1[1], enemyDesign1[2]}, {0, 0, false}, 0, 2000},
{15 + ENEMY_SPACING, 10, true, {enemyDesign1[0], enemyDesign1[1], enemyDesign1[2]}, {0, 0, false}, 0, 2000},
{15 + 2 * ENEMY_SPACING, 10, true, {enemyDesign1[0], enemyDesign1[1], enemyDesign1[2]}, {0, 0, false}, 0, 2000},
{15, 14, true, {enemyDesign2[0], enemyDesign2[1], enemyDesign2[2]}, {0, 0, false}, 0, 2000},
{15 + ENEMY_SPACING, 14, true, {enemyDesign2[0], enemyDesign2[1], enemyDesign2[2]}, {0, 0, false}, 0, 2000},
{15 + 2 * ENEMY_SPACING, 14, true, {enemyDesign2[0], enemyDesign2[1], enemyDesign2[2]}, {0, 0, false}, 0, 2000},
{15, 18, true, {enemyDesign3[0], enemyDesign3[1], enemyDesign3[2]}, {0, 0, false}, 0, 2000},
{15 + ENEMY_SPACING, 18, true, {enemyDesign3[0], enemyDesign3[1], enemyDesign3[2]}, {0, 0, false}, 0, 2000},
{15 + 2 * ENEMY_SPACING, 18, true, {enemyDesign3[0], enemyDesign3[1], enemyDesign3[2]}, {0, 0, false}, 0, 2000}
};
Spaceship spaceship = {0, 0, false, {"<▀█▀>", "█████", ""}, {0, 0, false}, 0};
unsigned long lastSpawnTime = 0;
Barrier barriers[NUM_BARRIERS];
for(int i = 0; i < NUM_BARRIERS; ++i) {
barriers[i] = {20 + i * 25, SCREEN_HEIGHT - 10, 6, 4, true};
for(int w = 0; w < 6; ++w) {
for(int h = 0; h < 4; ++h) {
barriers[i].blocks[w][h] = true;
}
}
}
int enemyDirection = 1;
int enemyMoveTimer = 0;
int enemySpeed = 25; // Lower is faster
// --- Initial Draw ---
clearScreen();
drawBoundary();
drawScore(player.score);
drawLives(player.lives);
for (int i = 0; i < NUM_BARRIERS; i++) drawBarrier(barriers[i]);
drawPlayer(player);
drawEnemies(enemies);
// --- Main Game Loop ---
while (player.lives > 0) {
// --- 1. Handle Input ---
if (_kbhit()) {
char ch = _getch();
if (ch == 224) ch = _getch(); // Catch arrow keys
switch (toupper(ch)) {
case 'A': case 75: // Left
movePlayer(player, 'L');
break;
case 'D': case 77: // Right
movePlayer(player, 'R');
break;
case ' ':
if (!bullet.isActive) shootBullet(player, bullet);
break;
case 27: // ESC for Pause
int pauseChoice = pauseMenu();
if (pauseChoice == 1) { // Restart
newGame();
return;
}
if (pauseChoice == 2) { // Main Menu
return;
}
// Redraw screen after resuming
clearScreen();
drawBoundary();
drawScore(player.score);
drawLives(player.lives);
for (int i = 0; i < NUM_BARRIERS; i++) drawBarrier(barriers[i]);
drawPlayer(player);
// Enemies will be redrawn in the update phase
break;
}
}
// --- 2. Update Game State ---
moveBullet(bullet);
moveEnemyBullets(enemies);
moveSpaceship(spaceship);
moveSpaceshipBullet(spaceship);
// Slow down enemy movement
if (enemyMoveTimer++ > enemySpeed) {
eraseEnemies(enemies);
moveEnemies(enemies, enemyDirection);
drawEnemies(enemies);
enemyMoveTimer = 0;
}
enemyShoot(enemies);
spawnSpaceship(spaceship, lastSpawnTime);
checkAndRemoveSpaceship(spaceship);
// --- 3. Check Collisions ---
if (bullet.isActive) {
if (checkCollisionWithEnemies(bullet, enemies, player.score)) {
drawScore(player.score);
if (enemySpeed > 5) enemySpeed--; // Speed up enemies on kill
}
if (checkCollisionWithSpaceship(bullet, spaceship, player.score)) {
drawScore(player.score);
}
for (int i = 0; i < NUM_BARRIERS; i++) {
if (checkBulletCollisionWithBarrier(bullet, barriers[i])) break;
}
}
if (checkPlayerHit(player, enemies, spaceship)) {
drawLives(player.lives);
Sleep(1000); // Pause briefly when hit
}
if (checkEnemyCollisionWithBarrier(enemies, barriers)) {
// Barrier was hit, redrawing handled inside function
}
for (int i = 0; i < MAX_ENEMIES; ++i) {
if(enemies[i].bullet.isActive) {
for (int b = 0; b < NUM_BARRIERS; b++) {
if (checkBulletCollisionWithBarrier(enemies[i].bullet, barriers[b])) break;
}
}
}
if (spaceship.bullet.isActive) {
for (int b = 0; b < NUM_BARRIERS; b++) {
if (checkBulletCollisionWithBarrier(spaceship.bullet, barriers[b])) break;
}
}
// --- 4. Check Win/Loss Conditions ---
if (allEnemiesDestroyed(enemies)) {
winScreen(player.score);
player.score += 100; // Win bonus
savePlayerData(player);
return;
}
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active && enemies[i].y >= player.y - 1) {
player.lives = 0; // Game over if enemies reach player
}
}
// --- 5. Delay ---
Sleep(20);
}
// --- Game Over ---
gameOverScreen(player.score);
savePlayerData(player);
}
void winScreen(int score) {
clearScreen();
const char* gameOverArt[] = {
" _____ ",
"___ ____(_)______ ",
"__ | /| / /_ /__ __ \\",
"__ |/ |/ /_ / _ / / /",
"____/|__/ /_/ /_/ /_/ "
};
for (int i = 0; i < 5; ++i) {
gotoxy(38, 10 + i);
cout << GREEN << gameOverArt[i] << RESET;
}
gotoxy(40, 18);
cout << YELLOW << "Final Score: " << score << RESET;
gotoxy(32, 22);
cout << "Press any key to return to the main menu...";
_getch();
Sleep(500); // Prevent accidental double input
}
void gameOverScreen(int score) {
clearScreen();
const char* gameOverArt[] = {
" ________ ________ ",
" / _____/_____ _____ ____ \\_____ \\___ __ ___________ ",
"/ \\ ___\\__ \\ / \\_/ __ \\ / | \\ \\/ // __ \\_ __ \\",
"\\ \\_\\ \\/ __ \\| Y Y \\ ___/ / | \\ /\\ ___/| | \\/",
" \\______ (____ /__|_| /\\___ > \\_______ /\\_/ \\___ >__| ",
" \\/ \\/ \\/ \\/ \\/ \\/ "
};
for (int i = 0; i < 6; ++i) {
gotoxy(15, 10 + i);
cout << RED << gameOverArt[i] << RESET;
}
gotoxy(40, 18);
cout << YELLOW << "Final Score: " << score << RESET;
gotoxy(32, 22);
cout << "Press any key to return to the main menu...";
_getch();
Sleep(500); // Prevent accidental double input
}
// --- Leaderboard ---
void showLeaderboard() {
clearScreen();
Player leaderboard[MAX_LEADERBOARD_ENTRIES];
int playerCount = 0;
loadLeaderboard(leaderboard, playerCount);
bubbleSort(leaderboard, playerCount);
cout << TURQUOISE << "\n _ _ _ _ \n";
cout << "| | ___ __ _ __| | ___ _ __| |__ ___ __ _ _ __ __| |\n";
cout << "| |/ _ \\/ _` |/ _` |/ _ \\ '__| '_ \\ / _ \\ / _` | '__/ _` |\n" << RESET;
cout << PURPLE << "| | __/ (_| | (_| | __/ | | |_) | (_) | (_| | | | (_| |\n";
cout << "|_|\\___|\\__,_|\\__,_|\\___|_| |_.__/ \\___/ \\__,_|_| \\__,_|\n\n" << RESET;
cout << SILVER << " " << left << setw(8) << "Rank" << setw(30) << "Name" << setw(15) << "Score" << RESET << "\n";
cout << PURPLE << " " << string(53, '_') << RESET << "\n\n";
if (playerCount == 0) {
cout << GRAY << " No scores yet. Be the first to set a record!" << RESET << endl;
}
for (int i = 0; i < playerCount && i < 10; i++) { // Show top 10
string color;
if (i == 0) color = YELLOW;
else if (i == 1) color = SILVER;
else if (i == 2) color = BRONZE;
else color = RESET;
cout << color << " " << left << setw(8) << i + 1
<< setw(30) << leaderboard[i].username
<< setw(15) << leaderboard[i].score << RESET << "\n";
}
cout << "\n\n" << GRAY << " Press any key to return to the menu..." << RESET;
getch();
}
void loadLeaderboard(Player leaderboard[], int& count) {
ifstream file("leaderboard.txt");
count = 0;
if (file.is_open()) {
while (count < MAX_LEADERBOARD_ENTRIES && file >> leaderboard[count].username >> leaderboard[count].score) {
bool exists = false;
for (int i = 0; i < count; ++i) {
if (leaderboard[i].username == leaderboard[count].username) {
if (leaderboard[count].score > leaderboard[i].score) {
leaderboard[i].score = leaderboard[count].score; // Update to higher score
}
exists = true;
break;
}
}
if (!exists) {
count++;
}
}
file.close();
}
}
void savePlayerData(const Player& player) {
Player leaderboard[MAX_LEADERBOARD_ENTRIES];
int playerCount = 0;
loadLeaderboard(leaderboard, playerCount);
bool playerFound = false;
for (int i = 0; i < playerCount; ++i) {
if (leaderboard[i].username == player.username) {
playerFound = true;
if (player.score > leaderboard[i].score) {
leaderboard[i].score = player.score; // Update score if higher
}
break;
}
}
if (!playerFound && playerCount < MAX_LEADERBOARD_ENTRIES) {
leaderboard[playerCount].username = player.username;
leaderboard[playerCount].score = player.score;
playerCount++;
}
ofstream file("leaderboard.txt", ios::trunc); // Overwrite file with updated data
if (file.is_open()) {
for (int i = 0; i < playerCount; ++i) {
file << leaderboard[i].username << " " << leaderboard[i].score << endl;
}
file.close();
}
}
void bubbleSort(Player leaderboard[], int count) {
for (int i = 0; i < count - 1; ++i) {
for (int j = 0; j < count - i - 1; ++j) {
if (leaderboard[j].score < leaderboard[j + 1].score) {
Player temp = leaderboard[j];
leaderboard[j] = leaderboard[j + 1];
leaderboard[j + 1] = temp;
}
}
}
}
// --- Drawing Functions ---
void drawPlayer(const Player& player) {
gotoxy(player.x, player.y);
cout << player.design[0];
gotoxy(player.x, player.y + 1);
cout << player.design[1];
}
void erasePlayer(const Player& player) {
gotoxy(player.x, player.y);
cout << " ";
gotoxy(player.x, player.y + 1);
cout << " ";
}
void drawEnemies(const Enemy enemies[]) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
for (int j = 0; j < 3; ++j) {
gotoxy(enemies[i].x, enemies[i].y + j);
cout << enemies[i].design[j];
}
}
}
}
void eraseEnemies(const Enemy enemies[]) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
for (int j = 0; j < 3; ++j) {
gotoxy(enemies[i].x, enemies[i].y + j);
cout << " ";
}
}
}
}
void drawSpaceship(const Spaceship& spaceship) {
if (spaceship.active) {
for (int i = 0; i < 2; ++i) {
gotoxy(spaceship.x, spaceship.y + i);
cout << spaceship.design[i];
}
}
}
void eraseSpaceship(const Spaceship& spaceship) {
if (spaceship.x > 0) {
for (int i = 0; i < 2; ++i) {
gotoxy(spaceship.x, spaceship.y + i);
cout << " ";
}
}
}
void drawBarrier(const Barrier& barrier) {
if (barrier.active) {
for (int i = 0; i < barrier.height; i++) {
gotoxy(barrier.x, barrier.y + i);
for (int j = 0; j < barrier.width; j++) {
if (barrier.blocks[j][i]) {
cout << "█";
} else {
cout << " ";
}
}
}
} else { // If barrier is inactive, erase it
for (int i = 0; i < barrier.height; i++) {
gotoxy(barrier.x, barrier.y + i);
cout << " "; // 6 spaces for width
}
}
}
void drawLives(int lives) {
gotoxy(SCREEN_WIDTH - 15, 1);
cout << "Lives: " << lives << " ";
}
void drawScore(int score) {
gotoxy(2, 1);
cout << "Score: " << score << " ";
}
// --- Game Logic & Movement ---
void movePlayer(Player& player, char direction) {
erasePlayer(player);
if (direction == 'L' && player.x > 1) {
player.x--;
} else if (direction == 'R' && player.x + player.width < SCREEN_WIDTH - 2) {
player.x++;
}
drawPlayer(player);
}
void shootBullet(Player& player, Bullet& bullet) {
bullet.x = player.x + 1; // Center of player ship
bullet.y = player.y - 1;
bullet.isActive = true;
}
void moveBullet(Bullet& bullet) {
if (bullet.isActive) {
gotoxy(bullet.x, bullet.y);
cout << " ";
bullet.y--;
if (bullet.y < 1) {
bullet.isActive = false;
} else {
gotoxy(bullet.x, bullet.y);
cout << "|";
}
}
}
void moveEnemies(Enemy enemies[], int& direction) {
bool boundaryReached = false;
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
enemies[i].x += direction;
if (enemies[i].x >= SCREEN_WIDTH - 8 || enemies[i].x <= 1) {
boundaryReached = true;
}
}
}
if (boundaryReached) {
direction *= -1;
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
enemies[i].y++;
}
}
}
}
void enemyShoot(Enemy enemies[]) {
unsigned long currentTime = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active && !enemies[i].bullet.isActive) {
if (rand() % 200 < 2) { // Adjust shooting probability
if (currentTime - enemies[i].lastShotTime >= enemies[i].shootCooldown) {
enemies[i].bullet.x = enemies[i].x + 2;
enemies[i].bullet.y = enemies[i].y + 3;
enemies[i].bullet.isActive = true;
enemies[i].lastShotTime = currentTime;
}
}
}
}
}
void moveEnemyBullets(Enemy enemies[]) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].bullet.isActive) {
gotoxy(enemies[i].bullet.x, enemies[i].bullet.y);
cout << " ";
enemies[i].bullet.y++;
if (enemies[i].bullet.y >= SCREEN_HEIGHT - 1) {
enemies[i].bullet.isActive = false;
} else {
gotoxy(enemies[i].bullet.x, enemies[i].bullet.y);
cout << "*";
}
}
}
}
void spawnSpaceship(Spaceship& spaceship, unsigned long& lastSpawnTime) {
unsigned long currentTime = time(0);
if (!spaceship.active && (currentTime - lastSpawnTime >= 20)) {
spaceship.x = 2;
spaceship.y = 4;
spaceship.active = true;
drawSpaceship(spaceship);
lastSpawnTime = currentTime;
}
}
void moveSpaceship(Spaceship& spaceship) {
if (spaceship.active) {
eraseSpaceship(spaceship);
spaceship.x++;
drawSpaceship(spaceship);
}
}
void checkAndRemoveSpaceship(Spaceship& spaceship) {
if (spaceship.active && spaceship.x >= SCREEN_WIDTH - 8) {
eraseSpaceship(spaceship);
spaceship.active = false;
}
}
void moveSpaceshipBullet(Spaceship& spaceship) {
// This could be implemented for added difficulty
}
// --- Collision Detection ---
bool checkCollisionWithEnemies(Bullet& bullet, Enemy enemies[], int& score) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
if (bullet.x >= enemies[i].x && bullet.x < enemies[i].x + 5 &&
bullet.y >= enemies[i].y && bullet.y < enemies[i].y + 3) {
eraseEnemies(&enemies[i]); // Erase just the one hit
enemies[i].active = false;
gotoxy(bullet.x, bullet.y); cout << " "; // Erase bullet
bullet.isActive = false;
int row = (enemies[i].y - 10) / 4;
if (row == 0) score += 30;
else if (row == 1) score += 20;
else score += 10;
return true;
}
}
}
return false;
}
bool checkCollisionWithPlayer(Player& player, Enemy enemies[]) {
// This is handled by checking enemy y-position in the main loop now
return false;
}
bool checkCollisionWithSpaceship(Bullet& bullet, Spaceship& spaceship, int& score) {
if (spaceship.active && bullet.isActive) {
if (bullet.x >= spaceship.x && bullet.x < spaceship.x + 5 &&
bullet.y >= spaceship.y && bullet.y < spaceship.y + 2) {
eraseSpaceship(spaceship);
spaceship.active = false;
gotoxy(bullet.x, bullet.y); cout << " ";
bullet.isActive = false;
score += (rand() % 151) + 50; // Random score from 50 to 200
return true;
}
}
return false;
}
bool checkBulletCollisionWithBarrier(Bullet& bullet, Barrier& barrier) {
if (bullet.isActive && barrier.active) {
int relativeX = bullet.x - barrier.x;
int relativeY = bullet.y - barrier.y;
if (relativeX >= 0 && relativeX < barrier.width &&
relativeY >= 0 && relativeY < barrier.height) {
if (barrier.blocks[relativeX][relativeY]) {
barrier.blocks[relativeX][relativeY] = false;
gotoxy(bullet.x, bullet.y); cout << " "; // Erase the block hit
bullet.isActive = false;
// Check if all blocks are destroyed
bool allDestroyed = true;
for(int w=0; w<barrier.width; ++w) {
for(int h=0; h<barrier.height; ++h) {
if(barrier.blocks[w][h]) allDestroyed = false;
}
}
if (allDestroyed) barrier.active = false;
return true;
}
}
}
return false;
}
bool checkPlayerHit(Player& player, Enemy enemies[], Spaceship& spaceship) {
for (int i = 0; i < MAX_ENEMIES; i++) {
if (enemies[i].bullet.isActive) {
if (enemies[i].bullet.x >= player.x && enemies[i].bullet.x < player.x + player.width &&
enemies[i].bullet.y >= player.y && enemies[i].bullet.y <= player.y + 1) {
enemies[i].bullet.isActive = false;
player.lives--;
return true;
}
}
}
return false;
}
bool checkEnemyCollisionWithBarrier(Enemy enemies[], Barrier barriers[]) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) {
for (int j = 0; j < NUM_BARRIERS; ++j) {
if (barriers[j].active) {
// Simple check: if enemy's bottom edge touches barrier's top edge
if (enemies[i].y + 2 >= barriers[j].y &&
enemies[i].x + 5 > barriers[j].x &&
enemies[i].x < barriers[j].x + barriers[j].width) {
barriers[j].active = false;
drawBarrier(barriers[j]); // Redraw to erase it
return true;
}
}
}
}
}
return false;
}
bool allEnemiesDestroyed(const Enemy enemies[]) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].active) return false;
}
return true;
}