/
OneLoneCoder_Worms3.PGE.cpp
1310 lines (1120 loc) · 39.1 KB
/
OneLoneCoder_Worms3.PGE.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
/*
OneLoneCoder.com - Code-It-Yourself! Worms Part #3
"stuuup-iid...." - @Javidx9
Disclaimer
~~~~~~~~~~
I don't care what you use this for. It's intended to be educational, and perhaps
to the oddly minded - a little bit of fun. Please hack this, change it and use it
in any way you see fit. BUT, you acknowledge that I am not responsible for anything
bad that happens as a result of your actions. However, if good stuff happens, I
would appreciate a shout out, or at least give the blog some publicity for me.
Cheers!
Background
~~~~~~~~~~
Worms is a classic game where several teams of worms use a variety of weaponry
to elimiate each other from a randomly generated terrain.
This code is the third part of a series that show how to make your own Worms game
from scratch in C++!
Controls A = Aim Left, S = Aim Right, Z = Jump, Space = Charge Weapon, TAB = Zoom
Author
~~~~~~
Twitter: @javidx9
Blog: www.onelonecoder.com
Video:
~~~~~~
Part #1 https://youtu.be/EHlaJvQpW3U
Part #2 https://youtu.be/pV2qYJjCdxM
Part #3 https://youtu.be/NKK5tIRZqyQ
Last Updated: 19/12/2017
*/
/* Alterations Joseph21 - 20220717
* - removed "using namespace std" and added explicit scope resolution operator where needed
* - altered screen and pixel sizes for better overview
* Port to PixelGameEngine - 20220717
* - see cheat sheet for generic adaptations needed for port
* - added function DrawWireFrameModel() - its implemented in the CGE but not in the PGE
* - added mask mode drawing for cWorm.Draw() method and for "mystery code block"
* - rewrote landscape drawing
* - applied .png sprite in OnUserCreate() instead of .spr
* - had to replace the mystery code - couldn't get it to work an render esthetically :(
* - introduced a function SevenSegmentDisplay()
*/
#include <iostream>
#include <string>
#include <algorithm>
//using namespace std;
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
// This function is present in the CGE, but not in the PGE.
// vecModelCoordinates = the wire frame model
// x, y - the screenposition where to draw it
// r = angle of rotation
// s = scaling factor
void DrawWireFrameModel(
olc::PixelGameEngine *engine,
const std::vector<std::pair<float, float>> &vecModelCoordinates,
float x, float y,
float r = 0.0f,
float s = 1.0f,
olc::Pixel col = olc::WHITE
) {
// pair.first = x coordinate
// pair.second = y coordinate
// Create translated model vector of coordinate pairs
std::vector<std::pair<float, float>> vecTransformedCoordinates;
int verts = vecModelCoordinates.size(); // keep the model vector static
vecTransformedCoordinates.resize( verts ); // create another vector the same size as the model vector
// Rotate
for (int i = 0; i < verts; i++) {
vecTransformedCoordinates[i].first = vecModelCoordinates[i].first * cosf( r ) - vecModelCoordinates[i].second * sinf( r );
vecTransformedCoordinates[i].second = vecModelCoordinates[i].first * sinf( r ) + vecModelCoordinates[i].second * cosf( r );
}
// Scale
for (int i = 0; i < verts; i++) {
vecTransformedCoordinates[i].first = vecTransformedCoordinates[i].first * s;
vecTransformedCoordinates[i].second = vecTransformedCoordinates[i].second * s;
}
// Translate
for (int i = 0; i < verts; i++) {
vecTransformedCoordinates[i].first = vecTransformedCoordinates[i].first + x;
vecTransformedCoordinates[i].second = vecTransformedCoordinates[i].second + y;
}
// Draw closed polygon
for (int i = 0; i < verts + 1; i++) {
int j = (i + 1);
engine->DrawLine( vecTransformedCoordinates[i % verts].first, vecTransformedCoordinates[i % verts].second,
vecTransformedCoordinates[j % verts].first, vecTransformedCoordinates[j % verts].second, col );
}
}
class cPhysicsObject
{
public:
cPhysicsObject(float x = 0.0f, float y = 0.0f)
{
px = x;
py = y;
}
public:
float px = 0.0f; // Position
float py = 0.0f;
float vx = 0.0f; // Velocity
float vy = 0.0f;
float ax = 0.0f; // Acceleration
float ay = 0.0f;
float radius = 4.0f; // Bounding rectangle for collisions
float fFriction = 0.0f; // Actually, a dampening factor is a more accurate name
int nBounceBeforeDeath = -1; // How many time object can bounce before death
bool bDead; // Flag to indicate object should be removed
bool bStable = false; // Has object stopped moving
// Make class abstract
virtual void Draw(olc::PixelGameEngine *engine, float fOffsetX, float fOffsetY, bool bPixel = false) = 0;
virtual int BounceDeathAction() = 0;
virtual bool Damage(float d) = 0;
};
class cDebris : public cPhysicsObject // a small rock that bounces
{
public:
cDebris(float x = 0.0f, float y = 0.0f) : cPhysicsObject(x, y)
{
// Set velocity to random direction and size for "boom" effect
vx = 10.0f * cosf(((float)rand() / (float)RAND_MAX) * 2.0f * 3.14159f);
vy = 10.0f * sinf(((float)rand() / (float)RAND_MAX) * 2.0f * 3.14159f);
radius = 1.0f;
fFriction = 0.8f;
bDead = false;
bStable = false;
nBounceBeforeDeath = 2; // After 2 bounces, dispose
}
virtual void Draw(olc::PixelGameEngine *engine, float fOffsetX, float fOffsetY, bool bPixel = false)
{
DrawWireFrameModel(engine, vecModel, px - fOffsetX, py - fOffsetY, atan2f(vy, vx), bPixel ? 0.5f : radius, olc::DARK_GREEN);
}
virtual int BounceDeathAction()
{
return 0; // Nothing, just fade
}
virtual bool Damage(float d)
{
return true; // Cannot be damaged
}
private:
static std::vector<std::pair<float, float>> vecModel;
};
std::vector<std::pair<float, float>> DefineDebris()
{
// A small unit rectangle
std::vector<std::pair<float, float>> vecModel;
vecModel.push_back({ 0.0f, 0.0f });
vecModel.push_back({ 1.0f, 0.0f });
vecModel.push_back({ 1.0f, 1.0f });
vecModel.push_back({ 0.0f, 1.0f });
return vecModel;
}
std::vector<std::pair<float, float>> cDebris::vecModel = DefineDebris();
class cMissile : public cPhysicsObject // A projectile weapon
{
public:
cMissile(float x = 0.0f, float y = 0.0f, float _vx = 0.0f, float _vy = 0.0f) : cPhysicsObject(x, y)
{
radius = 2.5f;
fFriction = 0.5f;
vx = _vx;
vy = _vy;
bDead = false;
nBounceBeforeDeath = 1;
bStable = false;
}
virtual void Draw(olc::PixelGameEngine *engine, float fOffsetX, float fOffsetY, bool bPixel = false)
{
DrawWireFrameModel(engine, vecModel, px - fOffsetX, py - fOffsetY, atan2f(vy, vx), bPixel ? 0.5f : radius, olc::BLACK);
}
virtual int BounceDeathAction()
{
return 20; // Explode Big
}
virtual bool Damage(float d)
{
return true;
}
private:
static std::vector<std::pair<float, float>> vecModel;
};
std::vector<std::pair<float, float>> DefineMissile()
{
// Defines a rocket like shape
std::vector<std::pair<float, float>> vecModel;
vecModel.push_back({ 0.0f, 0.0f });
vecModel.push_back({ 1.0f, 1.0f });
vecModel.push_back({ 2.0f, 1.0f });
vecModel.push_back({ 2.5f, 0.0f });
vecModel.push_back({ 2.0f, -1.0f });
vecModel.push_back({ 1.0f, -1.0f });
vecModel.push_back({ 0.0f, 0.0f });
vecModel.push_back({ -1.0f, -1.0f });
vecModel.push_back({ -2.5f, -1.0f });
vecModel.push_back({ -2.0f, 0.0f });
vecModel.push_back({ -2.5f, 1.0f });
vecModel.push_back({ -1.0f, 1.0f });
// Scale points to make shape unit(ish) sized
for (auto &v : vecModel)
{
v.first /= 1.5f; v.second /= 1.5f;
}
return vecModel;
}
std::vector<std::pair<float, float>> cMissile::vecModel = DefineMissile();
class cWorm : public cPhysicsObject // A unit, or worm
{
public:
cWorm(float x = 0.0f, float y = 0.0f) : cPhysicsObject(x, y)
{
radius = 3.5f;
fFriction = 0.2f;
bDead = false;
nBounceBeforeDeath = -1;
bStable = false;
// load sprite data from sprite file
if (sprWorm == nullptr)
sprWorm = new olc::Sprite("WormsSprites/worms1.png");
}
virtual void Draw(olc::PixelGameEngine *engine, float fOffsetX, float fOffsetY, bool bPixel = false)
{
engine->SetPixelMode( olc::Pixel::MASK );
if (bIsPlayable) // Draw Worm Sprite with health bar, in team colours
{
engine->DrawPartialSprite(px - fOffsetX - radius, py - fOffsetY - radius, sprWorm, nTeam * 8, 0, 8, 8);
// Draw health bar for worm
for (int i = 0; i < 11 * fHealth; i++)
{
engine->Draw(px - 5 + i - fOffsetX, py + 5 - fOffsetY, olc::BLUE);
engine->Draw(px - 5 + i - fOffsetX, py + 6 - fOffsetY, olc::BLUE);
}
}
else // Draw tombstone sprite for team colour
{
engine->DrawPartialSprite(px - fOffsetX - radius, py - fOffsetY - radius, sprWorm, nTeam * 8, 8, 8, 8);
}
engine->SetPixelMode( olc::Pixel::NORMAL );
}
virtual int BounceDeathAction()
{
return 0; // Nothing
}
virtual bool Damage(float d) // Reduce worm's health by said amount
{
fHealth -= d;
if (fHealth <= 0)
{ // Worm has died, no longer playable
fHealth = 0.0f;
bIsPlayable = false;
}
return fHealth > 0;
}
public:
float fShootAngle = 0.0f;
float fHealth = 1.0f;
int nTeam = 0; // ID of which team this worm belongs to
bool bIsPlayable = true;
private:
static olc::Sprite *sprWorm;
};
olc::Sprite* cWorm::sprWorm = nullptr;
class cTeam // Defines a group of worms
{
public:
std::vector<cWorm*> vecMembers;
int nCurrentMember = 0; // Index into vector for current worms turn
int nTeamSize = 0; // Total number of worms in team
bool IsTeamAlive()
{
// Iterate through all team members, if any of them have >0 health, return true;
bool bAllDead = false;
for (auto w : vecMembers)
bAllDead |= (w->fHealth > 0.0f);
return bAllDead;
}
cWorm* GetNextMember()
{
// Return a pointer to the next team member that is valid for control
do {
nCurrentMember++;
if (nCurrentMember >= nTeamSize) nCurrentMember = 0;
} while (vecMembers[nCurrentMember]->fHealth <= 0);
return vecMembers[nCurrentMember];
}
};
// Main Game Engine Class
class OneLoneCoder_Worms : public olc::PixelGameEngine // The game
{
public:
OneLoneCoder_Worms()
{
sAppName = "Worms";
}
private:
// Terrain size
int nMapWidth = 1024;
int nMapHeight = 512;
char *map = nullptr;
// Camera Coordinates
float fCameraPosX = 0.0f;
float fCameraPosY = 0.0f;
float fCameraPosXTarget = 0.0f;
float fCameraPosYTarget = 0.0f;
// list of things that exist in game world
std::list<std::unique_ptr<cPhysicsObject>> listObjects;
cPhysicsObject* pObjectUnderControl = nullptr; // Pointer to object currently under control
cPhysicsObject* pCameraTrackingObject = nullptr; // Pointer to object that camera should track
// Flags that govern/are set by game state machine
bool bZoomOut = false; // Render whole map
bool bGameIsStable = false; // All physics objects are stable
bool bEnablePlayerControl = true; // The player is in control, keyboard input enabled
bool bEnableComputerControl = false; // The AI is in control
bool bEnergising = false; // Weapon is charging
bool bFireWeapon = false; // Weapon should be discharged
bool bShowCountDown = false; // Display turn time counter on screen
bool bPlayerHasFired = false; // Weapon has been discharged
float fEnergyLevel = 0.0f; // Energy accumulated through charging (player only)
float fTurnTime = 0.0f; // Time left to take turn
// Vector to store teams
std::vector<cTeam> vecTeams;
// Current team being controlled
int nCurrentTeam = 0;
// AI control flags
bool bAI_Jump = false; // AI has pressed "JUMP" key
bool bAI_AimLeft = false; // AI has pressed "AIM_LEFT" key
bool bAI_AimRight = false; // AI has pressed "AIM_RIGHT" key
bool bAI_Energise = false; // AI has pressed "FIRE" key
float fAITargetAngle = 0.0f; // Angle AI should aim for
float fAITargetEnergy = 0.0f; // Energy level AI should aim for
float fAISafePosition = 0.0f; // X-Coordinate considered safe for AI to move to
cWorm* pAITargetWorm = nullptr; // Pointer to worm AI has selected as target
float fAITargetX = 0.0f; // Coordinates of target missile location
float fAITargetY = 0.0f;
enum GAME_STATE
{
GS_RESET = 0,
GS_GENERATE_TERRAIN = 1,
GS_GENERATING_TERRAIN,
GS_ALLOCATE_UNITS,
GS_ALLOCATING_UNITS,
GS_START_PLAY,
GS_CAMERA_MODE,
GS_GAME_OVER1,
GS_GAME_OVER2
} nGameState, nNextState;
enum AI_STATE
{
AI_ASSESS_ENVIRONMENT = 0,
AI_MOVE,
AI_CHOOSE_TARGET,
AI_POSITION_FOR_TARGET,
AI_AIM,
AI_FIRE,
} nAIState, nAINextState;
virtual bool OnUserCreate()
{
// Create Map
map = new char[nMapWidth * nMapHeight];
memset(map, 0, nMapWidth*nMapHeight * sizeof( char));
// Set initial states for state machines
nGameState = GS_RESET;
nNextState = GS_RESET;
nAIState = AI_ASSESS_ENVIRONMENT;
nAINextState = AI_ASSESS_ENVIRONMENT;
bGameIsStable = false;
return true;
}
virtual bool OnUserUpdate(float fElapsedTime)
{
// Tab key toggles between whole map view and up close view
if (GetKey(olc::Key::TAB).bReleased)
bZoomOut = !bZoomOut;
// Mouse Edge Map Scroll
float fMapScrollSpeed = 400.0f;
if (GetMouseX() < 5) fCameraPosX -= fMapScrollSpeed * fElapsedTime;
if (GetMouseX() > ScreenWidth() - 5) fCameraPosX += fMapScrollSpeed * fElapsedTime;
if (GetMouseY() < 5) fCameraPosY -= fMapScrollSpeed * fElapsedTime;
if (GetMouseY() > ScreenHeight() - 5) fCameraPosY += fMapScrollSpeed * fElapsedTime;
// Control Supervisor
switch (nGameState)
{
case GS_RESET:
{
bEnablePlayerControl = false;
bGameIsStable = false;
bPlayerHasFired = false;
bShowCountDown = false;
nNextState = GS_GENERATE_TERRAIN;
}
break;
case GS_GENERATE_TERRAIN:
{
bZoomOut = true;
CreateMap();
bGameIsStable = false;
bShowCountDown = false;
nNextState = GS_GENERATING_TERRAIN;
}
break;
case GS_GENERATING_TERRAIN:
{
bShowCountDown = false;
if (bGameIsStable)
nNextState = GS_ALLOCATE_UNITS;
}
break;
case GS_ALLOCATE_UNITS:
{
// Deploy teams
int nTeams = 4;
int nWormsPerTeam = 4;
// Calculate spacing of worms and teams
float fSpacePerTeam = (float)nMapWidth / (float)nTeams;
float fSpacePerWorm = fSpacePerTeam / (nWormsPerTeam * 2.0f);
// Create teams
for (int t = 0; t < nTeams; t++)
{
vecTeams.emplace_back(cTeam());
float fTeamMiddle = (fSpacePerTeam / 2.0f) + (t * fSpacePerTeam);
for (int w = 0; w < nWormsPerTeam; w++)
{
float fWormX = fTeamMiddle - ((fSpacePerWorm * (float)nWormsPerTeam) / 2.0f) + w * fSpacePerWorm;
float fWormY = 0.0f;
// Add worms to teams
cWorm *worm = new cWorm(fWormX,fWormY);
worm->nTeam = t;
listObjects.push_back(std::unique_ptr<cWorm>(worm));
vecTeams[t].vecMembers.push_back(worm);
vecTeams[t].nTeamSize = nWormsPerTeam;
}
vecTeams[t].nCurrentMember = 0;
}
// Select players first worm for control and camera tracking
pObjectUnderControl = vecTeams[0].vecMembers[vecTeams[0].nCurrentMember];
pCameraTrackingObject = pObjectUnderControl;
bShowCountDown = false;
nNextState = GS_ALLOCATING_UNITS;
}
break;
case GS_ALLOCATING_UNITS: // Wait for units to "parachute" in
{
if (bGameIsStable)
{
bEnablePlayerControl = true;
bEnableComputerControl = false;
fTurnTime = 15.0f;
bZoomOut = false;
nNextState = GS_START_PLAY;
}
}
break;
case GS_START_PLAY:
{
bShowCountDown = true;
// If player has discharged weapon, or turn time is up, move on to next state
if (bPlayerHasFired || fTurnTime <= 0.0f)
nNextState = GS_CAMERA_MODE;
}
break;
case GS_CAMERA_MODE: // Camera follows object of interest until the physics engine has settled
{
bEnableComputerControl = false;
bEnablePlayerControl = false;
bPlayerHasFired = false;
bShowCountDown = false;
fEnergyLevel = 0.0f;
if (bGameIsStable) // Once settled, choose next worm
{
// Get Next Team, if there is no next team, game is over
int nOldTeam = nCurrentTeam;
do {
nCurrentTeam++;
nCurrentTeam %= vecTeams.size();
} while (!vecTeams[nCurrentTeam].IsTeamAlive());
// Lock controls if AI team is currently playing
if (nCurrentTeam == 0) // Player Team
{
bEnablePlayerControl = true; // Swap these around for complete AI battle
bEnableComputerControl = false;
}
else // AI Team
{
bEnablePlayerControl = false;
bEnableComputerControl = true;
}
// Set control and camera
pObjectUnderControl = vecTeams[nCurrentTeam].GetNextMember();
pCameraTrackingObject = pObjectUnderControl;
fTurnTime = 15.0f;
bZoomOut = false;
nNextState = GS_START_PLAY;
// If no different team could be found...
if (nCurrentTeam == nOldTeam)
{
// ...Game is over, Current Team have won!
nNextState = GS_GAME_OVER1;
}
}
}
break;
case GS_GAME_OVER1: // Zoom out and launch loads of missiles!
{
bEnableComputerControl = false;
bEnablePlayerControl = false;
bZoomOut = true;
bShowCountDown = false;
for (int i = 0; i < 100; i ++)
{
int nBombX = rand() % nMapWidth;
int nBombY = rand() % (nMapHeight / 2);
listObjects.push_back(std::unique_ptr<cMissile>(new cMissile(nBombX, nBombY, 0.0f, 0.5f)));
}
nNextState = GS_GAME_OVER2;
}
break;
case GS_GAME_OVER2: // Stay here and wait for chaos to settle
{
bEnableComputerControl = false;
bEnablePlayerControl = false;
// No exit from this state!
}
break;
}
// AI State Machine
if (bEnableComputerControl)
{
switch (nAIState)
{
case AI_ASSESS_ENVIRONMENT:
{
int nAction = rand() % 3;
if (nAction == 0) // Play Defensive - move away from team
{
// Find nearest ally, walk away from them
float fNearestAllyDistance = INFINITY; float fDirection = 0;
cWorm *origin = (cWorm*)pObjectUnderControl;
for (auto w : vecTeams[nCurrentTeam].vecMembers)
{
if (w != pObjectUnderControl)
{
if (fabs(w->px - origin->px) < fNearestAllyDistance)
{
fNearestAllyDistance = fabs(w->px - origin->px);
fDirection = (w->px - origin->px) < 0.0f ? 1.0f : -1.0f;
}
}
}
if (fNearestAllyDistance < 50.0f)
fAISafePosition = origin->px + fDirection * 80.0f;
else
fAISafePosition = origin->px;
}
if (nAction == 1) // Play Ballsy - move towards middle
{
cWorm *origin = (cWorm*)pObjectUnderControl;
float fDirection = ((float)(nMapWidth / 2.0f) - origin->px) < 0.0f ? -1.0f : 1.0f;
fAISafePosition = origin->px + fDirection * 200.0f;
}
if (nAction == 2) // Play Dumb - don't move
{
cWorm *origin = (cWorm*)pObjectUnderControl;
fAISafePosition = origin->px;
}
// Clamp so dont walk off map
if (fAISafePosition <= 20.0f) fAISafePosition = 20.0f;
if (fAISafePosition >= nMapWidth - 20.0f) fAISafePosition = nMapWidth - 20.0f;
nAINextState = AI_MOVE;
}
break;
case AI_MOVE:
{
cWorm *origin = (cWorm*)pObjectUnderControl;
if (fTurnTime >= 8.0f && origin->px != fAISafePosition)
{
// Walk towards target until it is in range
if (fAISafePosition < origin->px && bGameIsStable)
{
origin->fShootAngle = -3.14159f * 0.6f;
bAI_Jump = true;
nAINextState = AI_MOVE;
}
if (fAISafePosition > origin->px && bGameIsStable)
{
origin->fShootAngle = -3.14159f * 0.4f;
bAI_Jump = true;
nAINextState = AI_MOVE;
}
}
else
nAINextState = AI_CHOOSE_TARGET;
}
break;
case AI_CHOOSE_TARGET: // Worm finished moving, choose target
{
bAI_Jump = false;
// Select Team that is not itself
cWorm *origin = (cWorm*)pObjectUnderControl;
int nCurrentTeam = origin->nTeam;
int nTargetTeam = 0;
do {
nTargetTeam = rand() % vecTeams.size();
} while (nTargetTeam == nCurrentTeam || !vecTeams[nTargetTeam].IsTeamAlive());
// Aggressive strategy is to aim for opponent unit with most health
cWorm *mostHealthyWorm = vecTeams[nTargetTeam].vecMembers[0];
for (auto w : vecTeams[nTargetTeam].vecMembers)
if (w->fHealth > mostHealthyWorm->fHealth)
mostHealthyWorm = w;
pAITargetWorm = mostHealthyWorm;
fAITargetX = mostHealthyWorm->px;
fAITargetY = mostHealthyWorm->py;
nAINextState = AI_POSITION_FOR_TARGET;
}
break;
case AI_POSITION_FOR_TARGET: // Calculate trajectory for target, if the worm needs to move, do so
{
cWorm *origin = (cWorm*)pObjectUnderControl;
float dy = -(fAITargetY - origin->py);
float dx = -(fAITargetX - origin->px);
float fSpeed = 30.0f;
float fGravity = 2.0f;
bAI_Jump = false;
float a = fSpeed * fSpeed*fSpeed*fSpeed - fGravity * (fGravity * dx * dx + 2.0f * dy * fSpeed * fSpeed);
if (a < 0) // Target is out of range
{
if (fTurnTime >= 5.0f)
{
// Walk towards target until it is in range
if (pAITargetWorm->px < origin->px && bGameIsStable)
{
origin->fShootAngle = -3.14159f * 0.6f;
bAI_Jump = true;
nAINextState = AI_POSITION_FOR_TARGET;
}
if (pAITargetWorm->px > origin->px && bGameIsStable)
{
origin->fShootAngle = -3.14159f * 0.4f;
bAI_Jump = true;
nAINextState = AI_POSITION_FOR_TARGET;
}
}
else
{
// Worm is stuck, so just fire in direction of enemy!
// Its dangerous to self, but may clear a blockage
fAITargetAngle = origin->fShootAngle;
fAITargetEnergy = 0.75f;
nAINextState = AI_AIM;
}
}
else
{
// Worm is close enough, calculate trajectory
float b1 = fSpeed * fSpeed + sqrtf(a);
float b2 = fSpeed * fSpeed - sqrtf(a);
float fTheta1 = atanf(b1 / (fGravity * dx)); // Max Height
float fTheta2 = atanf(b2 / (fGravity * dx)); // Min Height
// We'll use max as its a greater chance of avoiding obstacles
fAITargetAngle = fTheta1 - (dx > 0 ? 3.14159f : 0.0f);
float fFireX = cosf(fAITargetAngle);
float fFireY = sinf(fAITargetAngle);
// AI is clamped to 3/4 power
fAITargetEnergy = 0.75f;
nAINextState = AI_AIM;
}
}
break;
case AI_AIM: // Line up aim cursor
{
cWorm *worm = (cWorm*)pObjectUnderControl;
bAI_AimLeft = false;
bAI_AimRight = false;
bAI_Jump = false;
if (worm->fShootAngle < fAITargetAngle)
bAI_AimRight = true;
else
bAI_AimLeft = true;
// Once cursors are aligned, fire - some noise could be
// included here to give the AI a varying accuracy, and the
// magnitude of the noise could be linked to game difficulty
if (fabs(worm->fShootAngle - fAITargetAngle) <= 0.001f)
{
bAI_AimLeft = false;
bAI_AimRight = false;
fEnergyLevel = 0.0f;
nAINextState = AI_FIRE;
}
else
nAINextState = AI_AIM;
}
break;
case AI_FIRE:
{
bAI_Energise = true;
bFireWeapon = false;
bEnergising = true;
if (fEnergyLevel >= fAITargetEnergy)
{
bFireWeapon = true;
bAI_Energise = false;
bEnergising = false;
bEnableComputerControl = false;
nAINextState = AI_ASSESS_ENVIRONMENT;
}
}
break;
}
}
// Decrease Turn Time
fTurnTime -= fElapsedTime;
if (pObjectUnderControl != nullptr)
{
pObjectUnderControl->ax = 0.0f;
if (pObjectUnderControl->bStable)
{
if ((bEnablePlayerControl && GetKey(olc::Key::Z).bPressed) || (bEnableComputerControl && bAI_Jump))
{
float a = ((cWorm*)pObjectUnderControl)->fShootAngle;
pObjectUnderControl->vx = 4.0f * cosf(a);
pObjectUnderControl->vy = 8.0f * sinf(a);
pObjectUnderControl->bStable = false;
bAI_Jump = false;
}
if ((bEnablePlayerControl && GetKey(olc::Key::S).bHeld) || (bEnableComputerControl && bAI_AimRight))
{
cWorm* worm = (cWorm*)pObjectUnderControl;
worm->fShootAngle += 1.0f * fElapsedTime;
if (worm->fShootAngle > 3.14159f) worm->fShootAngle -= 3.14159f * 2.0f;
}
if ((bEnablePlayerControl && GetKey(olc::Key::A).bHeld) || (bEnableComputerControl && bAI_AimLeft))
{
cWorm* worm = (cWorm*)pObjectUnderControl;
worm->fShootAngle -= 1.0f * fElapsedTime;
if (worm->fShootAngle < -3.14159f) worm->fShootAngle += 3.14159f * 2.0f;
}
if ((bEnablePlayerControl && GetKey(olc::Key::SPACE).bPressed))
{
bFireWeapon = false;
bEnergising = true;
fEnergyLevel = 0.0f;
}
if ((bEnablePlayerControl && GetKey(olc::Key::SPACE).bHeld) || (bEnableComputerControl && bAI_Energise))
{
if (bEnergising)
{
fEnergyLevel += 0.75f * fElapsedTime;
if (fEnergyLevel >= 1.0f)
{
fEnergyLevel = 1.0f;
bFireWeapon = true;
}
}
}
if ((bEnablePlayerControl && GetKey(olc::Key::SPACE).bReleased))
{
if (bEnergising)
{
bFireWeapon = true;
}
bEnergising = false;
}
}
if (pCameraTrackingObject != nullptr)
{
fCameraPosXTarget = pCameraTrackingObject->px - ScreenWidth() / 2;
fCameraPosYTarget = pCameraTrackingObject->py - ScreenHeight() / 2;
fCameraPosX += (fCameraPosXTarget - fCameraPosX) * 15.0f * fElapsedTime;
fCameraPosY += (fCameraPosYTarget - fCameraPosY) * 15.0f * fElapsedTime;
}
if (bFireWeapon)
{
cWorm* worm = (cWorm*)pObjectUnderControl;
// Get Weapon Origin
float ox = worm->px;
float oy = worm->py;
// Get Weapon Direction
float dx = cosf(worm->fShootAngle);
float dy = sinf(worm->fShootAngle);
// Create Weapon Object
cMissile *m = new cMissile(ox, oy, dx * 40.0f * fEnergyLevel, dy * 40.0f * fEnergyLevel);
pCameraTrackingObject = m;
listObjects.push_back(std::unique_ptr<cMissile>(m));
// Reset flags involved with firing weapon
bFireWeapon = false;
fEnergyLevel = 0.0f;
bEnergising = false;
bPlayerHasFired = true;
if (rand() % 100 >= 50)
bZoomOut = true;
}
}
// Clamp map boundaries
if (fCameraPosX < 0) fCameraPosX = 0;
if (fCameraPosX >= nMapWidth - ScreenWidth()) fCameraPosX = nMapWidth - ScreenWidth();
if (fCameraPosY < 0) fCameraPosY = 0;
if (fCameraPosY >= nMapHeight - ScreenHeight()) fCameraPosY = nMapHeight - ScreenHeight();
// Do 10 physics iterations per frame
for (int z = 0; z < 10; z++)
{
// Update physics of all physical objects
for (auto &p : listObjects)
{
// Apply Gravity
p->ay += 2.0f;
// Update Velocity
p->vx += p->ax * fElapsedTime;
p->vy += p->ay * fElapsedTime;
// Update Position
float fPotentialX = p->px + p->vx * fElapsedTime;
float fPotentialY = p->py + p->vy * fElapsedTime;
// Reset Acceleration
p->ax = 0.0f;
p->ay = 0.0f;
p->bStable = false;
// Collision Check With Map
float fAngle = atan2f(p->vy, p->vx);
float fResponseX = 0;
float fResponseY = 0;
bool bCollision = false;
for (float r = fAngle - 3.14159f / 2.0f; r < fAngle + 3.14159f / 2.0f; r += 3.14159f / 4.0f)
{
// Iterate through semicircle of objects radius rotated to direction of travel
float fTestPosX = (p->radius) * cosf(r) + fPotentialX;
float fTestPosY = (p->radius) * sinf(r) + fPotentialY;
if (fTestPosX >= nMapWidth) fTestPosX = nMapWidth - 1;
if (fTestPosY >= nMapHeight) fTestPosY = nMapHeight - 1;
if (fTestPosX < 0) fTestPosX = 0;
if (fTestPosY < 0) fTestPosY = 0;
// Test if any points on semicircle intersect with terrain
if (map[(int)fTestPosY * nMapWidth + (int)fTestPosX] > 0)
{
// Accumulate collision points to give an escape response vector
// Effectively, normal to the areas of contact
fResponseX += fPotentialX - fTestPosX;
fResponseY += fPotentialY - fTestPosY;
bCollision = true;
}
}
float fMagVelocity = sqrtf(p->vx*p->vx + p->vy*p->vy);
float fMagResponse = sqrtf(fResponseX*fResponseX + fResponseY*fResponseY);
if (p->px < 0 || p->px > nMapWidth || p->py <0 || p->py > nMapHeight)
p->bDead = true;
// Find angle of collision
if (bCollision)
{
p->bStable = true;
// Calculate reflection vector of objects velocity vector, using response vector as normal
float dot = p->vx * (fResponseX / fMagResponse) + p->vy * (fResponseY / fMagResponse);
// Use friction coefficient to dampen response (approximating energy loss)