-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpringChallenge.cpp
2056 lines (1711 loc) · 59.7 KB
/
SpringChallenge.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
#pragma region ..\Codin\AssassinController.cpp
// #include "AssassinController.h"
#pragma region ..\Codin\AssassinController.h
// #pragma once
// #include "Controller.h"
#pragma region ..\Codin\Controller.h
// #pragma once
// #include "Vector.h"
#pragma region ..\Codin\Vector.h
// #pragma once
// #include "Math.h"
#pragma region ..\Codin\Math.h
// #pragma once
#include <cmath>
constexpr inline int Pow2(int val)
{
return val * val;
}
inline int Sqrt(int val)
{
return static_cast<int>(std::sqrt(static_cast<float>(val)));
}
#pragma endregion ..\Codin\Math.h
#include <iosfwd>
struct Vector
{
int x, y;
bool operator==(const Vector& b) const { return x == b.x && y == b.y; }
bool operator!=(const Vector& b) const { return !(*this == b); }
Vector operator+(const Vector& b) const { return { x + b.x, y + b.y }; }
Vector& operator+=(const Vector& b) { x += b.x; y += b.y; return *this; }
Vector operator-(const Vector& b) const { return { x - b.x, y - b.y }; }
Vector& operator-=(const Vector& b) { x -= b.x; y -= b.y; return *this; }
Vector operator*(int b) const { return { x * b, y * b }; }
Vector& operator*=(int b) { x *= b; y *= b; return *this; }
Vector operator/(int b) const { return { x / b, y / b }; }
Vector& operator/=(int b) { x /= b; y /= b; return *this; }
Vector operator-() const { return { -x, -y }; };
constexpr int Length2() const { return Pow2(x) + Pow2(y); }
Vector Lengthed(int length) const;
Vector Limited(int lenght) const;
Vector Perpendicular() const;
};
inline int Distance2(const Vector& a, const Vector& b)
{
return Pow2(a.x - b.x) + Pow2(a.y - b.y);
}
std::istream& operator>>(std::istream& in, Vector& vec);
std::ostream& operator<<(std::ostream& out, const Vector& vec);
#pragma endregion ..\Codin\Vector.h
#include <iosfwd>
#include <string>
#include <string_view>
class Entity;
class Game;
enum class Spell : int8_t
{
None,
Wind,
Shield,
Control,
};
std::ostream& operator<<(std::ostream& out, Spell spell);
class Controller
{
public:
Controller(const Entity& owner, std::string_view name) : owner(owner), name(name) { }
virtual ~Controller() { }
void Clear();
virtual bool Attack(const Game& game, const Entity& danger, bool canCastWind) = 0;
virtual bool Defend(const Game& game, const Entity& opponent, bool shouldDefend) = 0;
virtual void Tick(const Game& game) = 0;
void MakeMove(std::ostream& out) const;
int GetTargetEntity() const { return targetEntity; }
Vector GetTargetPosition() const { return targetPosition; }
Spell GetTargetSpell() const { return targetSpell; }
protected:
void SetTarget(int entity, const Vector& pos, std::string_view info);
void SetSpell(Spell spell, int entity, const Vector& pos, std::string_view info);
bool HasTarget() const { return targetEntity != -1; }
static bool IsTargetedEntity(int entity, const Game& game);
const Entity& owner;
private:
const std::string name{};
Vector targetPosition{};
int targetEntity{ -1 };
Spell targetSpell{ Spell::None };
};
#pragma endregion ..\Codin\Controller.h
class AssassinController : public Controller
{
public:
AssassinController(const Entity& owner, bool closeToBase) : Controller(owner, "Assassin"), closeToBase(closeToBase) {}
virtual bool Attack(const Game& game, const Entity& danger, bool canCastWind) override;
virtual bool Defend(const Game& game, const Entity& opponent, bool shouldDefend) override;
virtual void Tick(const Game& game) override;
private:
Vector GetIdleTarget(const Game& game, bool moveToOpponentsBase) const;
int moveToOpponentsBaseForFrames = 0;
bool closeToBase = false;
};
#pragma endregion ..\Codin\AssassinController.h
// #include "Entity.h"
#pragma region ..\Codin\Entity.h
// #pragma once
// #include "Controller.h"
// #include "Vector.h"
#include <cstdint>
#include <memory>
struct EntityDescription;
enum class EntityType : int8_t
{
Monster,
MyHero,
OpponentsHero,
};
enum class ThreatFor : int8_t
{
None,
MyBase,
OpponentsBase,
};
class Entity
{
public:
Entity(const EntityDescription& entityDesc, int frame);
Entity(const Entity& entity);
void Actualize(const EntityDescription& entityDesc, int frame);
void SetController(std::unique_ptr<Controller> controller);
Controller* GetController() { return controllingBrain.get(); }
int GetId() const { return id; }
const Vector& GetPosition() const { return position; }
const Vector& GetVelocity() const { return velocity; }
Vector GetTargetPosition() const { return position + velocity; }
EntityType GetType() const { return type; }
ThreatFor GetThreatFor() const { return threatFor; }
int GetShieldLife() const { return shieldLife; }
int GetHealt() const { return health; }
bool IsControlled() const { return isControlled; }
bool IsNearBase() const { return isNearBase; }
int GetLastFrame() const { return lastFrame; }
void SetPosition(const Vector& pos) { position = pos; }
void SetVelocity(const Vector& vel) { velocity = vel; }
void SetNearBase(bool isNear) { isNearBase = isNear; }
Vector GetAwayDirection(const Entity& other) const;
private:
std::unique_ptr<Controller> controllingBrain{};
Vector position{};
Vector velocity{};
int id{};
int shieldLife{};
int health{};
int lastFrame{};
EntityType type{};
ThreatFor threatFor{};
bool isControlled{};
bool isNearBase{};
};
#pragma endregion ..\Codin\Entity.h
// #include "Game.h"
#pragma region ..\Codin\Game.h
// #pragma once
// #include "Vector.h"
#include <iosfwd>
#include <memory>
#include <unordered_map>
#include <vector>
class Entity;
struct EntityDescription;
struct StatsDescription;
enum class ControllerSetup : int8_t
{
Default,
Assasinate,
Protect,
Attack
};
class Game
{
public:
Game(const Vector& basePosition, int numHeroes)
: basePosition(basePosition), numHeroes(numHeroes)
{ }
Game(const Game&) = delete;
int GetMana() const { return mana; }
void Tick(const StatsDescription& myStats, const StatsDescription& opponentsStats, const std::vector<EntityDescription>& entitiesDesc);
void MakeMove(std::ostream& out) const;
const std::unordered_map<int, std::shared_ptr<Entity>>& GetAllEntities() const { return allEntities; }
const std::vector<std::shared_ptr<Entity>>& GetMyHeroes() const { return myHeroes; }
const Vector& GetBasePosition() const { return basePosition; }
Vector GetOpponentsBasePosition() const;
private:
void TickAttackAndDefend();
void ControllCreatedHero(Entity* hero);
void SwitchControllersToAttackOpponentsBase();
void SwitchControllersToAssassinateOpponentsBase();
void SwitchControllersToProtectMyBase();
bool ShouldAttack(const std::vector<Entity*> heroes) const;
bool IsOpponentNearMyBase() const;
std::vector<const Entity*> GetDangerousEnemies() const;
std::vector<const Entity*> GetDangerousOpponents() const;
std::vector<Entity*> GetHeroes();
std::unordered_map<int, std::shared_ptr<Entity>> allEntities;
std::vector<std::shared_ptr<Entity>> myHeroes;
Vector basePosition{};
int numHeroes{};
int frame{};
int health{};
int mana{};
ControllerSetup controllerSetup = ControllerSetup::Default;
};
#pragma endregion ..\Codin\Game.h
// #include "Rules.h"
#pragma region ..\Codin\Rules.h
// #pragma once
// #include "Vector.h"
struct Rules
{
static constexpr Vector mapSize{ 17630, 9000 };
static constexpr int gameLenght = 220;
static constexpr int baseViewRange = 6000;
static constexpr int heroViewRange = 2200;
static constexpr int heroMoveRange = 800;
static constexpr int heroAttackRange = 800;
static constexpr int heroDamage = 2;
static constexpr int monsterMoveRange = 400;
static constexpr int monsterBaseAttackRange = 5000;
static constexpr int monsterBaseDestroyRange = 300;
static constexpr int spellManaCost = 10;
static constexpr int spellWindPushRange = 2200;
static constexpr int spellWindRange = 1280;
static constexpr int spellShieldTime = 12;
static constexpr int spellShieldRange = 2200;
static constexpr int spellControlRange = 2200;
};
#pragma endregion ..\Codin\Rules.h
// #include "Utils.h"
#pragma region ..\Codin\Utils.h
// #pragma once
/// Mark that given parameter is not used at all in the function.
#define UNUSED(x) (void)(x)
/// Mark that given parameter is not used in given code path.
#define TOUCH(x) (void)(x)
// https://stackoverflow.com/questions/1082192/how-to-generate-random-variable-names-in-c-using-macros
// One level of macro indirection is required in order to resolve __COUNTER__,
// and get varname1 instead of varname__COUNTER__.
#define CONCAT(a, b) CONCAT_INNER(a, b)
#define CONCAT_INNER(a, b) a ## b
#define UNIQUE_NAME(base) CONCAT(base, __COUNTER__)
#pragma endregion ..\Codin\Utils.h
bool AssassinController::Attack(const Game& game, const Entity& danger, bool canCastWind)
{
UNUSED(game);
UNUSED(danger);
UNUSED(canCastWind);
return false;
}
bool AssassinController::Defend(const Game& game, const Entity& opponent, bool shouldDefend)
{
UNUSED(game);
UNUSED(opponent);
UNUSED(shouldDefend);
return false;
}
void AssassinController::Tick(const Game& game)
{
const bool moveToOpponentsBase = moveToOpponentsBaseForFrames > 0;
moveToOpponentsBaseForFrames = std::max(moveToOpponentsBaseForFrames - 1, 0);
const Vector idleTarget = GetIdleTarget(game, moveToOpponentsBase);
if (Distance2(owner.GetPosition(), game.GetOpponentsBasePosition()) < Pow2(Rules::baseViewRange + Rules::heroMoveRange))
{
// Try to push enemies into the base.
if (game.GetMana() >= Rules::spellManaCost * 3)
{
bool castWindOnMonsters = false;
int minDistanceToEdge = std::numeric_limits<int>::max();
for (const auto& ent : game.GetAllEntities())
{
const Entity* enemy = ent.second.get();
if (enemy->GetType() == EntityType::Monster
&& enemy->GetShieldLife() == 0
&& Distance2(enemy->GetPosition(), owner.GetPosition()) < Pow2(Rules::spellWindRange))
{
castWindOnMonsters = true;
minDistanceToEdge = std::min(minDistanceToEdge, std::min(enemy->GetPosition().y, Rules::mapSize.y - enemy->GetPosition().y));
}
}
if (castWindOnMonsters)
{
const Vector windTargetPoition = game.GetOpponentsBasePosition() + Vector{ 0, owner.GetPosition().y - minDistanceToEdge };
SetSpell(Spell::Wind, -1, windTargetPoition, "AC-windMonster");
moveToOpponentsBaseForFrames = 3;
return;
}
}
}
if (Distance2(owner.GetPosition(), idleTarget) < Pow2(Rules::heroMoveRange))
{
// Try to protect myself with shield.
if (game.GetMana() >= Rules::spellManaCost * 6)
{
if (owner.GetShieldLife() == 0)
{
SetSpell(Spell::Shield, owner.GetId(), {}, "AC-spellShieldHero");
return;
}
}
}
SetTarget(-1, idleTarget, "AC-idle");
}
Vector AssassinController::GetIdleTarget(const Game& game, bool moveToOpponentsBase) const
{
// Set minimal distance to the opponents base.
const int distToOpponentsBase2 = Distance2(owner.GetPosition(), game.GetOpponentsBasePosition());
if (moveToOpponentsBase
&& distToOpponentsBase2 > Pow2(Rules::heroMoveRange + Rules::spellWindPushRange))
{
return game.GetOpponentsBasePosition();
}
const Vector idleTarget = closeToBase
? Vector{ Rules::baseViewRange - Rules::spellWindPushRange - Rules::monsterMoveRange, Rules::spellWindRange * 7 / 10 }
: Vector{ Rules::baseViewRange - Rules::monsterMoveRange, Rules::spellWindRange };
if (game.GetOpponentsBasePosition() == Vector{})
return idleTarget;
else
return Rules::mapSize - idleTarget;
}
#pragma endregion ..\Codin\AssassinController.cpp
#pragma region ..\Codin\Controller.cpp
// #include "Controller.h"
// #include "Entity.h"
// #include "Game.h"
// #include "Utils.h"
#include <iostream>
#define LOG_TARGET 1
void Controller::Clear()
{
targetPosition = owner.GetPosition();
targetEntity = -1;
targetSpell = Spell::None;
}
void Controller::MakeMove(std::ostream& out) const
{
if (targetSpell != Spell::None)
{
out << "SPELL " << targetSpell;
if (targetSpell == Spell::Shield || targetSpell == Spell::Control)
out << ' ' << targetEntity;
if (targetSpell == Spell::Wind || targetSpell == Spell::Control)
out << ' ' << targetPosition;
}
else if (owner.GetPosition() != targetPosition)
out << "MOVE " << targetPosition;
else
out << "WAIT";
out << ' ' << name << owner.GetId() << std::endl;
}
void Controller::SetTarget(int entity, const Vector& pos, std::string_view info)
{
targetEntity = entity;
targetPosition = pos;
targetSpell = Spell::None;
#if LOG_TARGET
std::cerr << "H(" << owner.GetId() << ") Move -> T:" << entity << " P:" << pos << ' ' << info << std::endl;
#else
TOUCH(info);
#endif
}
void Controller::SetSpell(Spell spell, int entity, const Vector& pos, std::string_view info)
{
targetEntity = entity;
targetPosition = pos;
targetSpell = spell;
#if LOG_TARGET
std::cerr << "H(" << owner.GetId() << ") S(" << spell << ") ->" << " T:" << entity << " P:" << pos << ' ' << info << std::endl;
#else
TOUCH(info);
#endif
}
bool Controller::IsTargetedEntity(int entity, const Game& game)
{
for (auto hero : game.GetMyHeroes())
{
if (hero->GetController()->targetEntity == entity)
return true;
}
return false;
}
std::ostream& operator<<(std::ostream& out, Spell spell)
{
std::string_view spellName{};
switch (spell)
{
case Spell::Wind: spellName = "WIND"; break;
case Spell::Shield: spellName = "SHIELD"; break;
case Spell::Control: spellName = "CONTROL"; break;
}
return out << spellName;
}
#pragma endregion ..\Codin\Controller.cpp
#pragma region ..\Codin\DefenderController.cpp
// #include "DefenderController.h"
#pragma region ..\Codin\DefenderController.h
// #pragma once
// #include "PaladinController.h"
#pragma region ..\Codin\PaladinController.h
// #pragma once
// #include "Controller.h"
// #include "Rules.h"
class PaladinController : public Controller
{
public:
PaladinController(const Entity& owner, std::string_view name = "Paladin") : Controller(owner, name) {}
virtual bool Attack(const Game& game, const Entity& danger, bool canCastWind) override;
virtual bool Defend(const Game& game, const Entity& opponent, bool shouldDefend) override;
virtual void Tick(const Game& game) override;
private:
bool TryCastSpellOnNearestOpponent(const Game& game);
bool TryGainMaxWildMana(const Game& game);
Vector GetIdleTarget(const Game& game) const;
bool IsAnyOpponentsHeroInMyBase(const Game& game) const;
bool wantsMoveCloserToBase = false;
static constexpr int minDistToBase = Rules::baseViewRange + Rules::heroViewRange * 1 / 4; // 1 / 2;
static constexpr int maxDistToBase = Rules::baseViewRange + Rules::heroViewRange * 2 / 2; // 7 / 10; // 7/10 ~= Sqrt(2) / 2 ~= 0.707107
static constexpr int minDistToEdge = Rules::heroViewRange * 7 / 10;
static constexpr int minDistToHero = 2 * Rules::heroViewRange * 7 / 10;
static constexpr int sensDistToEnemy = Rules::heroViewRange * 3 / 2;
static constexpr int optDistToEnemy = Rules::heroAttackRange * 1 / 2;
};
#pragma endregion ..\Codin\PaladinController.h
class DefenderController : public PaladinController
{
public:
DefenderController(const Entity& owner) : PaladinController(owner, "Defender") {}
virtual void Tick(const Game& game) override;
private:
Vector GetIdleTarget(const Game& game) const;
static constexpr Vector defenderPosition{ Rules::spellWindRange * 2, Rules::spellWindRange * 2 };
};
#pragma endregion ..\Codin\DefenderController.h
// #include "Game.h"
void DefenderController::Tick(const Game& game)
{
// We have already attacked dangerous enemy. No other move is needed.
if (HasTarget())
return;
// No enemies to attack,
SetTarget(-1, GetIdleTarget(game), "DC-idle");
}
Vector DefenderController::GetIdleTarget(const Game& game) const
{
Vector idleTarget = game.GetBasePosition();
if (idleTarget == Vector{})
idleTarget = defenderPosition;
else
idleTarget -= defenderPosition;
return idleTarget;
}
#pragma endregion ..\Codin\DefenderController.cpp
#pragma region ..\Codin\Entity.cpp
// #include "Entity.h"
// #include "EntityDescription.h"
#pragma region ..\Codin\EntityDescription.h
// #pragma once
// #include "Vector.h"
#include <iosfwd>
struct EntityDescription
{
int id; // Unique identifier
int type; // 0=monster, 1=your hero, 2=opponent hero
Vector pos; // Position of this entity
int shieldLife; // Ignore for this league; Count down until shield spell fades
int isControlled; // Ignore for this league; Equals 1 when this entity is under a control spell
int health; // Remaining health of this monster
Vector vel; // Trajectory of this monster
int nearBase; // 0=monster with no target yet, 1=monster targeting a base
int threatFor; // Given this monster's trajectory, is it a threat to 1=your base, 2=your opponent's base, 0=neither
};
std::istream& operator>>(std::istream& in, EntityDescription& entDesc);
std::ostream& operator<<(std::ostream& out, const EntityDescription& entDesc);
#pragma endregion ..\Codin\EntityDescription.h
Entity::Entity(const EntityDescription& entityDesc, int frame)
{
Actualize(entityDesc, frame);
}
Entity::Entity(const Entity& entity)
: controllingBrain{} //< Copy resets brain.
, position{ entity.position }
, velocity{ entity.velocity }
, id{ entity.id }
, shieldLife{ entity.shieldLife }
, health{ entity.health }
, lastFrame{ entity.lastFrame }
, type{ entity.type }
, threatFor{ entity.threatFor }
, isControlled{ entity.isControlled }
, isNearBase{ entity.isNearBase }
{}
void Entity::Actualize(const EntityDescription& entityDesc, int frame)
{
position = entityDesc.pos;
velocity = entityDesc.vel;
id = entityDesc.id;
shieldLife = entityDesc.shieldLife;
health = entityDesc.health;
type = static_cast<EntityType>(entityDesc.type);
threatFor = entityDesc.threatFor >= 0 ? static_cast<ThreatFor>(entityDesc.threatFor) : ThreatFor::None;
isControlled = entityDesc.isControlled != 0;
isNearBase = entityDesc.nearBase == 1;
lastFrame = frame;
}
void Entity::SetController(std::unique_ptr<Controller> controller)
{
controllingBrain = std::move(controller);
}
Vector Entity::GetAwayDirection(const Entity& other) const
{
if (GetPosition() != other.GetPosition())
return GetPosition() - other.GetPosition();
Vector awayDirection{
(id < other.id) ? -1 : 1,
(id % 2 < other.id % 2) ? -1 : 1,
};
return awayDirection;
}
#pragma endregion ..\Codin\Entity.cpp
#pragma region ..\Codin\EntityDescription.cpp
// #include "EntityDescription.h"
#include <iostream>
std::istream& operator>>(std::istream& in, EntityDescription& entDesc)
{
in >> entDesc.id >> entDesc.type >> entDesc.pos >> entDesc.shieldLife >> entDesc.isControlled >> entDesc.health >> entDesc.vel >> entDesc.nearBase >> entDesc.threatFor;
return in;
}
std::ostream& operator<<(std::ostream& out, const EntityDescription& entDesc)
{
out << entDesc.id << ' ' << entDesc.type << ' ' << entDesc.pos << ' ' << entDesc.shieldLife << ' ' << entDesc.isControlled << ' ' << entDesc.health << ' ' << entDesc.vel << ' ' << entDesc.nearBase << ' ' << entDesc.threatFor;
return out;
}
#pragma endregion ..\Codin\EntityDescription.cpp
#pragma region ..\Codin\Game.cpp
// #include "Game.h"
// #include "AssassinController.h"
// #include "DefenderController.h"
// #include "Entity.h"
// #include "EntityDescription.h"
// #include "PaladinController.h"
// #include "PeasantController.h"
#pragma region ..\Codin\PeasantController.h
// #pragma once
// #include "Controller.h"
class PeasantController : public Controller
{
public:
PeasantController(const Entity& owner) : Controller(owner, "Peasant") {}
virtual bool Attack(const Game& game, const Entity& danger, bool canCastWind) override;
virtual bool Defend(const Game& game, const Entity& opponent, bool shouldDefend) override;
virtual void Tick(const Game& game) override;
};
#pragma endregion ..\Codin\PeasantController.h
// #include "Rules.h"
// #include "RogueController.h"
#pragma region ..\Codin\RogueController.h
// #pragma once
// #include "Controller.h"
// #include "Rules.h"
class RogueController : public Controller
{
public:
RogueController(const Entity& owner) : Controller(owner, "Rogue") {}
virtual bool Attack(const Game& game, const Entity& danger, bool canCastWind) override;
virtual bool Defend(const Game& game, const Entity& opponent, bool shouldDefend) override;
virtual void Tick(const Game& game) override;
private:
bool TryCastSpells(const Game& game);
Vector GetIdleTarget(const Game& game, bool moveToOpponentsBase) const;
Vector GetWindDirection(const Game& game) const;
bool moveRight = false;
int moveToOpponentsBaseForFrames = 0;
static constexpr int optDistToBase = Rules::monsterBaseAttackRange - Rules::spellWindPushRange;
static constexpr int maxDistToBase = optDistToBase + Rules::spellWindPushRange;// Rules::mapSize.y;
static constexpr int minDistToEdge = Rules::spellWindRange;
};
#pragma endregion ..\Codin\RogueController.h
// #include "Simulate.h"
#pragma region ..\Codin\Simulate.h
// #pragma once
class Entity;
class Game;
struct Vector;
#include <vector>
class Simulate
{
public:
static Vector GetNearestBasePosition(const Entity& entity);
static void Update(Entity& entity);
static Vector PositionAfterFrames(const Entity& entity, int frames);
static int EnemyFramesToAttackBase(const Entity& entity);
static int HeroFramesToAttackEnemy(const Entity& hero, const Entity& enemy);
static int HeroFramesToCastSpell(const Entity& hero, const Entity& enemy, int spellRange);
static int FramesToKill(int healt);
// Find the attack position damaging the most enemies at once or closest to the preferred position in attack and move range.
static Vector GetBestAttackPosition(const Entity& hero, const Entity& danger, const Vector& preferedPosition, const Game& game);
// Find the attack position closest to the preferred position in attack and move range.
static Vector GetPreferedAttackPosition(const Entity& hero, const Entity& danger, const Vector& preferedPosition);
static Vector GetEnemiesCenter(const std::vector<const Entity*>& enemies);
};
#pragma endregion ..\Codin\Simulate.h
// #include "StatsDescription.h"
#pragma region ..\Codin\StatsDescription.h
// #pragma once
#include <iosfwd>
struct StatsDescription
{
int health; // Your base health
int mana; // Ignore in the first league; Spend ten mana to cast a spell
};
std::istream& operator>>(std::istream& in, StatsDescription& statsDesc);
#pragma endregion ..\Codin\StatsDescription.h
// #include "Utils.h"
#include <algorithm>
#include <cassert>
#include <iostream>
void Game::Tick(const StatsDescription& myStats, const StatsDescription& opponentsStats, const std::vector<EntityDescription>& entitiesDesc)
{
UNUSED(opponentsStats);
++frame;
health = myStats.health;
mana = myStats.mana;
// Actualize all entities.
for (const auto& entDesc : entitiesDesc)
{
auto entIt = allEntities.find(entDesc.id);
if (entIt != allEntities.end())
entIt->second->Actualize(entDesc, frame);
else
{
entIt = allEntities.insert(std::make_pair(entDesc.id, std::make_shared<Entity>(entDesc, frame))).first;
if (entIt->second->GetType() == EntityType::MyHero)
{
ControllCreatedHero(entIt->second.get());
myHeroes.push_back(entIt->second);
}
}
}
// Setup controllers.
if (frame >= Rules::gameLenght * 12 / 16)
{
if (controllerSetup != ControllerSetup::Attack)
SwitchControllersToAttackOpponentsBase();
}
else if (frame >= Rules::gameLenght * 10 / 16)
{
if (controllerSetup != ControllerSetup::Protect)
SwitchControllersToProtectMyBase();
}
else if (frame >= Rules::gameLenght * 8 / 16)
{
if (controllerSetup != ControllerSetup::Assasinate)
SwitchControllersToAssassinateOpponentsBase();
}
else
{
if (controllerSetup == ControllerSetup::Default && IsOpponentNearMyBase())
SwitchControllersToProtectMyBase();
}
// Remove no longer valid entities.
for (auto it = allEntities.begin(); it != allEntities.end(); /* inside the loop */)
{
if (it->second->GetLastFrame() != frame)
{
assert(it->second->GetType() != EntityType::MyHero);
it = allEntities.erase(it);
}
else
++it;
}
// Prepare all heroes for new tick.
for (const auto& hero : myHeroes)
hero->GetController()->Clear();
// First take care of dangerous enemies and opponents.
TickAttackAndDefend();
// Tick all heroes.
for (const auto& hero : myHeroes)
hero->GetController()->Tick(*this);
}
void Game::TickAttackAndDefend()
{
std::vector<const Entity*> dangerousEnemies = GetDangerousEnemies();
std::vector<const Entity*> dangerousOpponents = GetDangerousOpponents();
std::vector<Entity*> heroes = GetHeroes();
// Attack
bool castedWind = false;
while (!dangerousEnemies.empty())
{
const Entity* danger = dangerousEnemies.front();
if (heroes.empty())
break;
std::sort(heroes.begin(), heroes.end(), [danger](const Entity* a, const Entity* b)
{
return Distance2(a->GetPosition(), danger->GetPosition()) < Distance2(b->GetPosition(), danger->GetPosition());
});
for (auto it = heroes.begin(); it != heroes.end(); /* in loop */)
{
if ((*it)->GetController()->Attack(*this, *danger, !castedWind))
{
const int dangerFrameToAttackBase = Simulate::EnemyFramesToAttackBase(*danger);
const int heroFrameToAttackDanger = Simulate::HeroFramesToAttackEnemy(*(*it), *danger);
const int heroFrameToKill = Simulate::FramesToKill(danger->GetHealt());
castedWind = (*it)->GetController()->GetTargetSpell() == Spell::Wind;
it = heroes.erase(it);
// If one hero can deal with it attack next danger.
if (danger->GetShieldLife() == 0
|| castedWind
|| heroFrameToKill + heroFrameToAttackDanger <= dangerFrameToAttackBase
|| heroes.size() <= 1)
{
break;
}
}
else
++it;
}
dangerousEnemies.erase(std::remove(dangerousEnemies.begin(), dangerousEnemies.end(), danger), dangerousEnemies.end());
}
// Defend
bool anyOpponentDefneded = false;
for (const Entity* opponent : dangerousOpponents)
{
if (heroes.empty())
break;
std::sort(heroes.begin(), heroes.end(), [opponent](const Entity* a, const Entity* b)
{
return Distance2(a->GetPosition(), opponent->GetPosition()) < Distance2(b->GetPosition(), opponent->GetPosition());
});
for (auto it = heroes.begin(); it != heroes.end(); /* in loop */)
{
if ((*it)->GetController()->Defend(*this, *opponent, !anyOpponentDefneded))
{
anyOpponentDefneded = true;
it = heroes.erase(it);
break;
}
else
++it;
}
}
}
bool Game::ShouldAttack(const std::vector<Entity*> heroes) const
{
// For the first quarter of the game, use only one hero to protect the base.
if (frame < Rules::gameLenght / 4 && heroes.size() <= 2)
return false;
// Use at most two heroes to protect the base.
if (heroes.size() <= 1)
return false;
return true;
}
void Game::MakeMove(std::ostream& out) const
{
for (const auto& hero : myHeroes)
hero->GetController()->MakeMove(out);
}
Vector Game::GetOpponentsBasePosition() const
{
return basePosition == Vector{} ? Rules::mapSize : Vector{};
}
void Game::ControllCreatedHero(Entity* hero)
{
std::unique_ptr<Controller> controller{};
if (myHeroes.size() < 0)
controller = std::make_unique<RogueController>(*hero);
else if (myHeroes.size() < 3)
controller = std::make_unique<PaladinController>(*hero);
else
controller = std::make_unique<DefenderController>(*hero);
hero->SetController(std::move(controller));
}
void Game::SwitchControllersToAttackOpponentsBase()
{
controllerSetup = ControllerSetup::Attack;
std::vector<Entity*> heroes = GetHeroes();
std::sort(heroes.begin(), heroes.end(), [this](const Entity* a, const Entity* b)
{
const int aDist2 = Distance2(a->GetPosition(), GetBasePosition());
const int bDist2 = Distance2(b->GetPosition(), GetBasePosition());
return aDist2 < bDist2;
});
for (size_t i = 0; i < heroes.size(); ++i)
{
if (i < 1)
heroes[i]->SetController(std::make_unique<DefenderController>(*heroes[i]));
else if (i < 2)
heroes[i]->SetController(std::make_unique<PaladinController>(*heroes[i]));
else
heroes[i]->SetController(std::make_unique<RogueController>(*heroes[i]));
}
}
void Game::SwitchControllersToAssassinateOpponentsBase()
{
controllerSetup = ControllerSetup::Assasinate;
std::vector<Entity*> heroes = GetHeroes();
std::sort(heroes.begin(), heroes.end(), [this](const Entity* a, const Entity* b)
{
const int aDist2 = Distance2(a->GetPosition(), GetBasePosition());
const int bDist2 = Distance2(b->GetPosition(), GetBasePosition());
return aDist2 < bDist2;
});
for (size_t i = 0; i < heroes.size(); ++i)
{
if (i < 1)
heroes[i]->SetController(std::make_unique<DefenderController>(*heroes[i]));
else
heroes[i]->SetController(std::make_unique<AssassinController>(*heroes[i], i >= 2));
}
}
void Game::SwitchControllersToProtectMyBase()
{
controllerSetup = ControllerSetup::Protect;
std::vector<Entity*> heroes = GetHeroes();
std::sort(heroes.begin(), heroes.end(), [this](const Entity* a, const Entity* b)
{
const int aDist2 = Distance2(a->GetPosition(), GetBasePosition());
const int bDist2 = Distance2(b->GetPosition(), GetBasePosition());
return aDist2 < bDist2;