Repository navigation
Expand file tree
/
Copy pathAsteroidGameModule.cpp
More file actions
1881 lines (1734 loc) · 73.9 KB
/
Copy pathAsteroidGameModule.cpp
File metadata and controls
1881 lines (1734 loc) · 73.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
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/BgeGameModule.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdlib>
#include <cwctype>
#include <cwchar>
#include <sstream>
#include <string>
#include <windows.h>
namespace {
constexpr float BGE_ASTEROID_GAME_TURN_DEGREES = 10.0f;
constexpr float BGE_ASTEROID_GAME_THRUST_STEP = 36.0f;
constexpr float BGE_ASTEROID_GAME_REVERSE_THRUST_STEP = 24.0f;
constexpr float BGE_ASTEROID_GAME_MAX_PLAYER_SPEED = 420.0f;
constexpr float BGE_ASTEROID_GAME_BULLET_SPEED = 520.0f;
constexpr float BGE_ASTEROID_GAME_BULLET_LIFETIME_SECONDS = 1.35f;
constexpr float BGE_ASTEROID_GAME_SPLIT_MIN_RADIUS = 28.0f;
constexpr float BGE_ASTEROID_GAME_SPLIT_SCALE = 0.58f;
constexpr int BGE_ASTEROID_GAME_RESERVED_BULLET_SLOTS = 2;
// Dedicated UFO slot, sitting just below the bullet reserve. Without this,
// asteroid splits would fill slots 1..N-bulletReserve-1 and starve the UFO
// finder, so a UFO would silently fail to spawn for an entire game.
constexpr int BGE_ASTEROID_GAME_UFO_RESERVED_SLOT = BGE_OBJECT_SLOT_COUNT - BGE_ASTEROID_GAME_RESERVED_BULLET_SLOTS - 1;
constexpr int BGE_ASTEROID_GAME_STARTING_LIVES = 3;
constexpr float BGE_ASTEROID_GAME_RESPAWN_INVULNERABLE_SECONDS = 1.50f;
constexpr float BGE_ASTEROID_GAME_HYPERSPACE_INVULNERABLE_SECONDS = 0.85f;
constexpr int BGE_ASTEROID_GAME_LARGE_ASTEROID_POINTS = 20;
constexpr int BGE_ASTEROID_GAME_MEDIUM_ASTEROID_POINTS = 50;
constexpr int BGE_ASTEROID_GAME_SMALL_ASTEROID_POINTS = 100;
constexpr float BGE_ASTEROID_GAME_UFO_RADIUS = 20.0f;
constexpr float BGE_ASTEROID_GAME_UFO_SPEED = 170.0f;
constexpr float BGE_ASTEROID_GAME_UFO_MIN_ARRIVAL_SECONDS = 7.0f;
constexpr float BGE_ASTEROID_GAME_UFO_MAX_ARRIVAL_SECONDS = 18.0f;
constexpr int BGE_ASTEROID_GAME_UFO_POINTS = 200;
std::wstring LowerModuleArg(std::wstring value)
{
std::transform(value.begin(), value.end(), value.begin(), [](wchar_t character) {
return static_cast<wchar_t>(std::towlower(character));
});
return value;
}
bool TryParseFloatModuleArg(const std::wstring& text, float& value)
{
wchar_t* end = nullptr;
value = std::wcstof(text.c_str(), &end);
return end != text.c_str() && end && *end == L'\0';
}
bool TryParseIntModuleArg(const std::wstring& text, int& value)
{
wchar_t* end = nullptr;
long parsed = std::wcstol(text.c_str(), &end, 10);
if (end == text.c_str() || !end || *end != L'\0') {
return false;
}
value = static_cast<int>(parsed);
return true;
}
bool TryParseSlotModuleArg(const std::wstring& text, int& slotIndex)
{
int parsed = 0;
if (!TryParseIntModuleArg(text, parsed) || parsed < 1 || parsed > BGE_OBJECT_SLOT_COUNT) {
return false;
}
slotIndex = parsed - 1;
return true;
}
float VectorLength(float x, float y)
{
return std::sqrt(x * x + y * y);
}
float RandomFloatInRange(float minimum, float maximum)
{
if (maximum <= minimum) {
return minimum;
}
float unit = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
return minimum + (maximum - minimum) * unit;
}
void NormalizeVectorOrDefault(float x, float y, float& outX, float& outY)
{
float length = VectorLength(x, y);
if (length < 1.0f) {
outX = 1.0f;
outY = 0.0f;
return;
}
outX = x / length;
outY = y / length;
}
void ClampVelocity(float& velocityX, float& velocityY, float maxSpeed)
{
float speed = VectorLength(velocityX, velocityY);
if (speed > maxSpeed && speed > 0.0f) {
float scale = maxSpeed / speed;
velocityX *= scale;
velocityY *= scale;
}
}
bool RuntimeReady(const BgeGameRuntime& runtime)
{
return runtime.objectMutex
&& runtime.objectSlots
&& runtime.animationRunning
&& runtime.activeObjectGroupIndex
&& runtime.mainPlayerGroupIndex
&& runtime.mainPlayerSlot
&& runtime.selectedObjectSlot
&& runtime.objectSelectionActive
&& runtime.rendererStateDirty;
}
int AsteroidGameHitPoints(float radius)
{
if (radius >= 54.0f) {
return BGE_ASTEROID_GAME_LARGE_ASTEROID_POINTS;
}
if (radius >= 32.0f) {
return BGE_ASTEROID_GAME_MEDIUM_ASTEROID_POINTS;
}
return BGE_ASTEROID_GAME_SMALL_ASTEROID_POINTS;
}
std::wstring AsteroidGameTitleText()
{
return L"Asteroid Game | asteroid game/restart | A/D turn | W/S thrust | Space fire | H hyperspace | P pause";
}
std::wstring AsteroidGameCommandText()
{
return L"Asteroid commands: asteroid title | asteroid hud | asteroid status | asteroid commands | asteroid pause/resume | asteroid hyperspace | asteroid player set/select | asteroid add/remove/count | asteroid fire | asteroid score/lives | restart";
}
class AsteroidGameModule final : public BgeGameModule {
public:
const wchar_t* Name() const override
{
return L"Asteroid Game";
}
bool OnStart(BgeGameRuntime& runtime, std::wstring& statusText) override
{
if (runtime.ownsGameLoop && !runtime.ownsGameLoop()) {
statusText = L"Asteroid Game runs in bge.game-loop";
return false;
}
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
BgeGameViewport viewport = runtime.viewport ? runtime.viewport() : BgeGameViewport{};
std::wstring hudText;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
auto& slots = *runtime.objectSlots;
for (int index = 0; index < BGE_OBJECT_SLOT_COUNT; ++index) {
slots[index] = BgeObjectSlotState{};
bulletLifeSeconds_[index] = 0.0f;
}
gameMode_ = true;
score_ = 0;
lives_ = BGE_ASTEROID_GAME_STARTING_LIVES;
respawnInvulnerableSeconds_ = 0.0f;
ufoSlotIndex_ = -1;
ufoViewMode_ = 0;
trialGroupFocus_ = BgeTrialGroup::Ufo;
ResetAsteroidGameUfoArrivalTimerLocked();
gameOver_ = false;
victory_ = false;
*runtime.mainPlayerGroupIndex = *runtime.activeObjectGroupIndex;
*runtime.mainPlayerSlot = 0;
*runtime.selectedObjectSlot = 0;
*runtime.objectSelectionActive = true;
if (runtime.setObjectKeyboardFocusLocked) {
runtime.setObjectKeyboardFocusLocked();
}
ConfigureAsteroidGamePlayerLocked(runtime, 0, viewport.width * 0.50f, viewport.playTop + viewport.playHeight * 0.50f);
ConfigureAsteroidGameAsteroidLocked(runtime, 1, viewport.width * 0.22f, viewport.playTop + viewport.playHeight * 0.26f, 64.0f, 78.0f, 52.0f);
ConfigureAsteroidGameAsteroidLocked(runtime, 2, viewport.width * 0.76f, viewport.playTop + viewport.playHeight * 0.30f, 58.0f, -72.0f, 64.0f);
ConfigureAsteroidGameAsteroidLocked(runtime, 3, viewport.width * 0.54f, viewport.playTop + viewport.playHeight * 0.76f, 52.0f, 54.0f, -86.0f);
std::wstring ufoStatus;
ApplyAsteroidGameUfoViewModeLocked(runtime, ufoViewMode_, viewport, ufoStatus);
BgeSetCurrentEdgePolicy(BgeEdgePolicy::Wrap);
*runtime.animationRunning = true;
if (runtime.refreshSelectedObjectGlobalsLocked) {
runtime.refreshSelectedObjectGlobalsLocked();
}
BgeUpdateCollisionFlags(slots);
if (runtime.persistActiveObjectGroupLocked) {
runtime.persistActiveObjectGroupLocked();
}
*runtime.rendererStateDirty = true;
hudText = BuildAsteroidGameHudLocked(runtime);
}
if (runtime.syncControls) {
runtime.syncControls();
}
if (runtime.invalidateRenderer) {
runtime.invalidateRenderer();
}
if (runtime.setHud) {
runtime.setHud(hudText);
}
statusText = L"Asteroid Game: score 0, lives " + std::to_wstring(lives_) + L"; " + BuildAsteroidGameTrialStatusTextLocked();
if (runtime.log) {
runtime.log("[AsteroidGame] start module=AsteroidGameModule mode=asteroid-game asteroids=3 player-slot=1 edge=wrap");
}
return true;
}
bool OnCommand(BgeGameRuntime& runtime, const std::vector<std::wstring>& tokens, std::wstring& statusText) override
{
if (tokens.empty()) {
statusText = L"Asteroid Game command missing";
return false;
}
std::wstring command = LowerModuleArg(tokens[0]);
if (command == L"score") {
return HandleScoreCommand(runtime, tokens, 1, statusText);
}
if (command == L"lives") {
return HandleLivesCommand(runtime, tokens, 1, statusText);
}
if (command == L"fire") {
return HandleFireCommand(runtime, statusText);
}
if (command == L"pause") {
return HandlePauseCommand(runtime, statusText);
}
if (command == L"resume") {
return HandleResumeCommand(runtime, statusText);
}
if (command == L"hyperspace" || command == L"hyper") {
return HandleHyperspaceCommand(runtime, statusText);
}
if (command == L"restart") {
return OnStart(runtime, statusText);
}
if (command == L"asteroid-game" || command == L"asteroids" || command == L"game") {
return OnStart(runtime, statusText);
}
if (command == L"asteroid") {
std::wstring subcommand = tokens.size() >= 2 ? LowerModuleArg(tokens[1]) : L"status";
if (subcommand == L"game" || subcommand == L"play" || subcommand == L"start") {
return OnStart(runtime, statusText);
}
if (subcommand == L"status" || subcommand == L"state") {
return HandleStatusCommand(runtime, statusText);
}
if (subcommand == L"hud" || subcommand == L"header") {
return HandleHudCommand(runtime, statusText);
}
if (subcommand == L"title" || subcommand == L"screen") {
return HandleTitleCommand(runtime, statusText);
}
if (subcommand == L"commands" || subcommand == L"help") {
return HandleCommandsCommand(runtime, statusText);
}
if (subcommand == L"restart" || subcommand == L"reset") {
return OnStart(runtime, statusText);
}
if (subcommand == L"score") {
return HandleScoreCommand(runtime, tokens, 2, statusText);
}
if (subcommand == L"lives") {
return HandleLivesCommand(runtime, tokens, 2, statusText);
}
if (subcommand == L"fire") {
return HandleFireCommand(runtime, statusText);
}
if (subcommand == L"pause") {
return HandlePauseCommand(runtime, statusText);
}
if (subcommand == L"resume") {
return HandleResumeCommand(runtime, statusText);
}
if (subcommand == L"hyperspace" || subcommand == L"hyper") {
return HandleHyperspaceCommand(runtime, statusText);
}
if (subcommand == L"player") {
return HandlePlayerCommand(runtime, tokens, 2, statusText);
}
if (subcommand == L"add" || subcommand == L"spawn" || subcommand == L"target") {
return HandleAsteroidAddCommand(runtime, tokens, 2, statusText);
}
if (subcommand == L"remove" || subcommand == L"clear") {
return HandleAsteroidRemoveCommand(runtime, tokens, 2, statusText);
}
if (subcommand == L"count") {
return HandleAsteroidCountCommand(runtime, statusText);
}
}
statusText = L"Asteroid Game module command not handled";
return false;
}
bool OnKeyDown(BgeGameRuntime& runtime, unsigned int key) override
{
if (runtime.ownsGameLoop && !runtime.ownsGameLoop()) {
return false;
}
int digitMode = BgeDigitModeIndexFromKey(key);
bool isTrialGroupKey = key == VK_PRIOR || key == VK_NEXT;
bool isGameKey = digitMode >= 0 || isTrialGroupKey || key == L'A' || key == L'a' || key == L'D' || key == L'd' || key == L'W' || key == L'w' || key == L'S' || key == L's' || key == L'H' || key == L'h' || key == L'P' || key == L'p' || key == VK_LEFT || key == VK_RIGHT || key == VK_UP || key == VK_DOWN || key == VK_SPACE;
if (!isGameKey || !RuntimeReady(runtime)) {
return false;
}
bool handled = false;
bool noPlayerSelected = false;
int bulletSlot = -1;
std::wstring statusText;
std::wstring hudText;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
if (!gameMode_) {
return false;
}
if (key == L'P' && !gameOver_ && !victory_) {
*runtime.animationRunning = !*runtime.animationRunning;
handled = true;
statusText = *runtime.animationRunning ? L"Asteroid Game resumed" : L"Asteroid Game paused";
}
else if (gameOver_ || victory_ || !*runtime.animationRunning) {
handled = true;
statusText = BuildAsteroidGameStatusLocked(runtime);
}
else if (isTrialGroupKey) {
trialGroupFocus_ = BgeCycleTrialGroup(trialGroupFocus_, key == VK_PRIOR ? -1 : 1);
handled = true;
statusText = BuildAsteroidGameTrialStatusTextLocked();
}
else if (digitMode >= 0) {
if (trialGroupFocus_ == BgeTrialGroup::Ufo) {
BgeGameViewport viewport = runtime.viewport ? runtime.viewport() : BgeGameViewport{};
handled = ApplyAsteroidGameUfoViewModeLocked(runtime, digitMode, viewport, statusText);
}
else {
handled = ApplyAsteroidGamePlayerIconVisibilityModeLocked(runtime, digitMode, statusText);
}
}
else if (!AsteroidGamePlayerAliveLocked(runtime, *runtime.mainPlayerSlot)) {
noPlayerSelected = true;
}
else if (key == L'A' || key == VK_LEFT) {
handled = RotateAsteroidGamePlayerLocked(runtime, -BGE_ASTEROID_GAME_TURN_DEGREES);
statusText = L"Asteroid Game: rotate left";
}
else if (key == L'D' || key == VK_RIGHT) {
handled = RotateAsteroidGamePlayerLocked(runtime, BGE_ASTEROID_GAME_TURN_DEGREES);
statusText = L"Asteroid Game: rotate right";
}
else if (key == L'W' || key == VK_UP) {
handled = ThrustAsteroidGamePlayerLocked(runtime, BGE_ASTEROID_GAME_THRUST_STEP);
statusText = L"Asteroid Game: thrust";
}
else if (key == L'S' || key == VK_DOWN) {
handled = ThrustAsteroidGamePlayerLocked(runtime, -BGE_ASTEROID_GAME_REVERSE_THRUST_STEP);
statusText = L"Asteroid Game: reverse thrust";
}
else if (key == VK_SPACE) {
handled = FireAsteroidGameProjectileLocked(runtime, bulletSlot);
statusText = handled ? L"Asteroid Game: fire bullet " + std::to_wstring(bulletSlot + 1) : L"Asteroid Game: no projectile slot";
}
else if (key == L'H') {
handled = HyperspaceAsteroidGamePlayerLocked(runtime);
statusText = handled ? L"Asteroid Game: hyperspace" : L"Asteroid Game: hyperspace unavailable";
}
if (handled) {
auto& slots = *runtime.objectSlots;
if (runtime.refreshSelectedObjectGlobalsLocked) {
runtime.refreshSelectedObjectGlobalsLocked();
}
BgeUpdateCollisionFlags(slots);
if (runtime.persistActiveObjectGroupLocked) {
runtime.persistActiveObjectGroupLocked();
}
*runtime.rendererStateDirty = true;
hudText = BuildAsteroidGameHudLocked(runtime);
}
}
if (noPlayerSelected) {
if (runtime.setStatus) {
runtime.setStatus(L"Asteroid Game: select player object 1 to fly");
}
return true;
}
if (handled) {
if (runtime.syncControls) {
runtime.syncControls();
}
if (runtime.invalidateRenderer) {
runtime.invalidateRenderer();
}
if (runtime.setStatus) {
runtime.setStatus(statusText);
}
if (!hudText.empty() && runtime.setHud) {
runtime.setHud(hudText);
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-input key=" << key;
if (bulletSlot >= 0) {
message << " bullet-slot=" << (bulletSlot + 1);
}
runtime.log(message.str());
}
return true;
}
return false;
}
bool OnTick(BgeGameRuntime& runtime, double deltaMilliseconds) override
{
if (!RuntimeReady(runtime)) {
return false;
}
bool dirty = false;
bool playerLostLife = false;
bool gameOver = false;
bool victory = false;
bool invulnerabilityEnded = false;
int hits = 0;
int spawned = 0;
int score = 0;
int lives = 0;
int points = 0;
int ufoHits = 0;
int asteroidsRemaining = 0;
std::wstring hudText;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
if (!gameMode_ || !*runtime.animationRunning) {
return false;
}
auto& slots = *runtime.objectSlots;
float deltaSeconds = static_cast<float>((std::max)(0.0, deltaMilliseconds) / 1000.0);
BgeGameViewport viewport = runtime.viewport ? runtime.viewport() : BgeGameViewport{};
if (respawnInvulnerableSeconds_ > 0.0f) {
float previousInvulnerability = respawnInvulnerableSeconds_;
respawnInvulnerableSeconds_ = (std::max)(0.0f, respawnInvulnerableSeconds_ - deltaSeconds);
if (previousInvulnerability > 0.0f && respawnInvulnerableSeconds_ <= 0.0f) {
ApplyAsteroidGamePlayerVisualLocked(runtime);
invulnerabilityEnded = true;
dirty = true;
}
}
for (int index = 0; index < BGE_OBJECT_SLOT_COUNT; ++index) {
BgeObjectSlotState& slot = slots[index];
if (slot.visible && !slot.isDeleted && slot.kind == BgeObjectKind::Bullet) {
bulletLifeSeconds_[index] -= deltaSeconds;
if (bulletLifeSeconds_[index] <= 0.0f) {
HideAsteroidGameSlotLocked(runtime, index);
dirty = true;
}
}
}
if (!gameOver_ && !victory_) {
int activeUfoSlot = ActiveAsteroidGameUfoSlotLocked(runtime);
if (activeUfoSlot >= 0) {
const BgeObjectSlotState& ufo = slots[activeUfoSlot];
float margin = (std::max)(40.0f, ufo.radius * 3.0f);
if (ufo.x < -margin || ufo.x > viewport.width + margin || ufo.y < viewport.playTop - margin || ufo.y > viewport.playTop + viewport.playHeight + margin) {
HideAsteroidGameSlotLocked(runtime, activeUfoSlot);
ResetAsteroidGameUfoArrivalTimerLocked();
dirty = true;
}
}
else {
ufoArrivalSeconds_ = (std::max)(0.0f, ufoArrivalSeconds_ - deltaSeconds);
if (ufoArrivalSeconds_ <= 0.0f) {
if (SpawnAsteroidGameUfoLocked(runtime, viewport)) {
dirty = true;
}
ResetAsteroidGameUfoArrivalTimerLocked();
}
}
}
for (int bulletIndex = 0; bulletIndex < BGE_OBJECT_SLOT_COUNT; ++bulletIndex) {
BgeObjectSlotState& bullet = slots[bulletIndex];
if (!bullet.visible || bullet.isDeleted || bullet.kind != BgeObjectKind::Bullet) {
continue;
}
for (int ufoIndex = 0; ufoIndex < BGE_OBJECT_SLOT_COUNT; ++ufoIndex) {
BgeObjectSlotState& ufo = slots[ufoIndex];
if (!ufo.visible || ufo.isDeleted || ufo.kind != BgeObjectKind::Ufo) {
continue;
}
if (!BgeObjectSlotsOverlap(bullet, ufo)) {
continue;
}
HideAsteroidGameSlotLocked(runtime, bulletIndex);
HideAsteroidGameSlotLocked(runtime, ufoIndex);
ResetAsteroidGameUfoArrivalTimerLocked();
score_ += BGE_ASTEROID_GAME_UFO_POINTS;
points += BGE_ASTEROID_GAME_UFO_POINTS;
score = score_;
++ufoHits;
dirty = true;
break;
}
}
for (int bulletIndex = 0; bulletIndex < BGE_OBJECT_SLOT_COUNT; ++bulletIndex) {
BgeObjectSlotState& bullet = slots[bulletIndex];
if (!bullet.visible || bullet.isDeleted || bullet.kind != BgeObjectKind::Bullet) {
continue;
}
for (int asteroidIndex = 0; asteroidIndex < BGE_OBJECT_SLOT_COUNT; ++asteroidIndex) {
BgeObjectSlotState& asteroid = slots[asteroidIndex];
if (!asteroid.visible || asteroid.isDeleted || asteroid.kind != BgeObjectKind::Asteroid) {
continue;
}
if (!BgeObjectSlotsOverlap(bullet, asteroid)) {
continue;
}
HideAsteroidGameSlotLocked(runtime, bulletIndex);
int hitPoints = AsteroidGameHitPoints(asteroid.radius);
spawned += SplitAsteroidGameAsteroidLocked(runtime, asteroidIndex);
score_ += hitPoints;
points += hitPoints;
score = score_;
++hits;
dirty = true;
break;
}
}
if (!gameOver_ && !victory_ && respawnInvulnerableSeconds_ <= 0.0f) {
int playerSlot = *runtime.mainPlayerSlot;
if (AsteroidGamePlayerAliveLocked(runtime, playerSlot)) {
for (int asteroidIndex = 0; asteroidIndex < BGE_OBJECT_SLOT_COUNT; ++asteroidIndex) {
BgeObjectSlotState& asteroid = slots[asteroidIndex];
if (!asteroid.visible || asteroid.isDeleted || (asteroid.kind != BgeObjectKind::Asteroid && asteroid.kind != BgeObjectKind::Ufo)) {
continue;
}
if (!BgeObjectSlotsOverlap(slots[playerSlot], asteroid)) {
continue;
}
lives_ = (std::max)(0, lives_ - 1);
lives = lives_;
playerLostLife = true;
dirty = true;
HideAsteroidGameBulletsLocked(runtime);
if (asteroid.kind == BgeObjectKind::Ufo) {
HideAsteroidGameSlotLocked(runtime, asteroidIndex);
ResetAsteroidGameUfoArrivalTimerLocked();
}
if (lives_ <= 0) {
HideAsteroidGameSlotLocked(runtime, playerSlot);
gameOver_ = true;
gameOver = true;
*runtime.animationRunning = false;
}
else {
BgeGameViewport viewport = runtime.viewport ? runtime.viewport() : BgeGameViewport{};
RespawnAsteroidGamePlayerLocked(runtime, viewport);
}
break;
}
}
}
asteroidsRemaining = CountKindLocked(runtime, BgeObjectKind::Asteroid);
if (!gameOver_ && !victory_ && asteroidsRemaining == 0) {
victory_ = true;
victory = true;
*runtime.animationRunning = false;
dirty = true;
}
if (dirty) {
BgeUpdateCollisionFlags(slots);
if (runtime.refreshSelectedObjectGlobalsLocked) {
runtime.refreshSelectedObjectGlobalsLocked();
}
if (runtime.persistActiveObjectGroupLocked) {
runtime.persistActiveObjectGroupLocked();
}
*runtime.rendererStateDirty = true;
hudText = BuildAsteroidGameHudLocked(runtime);
}
}
if (!hudText.empty() && runtime.setHud) {
runtime.setHud(hudText);
}
if (gameOver) {
if (runtime.setStatus) {
runtime.setStatus(L"Game over: score " + std::to_wstring(score_) + L", lives 0; use restart");
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-game-over score=" << score_;
runtime.log(message.str());
}
}
else if (victory) {
if (runtime.setStatus) {
runtime.setStatus(L"Asteroid field cleared: score " + std::to_wstring(score_) + L", lives " + std::to_wstring(lives_));
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-victory score=" << score_ << " lives=" << lives_;
runtime.log(message.str());
}
}
else if (playerLostLife) {
if (runtime.setStatus) {
runtime.setStatus(L"Ship hit: lives " + std::to_wstring(lives) + L", score " + std::to_wstring(score_) + L"; respawning");
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-life-lost lives=" << lives << " score=" << score_;
runtime.log(message.str());
}
}
else if (ufoHits > 0) {
if (runtime.setStatus) {
runtime.setStatus(L"UFO hit: +" + std::to_wstring(points) + L", score " + std::to_wstring(score) + L", lives " + std::to_wstring(lives_));
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-ufo-hit count=" << ufoHits << " points=" << points << " score=" << score;
runtime.log(message.str());
}
}
else if (hits > 0) {
if (runtime.setStatus) {
runtime.setStatus(L"Asteroid hit: +" + std::to_wstring(points) + L", score " + std::to_wstring(score) + L", lives " + std::to_wstring(lives_) + L", asteroids " + std::to_wstring(asteroidsRemaining));
}
if (runtime.log) {
std::ostringstream message;
message << "[AsteroidGame] module-hit count=" << hits << " spawned=" << spawned << " points=" << points << " score=" << score;
runtime.log(message.str());
}
}
else if (invulnerabilityEnded && runtime.setStatus) {
runtime.setStatus(L"Asteroid Game: score " + std::to_wstring(score_) + L", lives " + std::to_wstring(lives_) + L", asteroids " + std::to_wstring(asteroidsRemaining));
}
return dirty;
}
private:
int CountKindLocked(const BgeGameRuntime& runtime, BgeObjectKind kind) const
{
int count = 0;
for (const auto& slot : *runtime.objectSlots) {
if (slot.visible && !slot.isDeleted && slot.kind == kind) {
++count;
}
}
return count;
}
std::wstring BuildAsteroidGameStatusLocked(const BgeGameRuntime& runtime) const
{
int asteroidCount = CountKindLocked(runtime, BgeObjectKind::Asteroid);
int bulletCount = CountKindLocked(runtime, BgeObjectKind::Bullet);
int ufoCount = CountKindLocked(runtime, BgeObjectKind::Ufo);
std::wstring state = L"stopped";
if (gameOver_) {
state = L"game over";
}
else if (victory_) {
state = L"cleared";
}
else if (respawnInvulnerableSeconds_ > 0.0f) {
state = L"respawning";
}
else if (*runtime.animationRunning) {
state = L"running";
}
std::wstringstream status;
status << L"Asteroid Game: score " << score_
<< L", lives " << lives_
<< L", asteroids " << asteroidCount
<< L", bullets " << bulletCount
<< L", ufo " << ufoCount
<< L", " << state
<< L", " << BuildAsteroidGameTrialStatusTextLocked();
return status.str();
}
std::wstring BuildAsteroidGameTrialStatusTextLocked() const
{
std::wstring status = L"test group ";
status += BgeTrialGroupName(trialGroupFocus_);
status += L" | PageUp/PageDown | 0-9 ";
if (trialGroupFocus_ == BgeTrialGroup::Ufo) {
status += L"UFO view " + std::to_wstring(BgeNormalizeUfoViewModeIndex(ufoViewMode_))
+ L" " + BgeUfoViewModeName(ufoViewMode_);
}
else {
status += L"ship view " + std::to_wstring(BgeNormalizePlayerIconVisibilityModeIndex(playerIconVisibilityMode_))
+ L" " + BgePlayerIconVisibilityModeName(playerIconVisibilityMode_);
}
return status;
}
std::wstring BuildAsteroidGameStateTextLocked(const BgeGameRuntime& runtime) const
{
if (gameOver_) {
return L"GAME OVER";
}
if (victory_) {
return L"CLEARED";
}
if (respawnInvulnerableSeconds_ > 0.0f) {
return L"RESPAWN";
}
if (*runtime.animationRunning) {
return L"RUNNING";
}
if (gameMode_) {
return L"PAUSED";
}
return L"READY";
}
std::wstring BuildAsteroidGameHudLocked(const BgeGameRuntime& runtime) const
{
std::wstringstream hud;
hud << L"ASTEROID GAME"
<< L" | SCORE " << score_
<< L" | LIVES " << lives_
<< L" | AST " << CountKindLocked(runtime, BgeObjectKind::Asteroid)
<< L" | UFO " << CountKindLocked(runtime, BgeObjectKind::Ufo)
<< L" | BUL " << CountKindLocked(runtime, BgeObjectKind::Bullet)
<< L" | TEST " << BgeTrialGroupName(trialGroupFocus_)
<< L" | " << BuildAsteroidGameStateTextLocked(runtime);
if (gameOver_) {
hud << L" | restart";
}
else if (victory_) {
hud << L" | field cleared | restart";
}
else if (gameMode_ && !*runtime.animationRunning) {
hud << L" | paused | resume/restart";
}
else {
hud << L" | A/D turn W/S thrust Space fire H hyperspace P pause";
}
return hud.str();
}
std::wstring BuildAsteroidGameScreenTextLocked(const BgeGameRuntime& runtime) const
{
if (gameOver_) {
return L"Game Over | final score " + std::to_wstring(score_) + L" | restart to play again";
}
if (victory_) {
return L"Asteroid Field Cleared | score " + std::to_wstring(score_) + L" | restart for a new field";
}
if (!gameMode_) {
return AsteroidGameTitleText();
}
return BuildAsteroidGameHudLocked(runtime);
}
void PublishAsteroidGameHudLocked(BgeGameRuntime& runtime) const
{
if (runtime.setHud) {
runtime.setHud(BuildAsteroidGameHudLocked(runtime));
}
}
bool HandleStatusCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
statusText = BuildAsteroidGameStatusLocked(runtime);
PublishAsteroidGameHudLocked(runtime);
return true;
}
bool HandleHudCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
statusText = BuildAsteroidGameHudLocked(runtime);
PublishAsteroidGameHudLocked(runtime);
return true;
}
bool HandleTitleCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = AsteroidGameTitleText();
if (runtime.setHud) {
runtime.setHud(statusText);
}
return true;
}
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
statusText = BuildAsteroidGameScreenTextLocked(runtime);
if (runtime.setHud) {
runtime.setHud(statusText);
}
return true;
}
bool HandleCommandsCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
statusText = AsteroidGameCommandText();
if (runtime.setHud) {
runtime.setHud(statusText);
}
return true;
}
bool HandlePauseCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
std::wstring hudText;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
if (!gameMode_) {
statusText = L"Use: asteroid game before pause";
return false;
}
if (gameOver_ || victory_) {
statusText = BuildAsteroidGameStatusLocked(runtime);
hudText = BuildAsteroidGameHudLocked(runtime);
}
else {
*runtime.animationRunning = false;
statusText = L"Asteroid Game paused";
hudText = BuildAsteroidGameHudLocked(runtime);
}
}
if (runtime.setHud) {
runtime.setHud(hudText);
}
return true;
}
bool HandleResumeCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
std::wstring hudText;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
if (!gameMode_) {
statusText = L"Use: asteroid game before resume";
return false;
}
if (gameOver_ || victory_) {
statusText = BuildAsteroidGameStatusLocked(runtime) + L"; use restart";
hudText = BuildAsteroidGameHudLocked(runtime);
}
else {
*runtime.animationRunning = true;
statusText = L"Asteroid Game resumed";
hudText = BuildAsteroidGameHudLocked(runtime);
}
}
if (runtime.setHud) {
runtime.setHud(hudText);
}
if (runtime.invalidateRenderer) {
runtime.invalidateRenderer();
}
return true;
}
bool HandleHyperspaceCommand(BgeGameRuntime& runtime, std::wstring& statusText)
{
if (!RuntimeReady(runtime)) {
statusText = L"Asteroid Game runtime unavailable";
return false;
}
bool moved = false;
{
std::lock_guard<std::mutex> lock(*runtime.objectMutex);
if (!gameMode_) {
statusText = L"Use: asteroid game before hyperspace";
return false;
}
if (gameOver_ || victory_ || !*runtime.animationRunning) {
statusText = BuildAsteroidGameStatusLocked(runtime) + L"; use resume/restart";
PublishAsteroidGameHudLocked(runtime);
return false;
}
moved = HyperspaceAsteroidGamePlayerLocked(runtime);
if (!moved) {
statusText = L"Asteroid Game: hyperspace unavailable";
return false;
}
BgeUpdateCollisionFlags(*runtime.objectSlots);
if (runtime.refreshSelectedObjectGlobalsLocked) {
runtime.refreshSelectedObjectGlobalsLocked();
}
if (runtime.persistActiveObjectGroupLocked) {
runtime.persistActiveObjectGroupLocked();
}
*runtime.rendererStateDirty = true;
}
if (runtime.syncControls) {
runtime.syncControls();
}
if (runtime.invalidateRenderer) {
runtime.invalidateRenderer();
}
PublishAsteroidGameHud(runtime);
statusText = L"Asteroid Game: hyperspace";
if (runtime.log) {
runtime.log("[AsteroidGame] module-command hyperspace");
}
return moved;
}
bool HandleScoreCommand(BgeGameRuntime& runtime, const std::vector<std::wstring>& tokens, size_t operationIndex, std::wstring& statusText)
{
UNREFERENCED_PARAMETER(runtime);
std::wstring operation = operationIndex < tokens.size() ? LowerModuleArg(tokens[operationIndex]) : L"status";
if (operation == L"status" || operation == L"show" || operation == L"current") {
statusText = L"Asteroid Game score: " + std::to_wstring(score_);
PublishAsteroidGameHud(runtime);
return true;
}
if (operation == L"reset" || operation == L"clear") {
score_ = 0;
statusText = L"Asteroid Game score reset";
PublishAsteroidGameHud(runtime);
return true;
}
int points = 0;
if (operation == L"set") {
if (operationIndex + 1 >= tokens.size() || !TryParseIntModuleArg(tokens[operationIndex + 1], points)) {
statusText = L"Use: score set <points>";
return false;
}
score_ = (std::max)(0, points);
statusText = L"Asteroid Game score: " + std::to_wstring(score_);
PublishAsteroidGameHud(runtime);
return true;
}
if (operation == L"add") {
if (operationIndex + 1 >= tokens.size() || !TryParseIntModuleArg(tokens[operationIndex + 1], points)) {
statusText = L"Use: score add <points>";
return false;
}