-
Notifications
You must be signed in to change notification settings - Fork 26
/
gamestate.cpp
2341 lines (2009 loc) · 70.7 KB
/
gamestate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "gamestate.h"
#include "gamemap.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include <boost/xpressive/xpressive_dynamic.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include "headers.h"
#include "huntercoin.h"
using namespace Game;
json_spirit::Value ValueFromAmount(int64 amount);
/* Parameters that determine when a poison-disaster will happen. The
probability is 1/x at each block between min and max time. */
static const unsigned PDISASTER_MIN_TIME = 1440;
static const unsigned PDISASTER_MAX_TIME = 12 * 1440;
static const unsigned PDISASTER_PROBABILITY = 10000;
/* Parameters about how long a poisoned player may still live. */
static const unsigned POISON_MIN_LIFE = 1;
static const unsigned POISON_MAX_LIFE = 50;
/* Parameters for dynamic banks after the life-steal fork. */
static const unsigned DYNBANKS_NUM_BANKS = 75;
static const unsigned DYNBANKS_MIN_LIFE = 25;
static const unsigned DYNBANKS_MAX_LIFE = 100;
namespace Game
{
inline bool IsOriginalSpawnArea(const Coord &c)
{
return IsOriginalSpawnArea(c.x, c.y);
}
inline bool IsWalkable(const Coord &c)
{
return IsWalkable(c.x, c.y);
}
/**
* Keep a set of walkable tiles. This is used for random selection of
* one of them for spawning / dynamic bank purposes. Note that it is
* important how they are ordered (according to Coord::operator<) in order
* to reach consensus on the game state.
*
* This is filled in from IsWalkable() whenever it is empty (on startup). It
* does not ever change.
*/
static std::vector<Coord> walkableTiles;
// for FORK_TIMESAVE -- 2 more sets of walkable tiles
static std::vector<Coord> walkableTiles_ts_players;
static std::vector<Coord> walkableTiles_ts_banks;
/* Calculate carrying capacity. This is where it is basically defined.
It depends on the block height (taking forks changing it into account)
and possibly properties of the player. Returns -1 if the capacity
is unlimited. */
static int64_t
GetCarryingCapacity (int nHeight, bool isGeneral, bool isCrownHolder)
{
if (!ForkInEffect (FORK_CARRYINGCAP, nHeight) || isCrownHolder)
return -1;
if (ForkInEffect (FORK_LIFESTEAL, nHeight))
return 100 * COIN;
if (ForkInEffect (FORK_LESSHEARTS, nHeight))
return 2000 * COIN;
return (isGeneral ? 50 : 25) * COIN;
}
/* Return the minimum necessary amount of locked coins. This replaces the
old NAME_COIN_AMOUNT constant and makes it more dynamic, so that we can
change it with hard forks. */
static int64_t
GetNameCoinAmount (unsigned nHeight)
{
if (ForkInEffect (FORK_TIMESAVE, nHeight))
return 100 * COIN;
if (ForkInEffect (FORK_LESSHEARTS, nHeight))
return 200 * COIN;
if (ForkInEffect (FORK_POISON, nHeight))
return 10 * COIN;
return COIN;
}
/* Get the destruct radius a hunter has at a certain block height. This
may depend on whether or not it is a general. */
static int
GetDestructRadius (int nHeight, bool isGeneral)
{
if (ForkInEffect (FORK_LESSHEARTS, nHeight))
return 1;
return isGeneral ? 2 : 1;
}
/* Get maximum allowed stay on a bank. */
static int
MaxStayOnBank (int nHeight)
{
if (ForkInEffect (FORK_LIFESTEAL, nHeight))
return 2;
/* Between those two forks, spawn death was disabled. */
if (ForkInEffect (FORK_CARRYINGCAP, nHeight)
&& !ForkInEffect (FORK_LESSHEARTS, nHeight))
return -1;
/* Return original value. */
return 30;
}
/* Check whether or not a heart should be dropped at the current height. */
static bool
DropHeart (int nHeight)
{
if (ForkInEffect (FORK_LIFESTEAL, nHeight))
return false;
const int heartEvery = (ForkInEffect (FORK_LESSHEARTS, nHeight) ? 500 : 10);
return nHeight % heartEvery == 0;
}
/* Ensure that walkableTiles is filled. */
static void
FillWalkableTiles ()
{
// for FORK_TIMESAVE -- less possible player and bank spawn tiles
if (walkableTiles_ts_players.empty ())
{
for (int x = 0; x < MAP_WIDTH; ++x)
for (int y = 0; y < MAP_HEIGHT; ++y)
if (IsWalkable (x, y))
{
if ( ! (SpawnMap[y][x] & SPAWNMAPFLAG_PLAYER) ) // note: player spawn tiles and bank spawn tiles are separated
continue;
walkableTiles_ts_players.push_back (Coord (x, y));
}
/* Do not forget to sort in the order defined by operator<! */
std::sort (walkableTiles_ts_players.begin (), walkableTiles_ts_players.end ());
assert (!walkableTiles_ts_players.empty ());
}
if (walkableTiles_ts_banks.empty ())
{
for (int x = 0; x < MAP_WIDTH; ++x)
for (int y = 0; y < MAP_HEIGHT; ++y)
if (IsWalkable (x, y))
{
if ( ! (SpawnMap[y][x] & SPAWNMAPFLAG_BANK) )
continue;
walkableTiles_ts_banks.push_back (Coord (x, y));
}
/* Do not forget to sort in the order defined by operator<! */
std::sort (walkableTiles_ts_banks.begin (), walkableTiles_ts_banks.end ());
assert (!walkableTiles_ts_banks.empty ());
}
if (!walkableTiles.empty ())
return;
for (int x = 0; x < MAP_WIDTH; ++x)
for (int y = 0; y < MAP_HEIGHT; ++y)
if (IsWalkable (x, y))
{
walkableTiles.push_back (Coord (x, y));
}
/* Do not forget to sort in the order defined by operator<! */
std::sort (walkableTiles.begin (), walkableTiles.end ());
assert (!walkableTiles.empty ());
}
} // namespace Game
// Random generator seeded with block hash
class Game::RandomGenerator
{
public:
RandomGenerator(uint256 hashBlock)
: state0(SerializeHash(hashBlock, SER_GETHASH, 0))
{
state = state0;
}
int GetIntRnd(int modulo)
{
// Advance generator state, if most bits of the current state were used
if (state < MIN_STATE)
{
state0.setuint256(SerializeHash(state0, SER_GETHASH, 0));
state = state0;
}
return state.DivideGetRemainder(modulo).getint();
}
/* Get an integer number in [a, b]. */
int GetIntRnd (int a, int b)
{
assert (a <= b);
const int mod = (b - a + 1);
const int res = GetIntRnd (mod) + a;
assert (res >= a && res <= b);
return res;
}
private:
CBigNum state, state0;
static const CBigNum MIN_STATE;
};
const CBigNum RandomGenerator::MIN_STATE = CBigNum().SetCompact(0x097FFFFFu);
/* ************************************************************************** */
/* KilledByInfo. */
bool
KilledByInfo::HasDeathTax () const
{
return reason != KILLED_SPAWN;
}
bool
KilledByInfo::DropCoins (unsigned nHeight, const PlayerState& victim) const
{
if (!ForkInEffect (FORK_LESSHEARTS, nHeight))
return true;
/* If the player is poisoned, no dropping of coins. Note that we have
to allow ==0 here (despite what gamestate.h says), since that is the
case precisely when we are killing the player right now due to poison. */
if (victim.remainingLife >= 0)
return false;
assert (victim.remainingLife == -1);
return true;
}
bool
KilledByInfo::CanRefund (unsigned nHeight, const PlayerState& victim) const
{
if (!ForkInEffect (FORK_LESSHEARTS, nHeight))
return false;
switch (reason)
{
case KILLED_SPAWN:
/* Before life-steal fork, poisoned players were not refunded. */
if (!ForkInEffect (FORK_LIFESTEAL, nHeight) && victim.remainingLife >= 0)
return false;
return true;
case KILLED_POISON:
return ForkInEffect (FORK_LIFESTEAL, nHeight);
default:
return false;
}
assert (false);
}
/* ************************************************************************** */
/* Move. */
static bool
ExtractField (json_spirit::Object& obj, const std::string field,
json_spirit::Value& v)
{
for (std::vector<json_spirit::Pair>::iterator i = obj.begin(); i != obj.end(); ++i)
{
if (i->name_ == field)
{
v = i->value_;
obj.erase(i);
return true;
}
}
return false;
}
bool Move::IsValid(const GameState &state) const
{
PlayerStateMap::const_iterator mi = state.players.find (player);
/* Before the life-steal fork, check that the move does not contain
destruct and waypoints together. This needs the height for its
decision, thus it is not done in Parse (as before). */
/* FIXME: Remove check once the fork is passed. */
if (!ForkInEffect (FORK_LIFESTEAL, state.nHeight + 1))
for (std::map<int, WaypointVector>::const_iterator i = waypoints.begin ();
i != waypoints.end (); ++i)
if (destruct.count (i->first) > 0)
return error ("%s: destruct and waypoints together", __func__);
int64_t oldLocked;
if (mi == state.players.end ())
{
if (!IsSpawn ())
return false;
oldLocked = 0;
}
else
{
if (IsSpawn ())
return false;
oldLocked = mi->second.lockedCoins;
}
assert (oldLocked >= 0 && newLocked >= 0);
const int64_t gameFee = newLocked - oldLocked;
const int64_t required = MinimumGameFee (state.nHeight + 1);
assert (required >= 0);
if (gameFee < required)
return error ("%s: too little game fee attached, got %lld, required %lld",
__func__, gameFee, required);
return true;
}
bool ParseWaypoints(json_spirit::Object &obj, std::vector<Coord> &result, bool &bWaypoints)
{
using namespace json_spirit;
bWaypoints = false;
result.clear();
Value v;
if (!ExtractField(obj, "wp", v))
return true;
if (v.type() != array_type)
return false;
Array arr = v.get_array();
if (arr.size() % 2)
return false;
int n = arr.size() / 2;
if (n > MAX_WAYPOINTS)
return false;
result.resize(n);
for (int i = 0; i < n; i++)
{
if (arr[2 * i].type() != int_type || arr[2 * i + 1].type() != int_type)
return false;
int x = arr[2 * i].get_int();
int y = arr[2 * i + 1].get_int();
if (!IsInsideMap(x, y))
return false;
// Waypoints are reversed for easier deletion of current waypoint from the end of the vector
result[n - 1 - i] = Coord(x, y);
if (i && result[n - 1 - i] == result[n - i])
return false; // Forbid duplicates
}
bWaypoints = true;
return true;
}
bool ParseDestruct(json_spirit::Object &obj, bool &result)
{
using namespace json_spirit;
result = false;
Value v;
if (!ExtractField(obj, "destruct", v))
return true;
if (v.type() != bool_type)
return false;
result = v.get_bool();
return true;
}
bool Move::Parse(const PlayerID &player, const std::string &json)
{
using namespace json_spirit;
if (!IsValidPlayerName(player))
return false;
Value v;
if (!read_string(json, v) || v.type() != obj_type)
return false;
Object obj = v.get_obj();
if (ExtractField(obj, "msg", v))
{
if (v.type() != str_type)
return false;
message = v.get_str();
}
if (ExtractField(obj, "address", v))
{
if (v.type() != str_type)
return false;
const std::string &addr = v.get_str();
if (!addr.empty() && !IsValidBitcoinAddress(addr))
return false;
address = addr;
}
if (ExtractField(obj, "addressLock", v))
{
if (v.type() != str_type)
return false;
const std::string &addr = v.get_str();
if (!addr.empty() && !IsValidBitcoinAddress(addr))
return false;
addressLock = addr;
}
if (ExtractField(obj, "color", v))
{
if (v.type() != int_type)
return false;
color = v.get_int();
if (color >= NUM_TEAM_COLORS)
return false;
if (!obj.empty()) // Extra fields are not allowed in JSON string
return false;
this->player = player;
return true;
}
std::set<int> character_indices;
for (std::vector<json_spirit::Pair>::iterator it = obj.begin(); it != obj.end(); ++it)
{
int i = atoi(it->name_);
if (i < 0 || strprintf("%d", i) != it->name_)
return false; // Number formatting must be strict
if (character_indices.count(i))
return false; // Cannot contain duplicate character indices
character_indices.insert(i);
v = it->value_;
if (v.type() != obj_type)
return false;
Object subobj = v.get_obj();
bool bWaypoints = false;
std::vector<Coord> wp;
if (!ParseWaypoints(subobj, wp, bWaypoints))
return false;
bool bDestruct;
if (!ParseDestruct(subobj, bDestruct))
return false;
if (bDestruct)
destruct.insert(i);
if (bWaypoints)
waypoints.insert(std::make_pair(i, wp));
if (!subobj.empty()) // Extra fields are not allowed in JSON string
return false;
}
this->player = player;
return true;
}
void Move::ApplyCommon(GameState &state) const
{
std::map<PlayerID, PlayerState>::iterator mi = state.players.find(player);
if (mi == state.players.end())
{
if (message)
{
PlayerState &pl = state.dead_players_chat[player];
pl.message = *message;
pl.message_block = state.nHeight;
}
return;
}
PlayerState &pl = mi->second;
if (message)
{
pl.message = *message;
pl.message_block = state.nHeight;
}
if (address)
pl.address = *address;
if (addressLock)
pl.addressLock = *addressLock;
}
std::string Move::AddressOperationPermission(const GameState &state) const
{
if (!address && !addressLock)
return std::string(); // No address operation requested - allow
std::map<PlayerID, PlayerState>::const_iterator mi = state.players.find(player);
if (mi == state.players.end())
return std::string(); // Spawn move - allow any address operation
return mi->second.addressLock;
}
void
Move::ApplySpawn (GameState &state, RandomGenerator &rnd) const
{
assert (state.players.count (player) == 0);
PlayerState pl;
assert (pl.next_character_index == 0);
pl.color = color;
/* This is a fresh player and name. Set its value to the height's
name coin amount and put the remainder in the game fee. This prevents
people from "overpaying" on purpose in order to get beefed-up players.
This rule, however, is only active after the life-steal fork. Before
that, overpaying did, indeed, allow to set the hunter value
arbitrarily high. */
if (ForkInEffect (FORK_LIFESTEAL, state.nHeight))
{
const int64_t coinAmount = GetNameCoinAmount (state.nHeight);
assert (pl.lockedCoins == 0 && pl.value == -1);
assert (newLocked >= coinAmount);
pl.value = coinAmount;
pl.lockedCoins = newLocked;
state.gameFund += newLocked - coinAmount;
}
else
{
pl.value = newLocked;
pl.lockedCoins = newLocked;
}
const unsigned limit = state.GetNumInitialCharacters ();
for (unsigned i = 0; i < limit; i++)
pl.SpawnCharacter (state.nHeight, rnd);
state.players.insert (std::make_pair (player, pl));
}
void Move::ApplyWaypoints(GameState &state) const
{
std::map<PlayerID, PlayerState>::iterator pl;
pl = state.players.find (player);
if (pl == state.players.end ())
return;
BOOST_FOREACH(const PAIRTYPE(int, std::vector<Coord>) &p, waypoints)
{
std::map<int, CharacterState>::iterator mi;
mi = pl->second.characters.find(p.first);
if (mi == pl->second.characters.end())
continue;
CharacterState &ch = mi->second;
const std::vector<Coord> &wp = p.second;
if (ch.waypoints.empty() || wp.empty() || ch.waypoints.back() != wp.back())
ch.from = ch.coord;
ch.waypoints = wp;
}
}
int64_t
Move::MinimumGameFee (unsigned nHeight) const
{
if (IsSpawn ())
{
const int64_t coinAmount = GetNameCoinAmount (nHeight);
// fee for new hunter is 1 HUC
if (ForkInEffect (FORK_TIMESAVE, nHeight))
return coinAmount + COIN;
if (ForkInEffect (FORK_LIFESTEAL, nHeight))
return coinAmount + 5 * COIN;
return coinAmount;
}
// destruct fee is 1 HUC
if (ForkInEffect (FORK_TIMESAVE, nHeight))
return COIN * destruct.size ();
if (ForkInEffect (FORK_LIFESTEAL, nHeight))
return 20 * COIN * destruct.size ();
return 0;
}
std::string CharacterID::ToString() const
{
if (!index)
return player;
return player + strprintf(".%d", int(index));
}
/* ************************************************************************** */
/* AttackableCharacter and CharactersOnTiles. */
void
AttackableCharacter::AttackBy (const CharacterID& attackChid,
const PlayerState& pl)
{
/* Do not attack same colour. */
if (color == pl.color)
return;
assert (attackers.count (attackChid) == 0);
attackers.insert (attackChid);
}
void
AttackableCharacter::AttackSelf (const GameState& state)
{
if (!ForkInEffect (FORK_LIFESTEAL, state.nHeight))
{
assert (attackers.count (chid) == 0);
attackers.insert (chid);
}
}
void
CharactersOnTiles::EnsureIsBuilt (const GameState& state)
{
if (built)
return;
assert (tiles.empty ());
BOOST_FOREACH (const PAIRTYPE(PlayerID, PlayerState)& p, state.players)
BOOST_FOREACH (const PAIRTYPE(int, CharacterState)& pc, p.second.characters)
{
// newly spawned hunters not attackable
if (ForkInEffect (FORK_TIMESAVE, state.nHeight))
if (CharacterIsProtected(pc.second.stay_in_spawn_area))
{
// printf("protection: character at x=%d y=%d is protected\n", pc.second.coord.x, pc.second.coord.y);
continue;
}
AttackableCharacter a;
a.chid = CharacterID (p.first, pc.first);
a.color = p.second.color;
a.drawnLife = 0;
tiles.insert (std::make_pair (pc.second.coord, a));
}
built = true;
}
void
CharactersOnTiles::ApplyAttacks (const GameState& state,
const std::vector<Move>& moves)
{
BOOST_FOREACH(const Move& m, moves)
{
if (m.destruct.empty ())
continue;
const PlayerStateMap::const_iterator miPl = state.players.find (m.player);
assert (miPl != state.players.end ());
const PlayerState& pl = miPl->second;
BOOST_FOREACH(int i, m.destruct)
{
const std::map<int, CharacterState>::const_iterator miCh
= pl.characters.find (i);
if (miCh == pl.characters.end ())
continue;
const CharacterID chid(m.player, i);
if (state.crownHolder == chid)
continue;
const CharacterState& ch = miCh->second;
// hunters in spectator mode can't attack
if ((ForkInEffect (FORK_TIMESAVE, state.nHeight)) &&
(CharacterInSpectatorMode(ch.stay_in_spawn_area)))
{
// printf("protection: character at x=%d y=%d can't attack\n", ch.coord.x, ch.coord.y);
continue;
}
EnsureIsBuilt (state);
const int radius = GetDestructRadius (state.nHeight, i == 0);
const Coord& c = ch.coord;
for (int y = c.y - radius; y <= c.y + radius; y++)
for (int x = c.x - radius; x <= c.x + radius; x++)
{
const std::pair<Map::iterator, Map::iterator> iters
= tiles.equal_range (Coord (x, y));
for (Map::iterator it = iters.first; it != iters.second; ++it)
{
AttackableCharacter& a = it->second;
if (a.chid == chid)
a.AttackSelf (state);
else
a.AttackBy (chid, pl);
}
}
}
}
}
void
CharactersOnTiles::DrawLife (GameState& state, StepResult& result)
{
if (!built)
return;
/* Find damage amount if we have life steal in effect. */
const bool lifeSteal = ForkInEffect (FORK_LIFESTEAL, state.nHeight);
const int64_t damage = GetNameCoinAmount (state.nHeight);
BOOST_FOREACH (PAIRTYPE(const Coord, AttackableCharacter)& tile, tiles)
{
AttackableCharacter& a = tile.second;
if (a.attackers.empty ())
continue;
assert (a.drawnLife == 0);
/* Find the player state of the attacked character. */
PlayerStateMap::iterator vit = state.players.find (a.chid.player);
assert (vit != state.players.end ());
PlayerState& victim = vit->second;
/* In case of life steal, actually draw life. The coins are not yet
added to the attacker, but instead their total amount is saved
for future redistribution. */
if (lifeSteal)
{
assert (a.chid.index == 0);
int64_t fullDamage = damage * a.attackers.size ();
if (fullDamage > victim.value)
fullDamage = victim.value;
victim.value -= fullDamage;
a.drawnLife += fullDamage;
/* If less than the minimum amount remains, als that is drawn
and later added to the game fund. */
assert (victim.value >= 0);
if (victim.value < damage)
{
a.drawnLife += victim.value;
victim.value = 0;
}
}
assert (victim.value >= 0);
assert (a.drawnLife >= 0);
/* If we have life steal and there is remaining health, let
the player survive. Note that it must have at least the minimum
value. If "split coins" are remaining, we still kill it. */
if (lifeSteal && victim.value != 0)
{
assert (victim.value >= damage);
continue;
}
if (a.chid.index == 0)
for (std::set<CharacterID>::const_iterator at = a.attackers.begin ();
at != a.attackers.end (); ++at)
{
const KilledByInfo killer(*at);
result.KillPlayer (a.chid.player, killer);
}
if (victim.characters.count (a.chid.index) > 0)
{
assert (a.attackers.begin () != a.attackers.end ());
const KilledByInfo& info(*a.attackers.begin ());
state.HandleKilledLoot (a.chid.player, a.chid.index, info, result);
victim.characters.erase (a.chid.index);
}
}
}
void
CharactersOnTiles::DefendMutualAttacks (const GameState& state)
{
if (!built)
return;
/* Build up a set of all (directed) attacks happening. The pairs
mean an attack (from, to). This is then later used to determine
mutual attacks, and remove them accordingly.
One can probably do this in a more efficient way, but for now this
is how it is implemented. */
typedef std::pair<CharacterID, CharacterID> Attack;
std::set<Attack> attacks;
BOOST_FOREACH (const PAIRTYPE(const Coord, AttackableCharacter)& tile, tiles)
{
const AttackableCharacter& a = tile.second;
for (std::set<CharacterID>::const_iterator mi = a.attackers.begin ();
mi != a.attackers.end (); ++mi)
attacks.insert (std::make_pair (*mi, a.chid));
}
BOOST_FOREACH (PAIRTYPE(const Coord, AttackableCharacter)& tile, tiles)
{
AttackableCharacter& a = tile.second;
std::set<CharacterID> notDefended;
for (std::set<CharacterID>::const_iterator mi = a.attackers.begin ();
mi != a.attackers.end (); ++mi)
{
const Attack counterAttack(a.chid, *mi);
if (attacks.count (counterAttack) == 0)
notDefended.insert (*mi);
}
a.attackers.swap (notDefended);
}
}
void
CharactersOnTiles::DistributeDrawnLife (RandomGenerator& rnd,
GameState& state) const
{
if (!built)
return;
const int64_t damage = GetNameCoinAmount (state.nHeight);
/* Life is already drawn. It remains to distribute the drawn balances
from each attacked character back to its attackers. For this,
we first find the still alive players and assemble them in a map. */
std::map<CharacterID, PlayerState*> alivePlayers;
BOOST_FOREACH (const PAIRTYPE(const Coord, AttackableCharacter)& tile, tiles)
{
const AttackableCharacter& a = tile.second;
assert (alivePlayers.count (a.chid) == 0);
/* Only non-hearted characters should be around if this is called,
since this means that life-steal is in effect. */
assert (a.chid.index == 0);
const PlayerStateMap::iterator pit = state.players.find (a.chid.player);
if (pit != state.players.end ())
{
PlayerState& pl = pit->second;
assert (pl.characters.count (a.chid.index) > 0);
alivePlayers.insert (std::make_pair (a.chid, &pl));
}
}
/* Now go over all attacks and distribute life to the attackers. */
BOOST_FOREACH (const PAIRTYPE(const Coord, AttackableCharacter)& tile, tiles)
{
const AttackableCharacter& a = tile.second;
if (a.attackers.empty () || a.drawnLife == 0)
continue;
/* Find attackers that are still alive. We will randomly distribute
coins to them later on. */
std::vector<CharacterID> alive;
for (std::set<CharacterID>::const_iterator mi = a.attackers.begin ();
mi != a.attackers.end (); ++mi)
if (alivePlayers.count (*mi) > 0)
alive.push_back (*mi);
/* Distribute the drawn life randomly until either all is spent
or all alive attackers have gotten some. */
int64_t toSpend = a.drawnLife;
while (!alive.empty () && toSpend >= damage)
{
const unsigned ind = rnd.GetIntRnd (alive.size ());
const std::map<CharacterID, PlayerState*>::iterator plIt
= alivePlayers.find (alive[ind]);
assert (plIt != alivePlayers.end ());
toSpend -= damage;
plIt->second->value += damage;
/* Do not use a silly trick like swapping in the last element.
We want to keep the array ordered at all times. The order is
important with respect to consensus, and this makes the consensus
protocol "clearer" to describe. */
alive.erase (alive.begin () + ind);
}
/* Distribute the remaining value to the game fund. */
assert (toSpend >= 0);
state.gameFund += toSpend;
}
}
/* ************************************************************************** */
/* CharacterState and PlayerState. */
void
CharacterState::Spawn (unsigned nHeight, int color, RandomGenerator &rnd)
{
// less possible player spawn tiles
if (ForkInEffect (FORK_TIMESAVE, nHeight))
{
FillWalkableTiles ();
const int pos = rnd.GetIntRnd (walkableTiles_ts_players.size ());
coord = walkableTiles_ts_players[pos];
dir = rnd.GetIntRnd (1, 8);
if (dir >= 5)
++dir;
assert (dir >= 1 && dir <= 9 && dir != 5);
}
/* Pick a random walkable spawn location after the life-steal fork. */
else if (ForkInEffect (FORK_LIFESTEAL, nHeight))
{
FillWalkableTiles ();
const int pos = rnd.GetIntRnd (walkableTiles.size ());
coord = walkableTiles[pos];
dir = rnd.GetIntRnd (1, 8);
if (dir >= 5)
++dir;
assert (dir >= 1 && dir <= 9 && dir != 5);
}
/* Use old logic with fixed spawns in the corners before the fork. */
else
{
const int pos = rnd.GetIntRnd(2 * SPAWN_AREA_LENGTH - 1);
const int x = pos < SPAWN_AREA_LENGTH ? pos : 0;
const int y = pos < SPAWN_AREA_LENGTH ? 0 : pos - SPAWN_AREA_LENGTH;
switch (color)
{
case 0: // Yellow (top-left)
coord = Coord(x, y);
break;
case 1: // Red (top-right)
coord = Coord(MAP_WIDTH - 1 - x, y);
break;
case 2: // Green (bottom-right)
coord = Coord(MAP_WIDTH - 1 - x, MAP_HEIGHT - 1 - y);
break;
case 3: // Blue (bottom-left)
coord = Coord(x, MAP_HEIGHT - 1 - y);
break;
default:
throw std::runtime_error("CharacterState::Spawn: incorrect color");
}
// Set look-direction for the sprite
if (coord.x == 0)
{
if (coord.y == 0)
dir = 3;
else if (coord.y == MAP_HEIGHT - 1)
dir = 9;
else
dir = 6;
}
else if (coord.x == MAP_WIDTH - 1)
{
if (coord.y == 0)
dir = 1;
else if (coord.y == MAP_HEIGHT - 1)
dir = 7;
else
dir = 4;
}
else if (coord.y == 0)
dir = 2;
else if (coord.y == MAP_HEIGHT - 1)
dir = 8;
}
StopMoving();
}
// Returns direction from c1 to c2 as a number from 1 to 9 (as on the numeric keypad)
static unsigned char
GetDirection (const Coord& c1, const Coord& c2)
{
int dx = c2.x - c1.x;
int dy = c2.y - c1.y;
if (dx < -1)
dx = -1;
else if (dx > 1)
dx = 1;
if (dy < -1)
dy = -1;
else if (dy > 1)
dy = 1;
return (1 - dy) * 3 + dx + 2;
}
// Simple straight-line motion
void CharacterState::MoveTowardsWaypoint()
{