-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGameManager.cpp
2700 lines (2394 loc) · 63 KB
/
GameManager.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
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Include/Global.h"
#include "Include/Graphics.h"
#include "Include/Player.h"
#include "Include/Zombie.h"
#include "Include/Weapon.h"
#include "Include/Timer.h"
#include "Include/Audio.h"
#include "Include/PopUpText.h"
#include "Include/Button.h"
#pragma region Create_Variables
#pragma region Rendering
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
#pragma endregion
#pragma region Menus
std::stack<StateStruct> g_StateStack;
std::stack<StateStruct> emptyStack; //for clearing stack
//menu screen
void Menu();
void handleMenuEvent(int& choice);
//game screen
void Game();
void handleGameEvent();
void handleGameInput();
//pause screen
void Pause();
bool paused = false; //flag
void handlePauseEvent();
//confirm screen
void Confirm();
enum class confirmState { FALSE, RETRY, QUIT, QUIT_TO_MENU };
confirmState confirmMode;
void showConfirmScreen(confirmState m);
void hideConfirmScreen();
bool confirmScreen = false; //flag
void handleConfirmEvent(int& choice);
//end game screen
void EndGame();
enum class endState { FALSE, WIN, LOSE, TIME_OVER };
endState endGameMode = endState::FALSE;
void showEndGamecreen(endState m);
void hideEndGameScreen();
bool endGameScreen = false; //flag
void handleEndGameEvent(int& choice);
//exit
void Exit();
void clearScreen();
#pragma endregion
#pragma region Game_Objects
player myPlayer;
zombie myZombie;
gameObject myTree;
gameObject myHarmZone;
gameObject mySignalZone;
gameObject myHealthPickup;
#pragma endregion
#pragma region Textures
//static textures
LTexture gGroundTexture;
LTexture gTreeTexture;
LTexture gBulletTexture;
LTexture gWhiteTexture;
LTexture gBloodPoolTexture;
//corsshair
LTexture gCrosshairTexture;
//screen effect textures
LTexture gVignetteTexture;
LTexture gLightTexture;
LTexture gLensDirtTexture;
LTexture gBloodOverlayTexture;
//UI textures
LTexture gHealthIconTexture;
LTexture gPistolIconTexture;
LTexture gRifleIconTexture;
//health pickup texture
LTexture gHealthPickUpTexture;
//background texture for menu
LTexture gMenuTexture;
//backdrop texture used for pause screen
SDL_Texture* backdrop;
#pragma endregion
#pragma region Colors
SDL_Color whiteColor = { 255, 255, 255 };
SDL_Color blackColor = { 0, 0, 0 };
SDL_Color UIColor = whiteColor;
#pragma endregion
#pragma region Animations
double animationTimeCounter = 0;
//player
//animations: pistol
std::map<playerState, LTexture> gPlayerPistolTexture;
std::map<playerState, std::vector <SDL_Rect>> gPlayerPistolClips;
//animations: rifle
std::map<playerState, LTexture> gPlayerRifleTexture;
std::map<playerState, std::vector <SDL_Rect>> gPlayerRifleClips;
//zombie
std::map<zombieState, LTexture> gZombieTexture;
std::map<zombieState, std::vector <SDL_Rect>> gZombieClips;
#pragma endregion
#pragma region Trees
std::vector <SDL_Rect> gTreeClips;
#pragma endregion
#pragma region Audio
audioManager myAudio;
#pragma endregion
#pragma region Fonts
const int fontSize = SCREEN_HEIGHT / 30;
const int fontSizeSmall = SCREEN_HEIGHT / 40;
const int fontSizeLarge = SCREEN_HEIGHT / 20;
const int fontSizeTitle = SCREEN_HEIGHT / 7.5;
TTF_Font* boldFont;
TTF_Font* regularFont;
TTF_Font* boldFontSmall;
TTF_Font* boldFontLarge;
TTF_Font* boldFontTitle;
TTF_Font* regularFontSmall;
#pragma endregion
#pragma region Objectives
int totalZombieKilled = 0;
bool tutorial = true;
int currentObjective = -1;
bool objective[TOTAL_OBJECTIVE];
std::string objectiveText;
int timeLeft = TIME_LIMIT;
//objective goals
int obj_zombieKilled = 0;
bool obj_keyPressed[4] = { false, false, false, false }; //whether w, a, s, d have been pressed
int obj_zones;
#pragma endregion
#pragma region Dialogues
std::vector <std::string> dialogueLine; //dialogue texts
std::vector <std::string> tipsLine; //tips texts
popUpText dialogue(3.0f, 1.0f);
popUpText dialogueTips(3.0f, 2.0f);
#pragma endregion
#pragma region Framerate
LTimer systemTimer; //The frames per second timer
LTimer deltaTimer; //The frames per second cap timer
int countedFrames = 0; //total frames
#pragma endregion
#pragma region Input
int mouseX;
int mouseY;
const Uint8* keys;
Uint32 mouses;
#pragma endregion
#pragma region Flags
bool allowSpawnZombie = false; //flag for zombie spawning
bool initedLevel = false;
bool quit = false;
bool cheat = false;
#pragma endregion
#pragma region Event_Handler
SDL_Event event;
#pragma endregion
#pragma region Camera
SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
#pragma endregion
#pragma region Vectors
std::vector<gameObject> trees;
std::vector<gameObject> harmZones;
std::vector<zombie> zombies;
std::vector<gameObject> bloodpools;
std::vector<bullet> bullets;
std::vector<gameObject> signalZones;
std::vector<gameObject> healthPickUps;
#pragma endregion
#pragma region Button
button myButton;
std::vector<button> buttons;
#pragma endregion
#pragma endregion
#pragma region Init_And_Load_Media
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Initialize SDL_ttf
if (TTF_Init() == -1)
{
printf("Unable to init TTF: %s\n", SDL_GetError());
success = false;
}
//Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
{
printf("Warning: Linear texture filtering not enabled!");
}
//Create window
gWindow = SDL_CreateWindow("SM2603 Project", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); //SDL_WINDOW_RESIZABLE
if (gWindow == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Create vsynced renderer for window
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (gRenderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
success = false;
}
//Initialize SDL_mixer
//new code for the sound here==================
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2048) < 0)
{
printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
success = false;
}
Mix_AllocateChannels(48); //allocate audio channels
}
}
}
//set base scaling
SDL_RenderSetLogicalSize(gRenderer, SCREEN_WIDTH, SCREEN_HEIGHT);
StateStruct state;
//add menu
state.StatePointer = Menu;
g_StateStack.push(state);
return success;
}
void loadSpritesheet(enum playerState state, std::map<playerState, LTexture>& spritesheet,
std::map<playerState, std::vector <SDL_Rect>>& spritesheetClip, int totalFrame)
{
int w = spritesheet[state].getWidth() / totalFrame;
int h = spritesheet[state].getHeight();
for (int i = 0; i < totalFrame; i++)
{
spritesheetClip[state].push_back({ i * w, 0, w , h });
}
}
void loadSpritesheet(enum zombieState state, std::map<zombieState, LTexture>& spritesheet,
std::map<zombieState, std::vector <SDL_Rect>>& spritesheetClip, int totalFrame)
{
int w = spritesheet[state].getWidth() / totalFrame;
int h = spritesheet[state].getHeight();
for (int i = 0; i < totalFrame; i++)
{
spritesheetClip[state].push_back({ i * w, 0, w , h });
}
}
void loadSpritesheet(LTexture& spritesheet, std::vector <SDL_Rect>& spritesheetClip, int totalFrame)
{
int w = spritesheet.getWidth() / totalFrame;
int h = spritesheet.getHeight();
for (int i = 0; i < totalFrame; i++)
{
spritesheetClip.push_back({ i * w, 0, w , h });
}
}
void loadClips(LTexture& spritesheet, std::vector<SDL_Rect>& spritesheetClip, int totalClip)
{
int w = spritesheet.getWidth() / totalClip;
int h = spritesheet.getHeight();
for (int i = 0; i < totalClip; i++)
{
spritesheetClip.push_back({ i * w, 0, w , h });
}
}
bool loadMedia()
{
//Loading success flag
bool success = true;
#pragma region Load_static_textures
//Load static texture
if (!gGroundTexture.loadFromFile("Assets/Texture/ground.png"))
{
printf("Failed to load player texture!\n");
success = false;
}
if (!gTreeTexture.loadFromFile("Assets/Texture/trees.png"))
{
printf("Failed to load tree texture!\n");
success = false;
}
else
{
loadClips(gTreeTexture, gTreeClips, TREES_CLIP);
}
if (!gCrosshairTexture.loadFromFile("Assets/Texture/crosshair.png"))
{
printf("Failed to load player texture!\n");
success = false;
}
if (!gBulletTexture.loadFromFile("Assets/Texture/bullet.png"))
{
printf("Failed to load bullet texture!\n");
success = false;
}
if (!gWhiteTexture.loadFromFile("Assets/Texture/white.png"))
{
printf("Failed to load white texture!\n");
success = false;
}
if (!gBloodPoolTexture.loadFromFile("Assets/Texture/blood pool.png"))
{
printf("Failed to load white texture!\n");
success = false;
}
if (!gHealthPickUpTexture.loadFromFile("Assets/Texture/health pickup.png"))
{
printf("Failed to load health pickup texture!\n");
success = false;
}
if (!gMenuTexture.loadFromFile("Assets/Texture/menu background.jpg"))
{
printf("Failed to load menu background texture!\n");
success = false;
}
#pragma endregion
#pragma region Load_animations_textures
//Load animation textures
//player
//pistol
//idle
if (!gPlayerPistolTexture[playerState::IDLE].loadFromFile("Assets/Texture/spritesheets/player/pistol/pistol idle.png"))
{
printf("Failed to load player pistol idle texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::IDLE, gPlayerPistolTexture, gPlayerPistolClips, PLAYER_PISTOL_IDLE_ANIMATION_FRAMES);
}
//walk
if (!gPlayerPistolTexture[playerState::WALK].loadFromFile("Assets/Texture/spritesheets/player/pistol/pistol walk.png"))
{
printf("Failed to load player pistol walk texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::WALK, gPlayerPistolTexture, gPlayerPistolClips, PLAYER_PISTOL_WALK_ANIMATION_FRAMES);
}
//fire
if (!gPlayerPistolTexture[playerState::FIRE].loadFromFile("Assets/Texture/spritesheets/player/pistol/pistol fire.png"))
{
printf("Failed to load player pistol fire texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::FIRE, gPlayerPistolTexture, gPlayerPistolClips, PLAYER_PISTOL_FIRE_ANIMATION_FRAMES);
}
//reload
if (!gPlayerPistolTexture[playerState::RELOAD].loadFromFile("Assets/Texture/spritesheets/player/pistol/pistol reload.png"))
{
printf("Failed to load player pistol reload texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::RELOAD, gPlayerPistolTexture, gPlayerPistolClips, PLAYER_PISTOL_RELOAD_ANIMATION_FRAMES);
}
//rifle
//idle
if (!gPlayerRifleTexture[playerState::IDLE].loadFromFile("Assets/Texture/spritesheets/player/rifle/rifle idle.png"))
{
printf("Failed to load player rifle idle texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::IDLE, gPlayerRifleTexture, gPlayerRifleClips, PLAYER_RIFLE_IDLE_ANIMATION_FRAMES);
}
//walk
if (!gPlayerRifleTexture[playerState::WALK].loadFromFile("Assets/Texture/spritesheets/player/rifle/rifle walk.png"))
{
printf("Failed to load player rifle walk texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::WALK, gPlayerRifleTexture, gPlayerRifleClips, PLAYER_RIFLE_WALK_ANIMATION_FRAMES);
}
//fire
if (!gPlayerRifleTexture[playerState::FIRE].loadFromFile("Assets/Texture/spritesheets/player/rifle/rifle fire.png"))
{
printf("Failed to load player rifle fire texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::FIRE, gPlayerRifleTexture, gPlayerRifleClips, PLAYER_RIFLE_FIRE_ANIMATION_FRAMES);
}
//reload
if (!gPlayerRifleTexture[playerState::RELOAD].loadFromFile("Assets/Texture/spritesheets/player/rifle/rifle reload.png"))
{
printf("Failed to load player rifle reload texture!\n");
success = false;
}
else
{
loadSpritesheet(playerState::RELOAD, gPlayerRifleTexture, gPlayerRifleClips, PLAYER_RIFLE_RELOAD_ANIMATION_FRAMES);
}
//zombie
//walk
if (!gZombieTexture[zombieState::WALK].loadFromFile("Assets/Texture/spritesheets/zombie/zombie walk.png"))
{
printf("Failed to load zombie walk texture!\n");
success = false;
}
else
{
loadSpritesheet(zombieState::WALK, gZombieTexture, gZombieClips, ZOMBIE_WALK_ANIMATION_FRAMES);
}
//attack
if (!gZombieTexture[zombieState::ATTACK].loadFromFile("Assets/Texture/spritesheets/zombie/zombie attack.png")) //TODO: change to zombie attack
{
printf("Failed to load zombie attack texture!\n");
success = false;
}
else
{
loadSpritesheet(zombieState::ATTACK, gZombieTexture, gZombieClips, ZOMBIE_ATTACK_ANIMATION_FRAMES);
}
#pragma endregion
#pragma region Load_screen_effect_textures
//Load screen effect texture
if (!gVignetteTexture.loadFromFile("Assets/Texture/vignette.png"))
{
printf("Failed to load vignette texture!\n");
success = false;
}
if (!gLightTexture.loadFromFile("Assets/Texture/light halo.png"))
{
printf("Failed to load light halo texture!\n");
success = false;
}
if (!gLensDirtTexture.loadFromFile("Assets/Texture/lens dirt.png"))
{
printf("Failed to load len dirt texture!\n");
success = false;
}
if (!gBloodOverlayTexture.loadFromFile("Assets/Texture/blood overlay.png"))
{
printf("Failed to load blood overlay texture!\n");
success = false;
}
#pragma endregion
#pragma region Load_UI_textures
//Load UI texture
if (!gHealthIconTexture.loadFromFile("Assets/Texture/health icon.png"))
{
printf("Failed to load health icon texture!\n");
success = false;
}
if (!gPistolIconTexture.loadFromFile("Assets/Texture/pistol icon.png"))
{
printf("Failed to load pistol icon texture!\n");
success = false;
}
if (!gRifleIconTexture.loadFromFile("Assets/Texture/rifle icon.png"))
{
printf("Failed to load rifle icon texture!\n");
success = false;
}
#pragma endregion
#pragma region Load_audio
//Load audio
myAudio.loadAudio();
#pragma endregion
#pragma region Load_text_font
//Load text font
boldFont = TTF_OpenFont("Assets/Font/OpenSans-Bold.ttf", fontSize);
if (boldFont == NULL) {
printf("Failed to load bold font! TTF Error: %s\n", TTF_GetError());
success = false;
}
boldFontSmall = TTF_OpenFont("Assets/Font/OpenSans-Bold.ttf", fontSizeSmall);
if (boldFontSmall == NULL) {
printf("Failed to load bold font small! TTF Error: %s\n", TTF_GetError());
success = false;
}
boldFontLarge = TTF_OpenFont("Assets/Font/OpenSans-Bold.ttf", fontSizeLarge);
if (boldFontLarge == NULL) {
printf("Failed to load bold font large! TTF Error: %s\n", TTF_GetError());
success = false;
}
boldFontTitle = TTF_OpenFont("Assets/Font/OpenSans-Bold.ttf", fontSizeTitle);
if (boldFontTitle == NULL) {
printf("Failed to load bold font title! TTF Error: %s\n", TTF_GetError());
success = false;
}
regularFont = TTF_OpenFont("Assets/Font/OpenSans-Regular.ttf", fontSize);
if (regularFont == NULL) {
printf("Failed to load regular font! TTF Error: %s\n", TTF_GetError());
success = false;
}
regularFontSmall = TTF_OpenFont("Assets/Font/OpenSans-Regular.ttf", fontSizeSmall);
if (regularFontSmall == NULL) {
printf("Failed to load regular font small! TTF Error: %s\n", TTF_GetError());
success = false;
}
#pragma endregion
#pragma region Load_text_line
//Load dialogues line
std::string str;
std::ifstream dialoguesFile("Assets/dialogues.txt");
if (dialoguesFile.fail()) {
printf("Failed to load dialogue file!\n");
success = false;
}
else {
while (std::getline(dialoguesFile, str))
{
dialogueLine.push_back(str);
}
}
std::ifstream tipsFile("Assets/tips.txt");
if (tipsFile.fail()) {
printf("Failed to load dialogue file!\n");
success = false;
}
else {
while (std::getline(tipsFile, str))
{
tipsLine.push_back(str);
}
}
#pragma endregion
return success;
}
void createGameObjectRandom(gameObject source, std::vector<gameObject>& vectorList, int total, int minSize, int maxSize, int rotation = 360, int maxType = -1)
{
for (int i = 0; i < total; i++)
{
bool ok = false;
int randomSize = 0;
int randomX = 0;
int randomY = 0;
while (!ok)
{
randomSize = GetRandomInt(minSize, maxSize, 1);
randomX = GetRandomInt(randomSize, LEVEL_WIDTH - randomSize, 1);
randomY = GetRandomInt(randomSize, LEVEL_HEIGHT - randomSize, 1);
if (calDistance(randomX, randomY, myPlayer.px, myPlayer.py) > randomSize + myPlayer.size)
{
ok = true;
}
}
int randomRotation = 0;
if (maxType != -1)
{
randomRotation = GetRandomInt(0, rotation, 1);
}
source.init(randomX, randomY, randomSize, randomRotation);
if (maxType != -1)
{
source.type = GetRandomInt(0, maxType - 2, 1);
}
vectorList.push_back(source);
}
}
#pragma endregion
#pragma region Common_Function
void frameCap()
{
//Calculate and correct fps
float avgFPS = countedFrames / (systemTimer.getTicks() / 1000.f);
if (avgFPS > 2000000)
{
avgFPS = 0;
}
++countedFrames;
//If frame finished early
int frameTicks = deltaTimer.getTicks();
if (frameTicks < SCREEN_TICK_PER_FRAME)
{
//Wait remaining time
SDL_Delay(SCREEN_TICK_PER_FRAME - frameTicks);
}
std::string title = "SM2603 Project [avg fps: " + std::to_string(int(avgFPS)) + "] " +
" [X:" + std::to_string(int(myPlayer.px)) + ", Y:" + std::to_string(int(myPlayer.py)) + "]";
SDL_SetWindowTitle(gWindow, title.c_str());
}
void clearScreen()
{
//Clear screen
SDL_SetRenderDrawColor(gRenderer, 100, 100, 100, 0);
SDL_RenderClear(gRenderer);
}
#pragma endregion
#pragma region Menu_Screen
void handleMenuEvent(int& choice)
{
//Poll events
while (SDL_PollEvent(&event))
{
//check events
switch (event.type)
{
case SDL_QUIT: //User hit the X
choice = 2;
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED)
{
//resize window
SDL_SetWindowSize(gWindow, event.window.data1, event.window.data2);
//SCREEN_WIDTH = event.window.data1;
//SCREEN_HEIGHT = event.window.data2;
}
break;
case SDL_KEYDOWN:
break;
case SDL_MOUSEBUTTONUP:
//start button
if (buttons[0].checkInside(mouseX, mouseY))
{
choice = 0;
}
//toggle music button
if (buttons[1].checkInside(mouseX, mouseY))
{
choice = 1;
}
//quit
if (buttons[2].checkInside(mouseX, mouseY))
{
choice = 2;
}
break;
}
}
//play or pause music
if (setting_Music)
{
Mix_ResumeMusic();
}
else if (!setting_Music)
{
Mix_PauseMusic();
}
}
void Menu()
{
//play background music
myAudio.playMainMusic();
myAudio.stopBackgroundLoop();
//show back the cursor
SDL_ShowCursor(SDL_ENABLE);
//SDL_WarpMouseInWindow(gWindow, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2); //set the cursor to center of the window
//set text positions
int textOffset = SCREEN_HEIGHT / 4;
int textX = SCREEN_WIDTH / 2;
int textY = SCREEN_HEIGHT / 2 - textOffset;
//add buttons
//start button
int buttonpy = textY + SCREEN_HEIGHT / 7.5 + 75;
myButton.init(SCREEN_WIDTH / 2, buttonpy, 50, "Start", regularFont);
buttons.push_back(myButton);
//toggle music button
buttonpy += 75;
myButton.init(SCREEN_WIDTH / 2, buttonpy, 50, "Toggle music", regularFont);
buttons.push_back(myButton);
//quit button
buttonpy += 75;
myButton.init(SCREEN_WIDTH / 2, buttonpy, 50, "Quit", regularFont);
buttons.push_back(myButton);
int choice = -1; //0 for yes, 1 for no
while (choice == -1)
{
deltaTimer.tick();
mouses = SDL_GetMouseState(&mouseX, &mouseY);
handleMenuEvent(choice);
//Clear screen
SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0);
SDL_RenderClear(gRenderer);
//Render black overlay
gMenuTexture.render(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//Render title
drawText(textX, textY, boldFontTitle, UIColor, "Dark Zone", 1);
//set toggle music text
if (setting_Music)
{
buttons[1].setText("Music On");
}
else if (!setting_Music)
{
buttons[1].setText("Music Off");
}
//Render buttons
for (int i = 0; i < buttons.size(); i++)
{
buttons[i].checkButton(mouses, mouseX, mouseY);
buttons[i].render(gRenderer);
}
//Update screen
SDL_RenderPresent(gRenderer);
frameCap();
}
//remove all buttons
buttons.clear();
clearScreen();
StateStruct temp;
switch (choice)
{
case 0: //start
initedLevel = false;
temp.StatePointer = Game;
g_StateStack.push(temp);
break;
case 1: //toggle music
setting_Music = !setting_Music;
break;
case 2: //quit
showConfirmScreen(confirmState::QUIT);
temp.StatePointer = Confirm;
g_StateStack.push(temp);
}
//get backdrop
backdrop = gMenuTexture.getSDLTexture();
}
#pragma endregion
#pragma region Game_Screen
void initLevel()
{
//reset state and flags
endGameMode = endState::FALSE;
confirmMode = confirmState::FALSE;
paused = false;
confirmScreen = false;
endGameScreen = false;
allowSpawnZombie = false;
//clear level objects
trees.clear();
harmZones.clear();
zombies.clear();
bloodpools.clear();
bullets.clear();
signalZones.clear();
healthPickUps.clear();
//reset difficulty
DIFFICULTY = 1;
totalZombieKilled = 0;
//reset timer
timeLeft = TIME_LIMIT;
//reset sound effects
Mix_HaltChannel(-1);
//if tutorial have been finished
if (currentObjective >= 2)
{
//reset objectives
currentObjective = 3;
objective[0] = true;
objective[1] = true;
objective[2] = true;
tutorial = false;
for (int i = 3; i < TOTAL_OBJECTIVE; i++)
{
objective[i] = false;
}
obj_zombieKilled = 0;
allowSpawnZombie = true;
//reset dialogues
dialogue.currentLine = 16;
dialogue.currentPart = 4;
}
else
{
//reset objectives
currentObjective = -1;
for (int i = 0; i < TOTAL_OBJECTIVE; i++)
{
objective[i] = false;
}
for (int i = 0; i < 3; i++)
{
obj_keyPressed[i] = false;
}
tutorial = true;
//reset dialogues
dialogue.currentLine = 0;
dialogue.currentPart = 0;
}
//init player
myPlayer.initPlayer();
//create weapon
myPlayer.myWeapon[0].init(PISTOL_NAME, PISTOL_DAMAGE, PISTOL_RATE_OF_FIRE, PISTOL_CLIP_SIZE, PISTOL_CLIP_SIZE, PISTOL_RELOAD_TIME);
myPlayer.myWeapon[1].init(RIFLE_NAME, RIFLE_DAMAGE, RIFLE_RATE_OF_FIRE, RIFLE_CLIP_SIZE, RIFLE_CLIP_SIZE, RIFLE_RELOAD_TIME);
//create trees
createGameObjectRandom(myTree, trees, MAX_TREE_NUM, MIN_TREE_SIZE, MAX_TREE_SIZE, -1, TREES_CLIP);
//create harmzone
createGameObjectRandom(myHarmZone, harmZones, MAX_HARM_ZONE_NUM * DIFFICULTY, MIN_HARM_ZONE_SIZE, MAX_HARM_ZONE_SIZE);
//create health pickups
createGameObjectRandom(myHealthPickup, healthPickUps, MAX_HEALTH_PICKUP_NUM, HEALTH_PICKUP_SIZE, HEALTH_PICKUP_SIZE);
//create objective zones for objective 5 (find the random signals)
createGameObjectRandom(mySignalZone, signalZones, TOTAL_SIGNAL_ZONE, 500, 500, 0); //random objective zone
obj_zones = signalZones.size();
for (int i = 0; i < signalZones.size(); i++)
{
printf("signalZones[%i] px = %f, py = %f\n", i, signalZones[i].px, signalZones[i].py);
}
printf("---inited level---\n");
}
void checkPreObjective()
{
if (dialogue.currentPart == 1)
{
currentObjective++;
}
}
void checkObjective0(int key)
{
if (currentObjective == 0)
{
obj_keyPressed[key] = true;
if (obj_keyPressed[0] && obj_keyPressed[1] && obj_keyPressed[2] && obj_keyPressed[3])
{
objective[0] = true;
}
}
}
void checkObjective1()
{
if (currentObjective == 1)
{
objective[1] = true;
}
}
void checkObjective2()
{
if (currentObjective == 2)
{
objective[2] = true;
tutorial = false;
}
}
void checkObjective3()
{
if (currentObjective == 3)
{
obj_zombieKilled++;
if (obj_zombieKilled >= ZOMBIE_NEEDED_TO_KILL) //killed required amount of zombies
{
objective[3] = true;
}
}
}
void checkObjective4()
{
if (currentObjective == 4)
{
int i = 0;
while (i < signalZones.size())
{
if (signalZones[i].checkCollision(myPlayer))
{
signalZones.erase(signalZones.begin() + i);
myAudio.playCollectObject();
obj_zones--;
}
else
{
int size1 = signalZones[i].size * 10;
int size2 = signalZones[i].size * 5;
int size3 = signalZones[i].size * 3;
gLightTexture.setColor(0, 0, 255, 25);
gLightTexture.render(camera, signalZones[i].px - size1 / 2, signalZones[i].py - size1 / 2, size1, size1);
gLightTexture.setColor(0, 0, 255, 50);
gLightTexture.render(camera, signalZones[i].px - size2 / 2, signalZones[i].py - size2 / 2, size2, size2);
gLightTexture.setColor(0, 0, 255, 100);
gLightTexture.render(camera, signalZones[i].px - size3 / 2, signalZones[i].py - size3 / 2, size3, size3);
gLightTexture.setColor(0, 0, 255, 200);
gLightTexture.render(camera, signalZones[i].rx, signalZones[i].ry, signalZones[i].size, signalZones[i].size);