forked from miki151/keeperrl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollective.cpp
1541 lines (1432 loc) · 54 KB
/
collective.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 "stdafx.h"
#include "collective.h"
#include "level.h"
#include "task.h"
#include "player.h"
#include "message_buffer.h"
#include "model.h"
#include "statistics.h"
#include "options.h"
vector<Collective::BuildInfo> Collective::normalBuildInfo {
BuildInfo(BuildInfo::DIG),
BuildInfo({SquareType::STOCKPILE, ResourceId::GOLD, 0, "Storage"}),
BuildInfo({SquareType::TREASURE_CHEST, ResourceId::WOOD, 5, "Treasure room"}),
BuildInfo({ResourceId::WOOD, 5, "Door", ViewId::DOOR}),
BuildInfo({SquareType::BED, ResourceId::WOOD, 10, "Bed"}),
BuildInfo({SquareType::TRAINING_DUMMY, ResourceId::IRON, 20, "Training room"}),
BuildInfo({SquareType::LIBRARY, ResourceId::WOOD, 20, "Library"}),
BuildInfo({SquareType::LABORATORY, ResourceId::STONE, 15, "Laboratory"}),
BuildInfo({SquareType::WORKSHOP, ResourceId::IRON, 15, "Workshop"}),
BuildInfo({SquareType::ANIMAL_TRAP, ResourceId::WOOD, 12, "Beast cage"}, "Place it in the forest."),
BuildInfo({SquareType::GRAVE, ResourceId::STONE, 20, "Graveyard"}),
BuildInfo({TrapType::BOULDER, "Boulder trap", ViewId::BOULDER}),
BuildInfo({TrapType::POISON_GAS, "Gas trap", ViewId::GAS_TRAP}),
BuildInfo(BuildInfo::DESTROY),
BuildInfo(BuildInfo::IMP),
BuildInfo(BuildInfo::GUARD_POST, "Place it anywhere to send a minion."),
};
vector<MinionType> minionTypes {
MinionType::IMP,
MinionType::NORMAL,
MinionType::UNDEAD,
MinionType::GOLEM,
MinionType::BEAST,
};
vector<Collective::BuildInfo>& Collective::getBuildInfo() const {
/* if (!isThroneBuilt())
return initialBuildInfo;
else*/
return normalBuildInfo;
};
Collective::ResourceInfo info;
constexpr const char* const Collective::warningText[numWarnings];
const map<Collective::ResourceId, Collective::ResourceInfo> Collective::resourceInfo {
{ResourceId::GOLD, { SquareType::TREASURE_CHEST, Item::typePredicate(ItemType::GOLD), ItemId::GOLD_PIECE, "gold"}},
{ResourceId::WOOD, { SquareType::STOCKPILE, Item::namePredicate("wood plank"), ItemId::WOOD_PLANK, "wood"}},
{ResourceId::IRON, { SquareType::STOCKPILE, Item::namePredicate("iron ore"), ItemId::IRON_ORE, "iron"}},
{ResourceId::STONE, { SquareType::STOCKPILE, Item::namePredicate("rock"), ItemId::ROCK, "stone"}},
};
vector<TechId> techIds {
TechId::HUMANOID_BREEDING,
TechId::NECROMANCY,
TechId::BEAST_TAMING,
TechId::MATTER_ANIMATION,
TechId::SPELLCASTING};
vector<Collective::ItemFetchInfo> Collective::getFetchInfo() const {
return {
{unMarkedItems(ItemType::CORPSE), SquareType::GRAVE, true, {}, Warning::GRAVES},
{[this](const Item* it) {
return minionEquipment.isItemUseful(it) && !markedItems.count(it);
}, SquareType::STOCKPILE, false, {}, Warning::STORAGE},
{[this](const Item* it) {
return it->getName() == "wood plank" && !markedItems.count(it); },
SquareType::STOCKPILE, false, {SquareType::TREE_TRUNK}, Warning::STORAGE},
{[this](const Item* it) {
return it->getName() == "iron ore" && !markedItems.count(it); },
SquareType::STOCKPILE, false, {}, Warning::STORAGE},
{[this](const Item* it) {
return it->getName() == "rock" && !markedItems.count(it); },
SquareType::STOCKPILE, false, {}, Warning::STORAGE},
};
}
struct MinionTaskInfo {
SquareType square;
string desc;
Collective::Warning warning;
};
map<MinionTask, MinionTaskInfo> taskInfo {
{MinionTask::LABORATORY, {SquareType::LABORATORY, "lab", Collective::Warning::LABORATORY}},
{MinionTask::TRAIN, {SquareType::TRAINING_DUMMY, "training", Collective::Warning::TRAINING}},
{MinionTask::WORKSHOP, {SquareType::WORKSHOP, "crafting", Collective::Warning::WORKSHOP}},
{MinionTask::SLEEP, {SquareType::BED, "sleeping", Collective::Warning::BEDS}},
{MinionTask::GRAVE, {SquareType::GRAVE, "sleeping", Collective::Warning::GRAVES}},
{MinionTask::STUDY, {SquareType::LIBRARY, "studying", Collective::Warning::LIBRARY}},
};
Collective::Collective(Model* m) : mana(200), model(m) {
EventListener::addListener(this);
// init the map so the values can be safely read with .at()
mySquares[SquareType::TREE_TRUNK].clear();
mySquares[SquareType::FLOOR].clear();
for (BuildInfo info : normalBuildInfo)
if (info.buildType == BuildInfo::SQUARE)
mySquares[info.squareInfo.type].clear();
else if (info.buildType == BuildInfo::TRAP)
trapMap[info.trapInfo.type].clear();
credit = {
{ResourceId::GOLD, 100},
{ResourceId::WOOD, 0},
{ResourceId::IRON, 0},
{ResourceId::STONE, 0},
};
for (TechId id: techIds)
techLevels[id] = 0;
for (MinionType t : minionTypes)
minionByType[t].clear();
}
const int basicImpCost = 20;
int startImpNum = -1;
const int minionLimit = 20;
void Collective::render(View* view) {
if (possessed && (!possessed->isPlayer() || possessed->isDead())) {
if (contains(team, possessed))
removeElement(team, possessed);
if ((possessed->isDead() || possessed->isSleeping()) && !team.empty()) {
possess(team.front(), view);
} else {
view->setTimeMilli(possessed->getTime() * 300);
view->clearMessages();
ViewObject::setHallu(false);
possessed = nullptr;
team.clear();
gatheringTeam = false;
teamLevelChanges.clear();
/* if (showDigMsg && Options::getValue(OptionId::HINTS)) {
view->refreshView(this);
showDigMsg = false;*/
// view->presentText("", "Now use the mouse and start digging into the mountain. Build rooms and traps and prepare for war. You can control a minion at any time by clicking on them in the minions tab.");
// }
}
}
if (!possessed) {
view->refreshView(this);
} else
view->stopClock();
if (showWelcomeMsg && Options::getValue(OptionId::HINTS)) {
view->refreshView(this);
showWelcomeMsg = false;
view->presentText("Welcome", "In short: you are an evil warlock who has been banished and will now take revenge on everyone.\n \n"
"Use the mouse to dig into the mountain. You will need access to trees, iron and gold ore. Build rooms and traps and prepare for war. You can control a minion at any time by clicking on them in the minions tab.\n \n You can turn these messages off in the options (press F2).");
}
}
bool Collective::isTurnBased() {
return possessed != nullptr && possessed->isPlayer();
}
vector<pair<Item*, Vec2>> Collective::getTrapItems(TrapType type, set<Vec2> squares) const {
vector<pair<Item*, Vec2>> ret;
if (squares.empty())
squares = mySquares.at(SquareType::WORKSHOP);
for (Vec2 pos : squares) {
vector<Item*> v = level->getSquare(pos)->getItems([type, this](Item* it) {
return it->getTrapType() == type && !markedItems.count(it); });
for (Item* it : v)
ret.emplace_back(it, pos);
}
return ret;
}
ViewObject Collective::getResourceViewObject(ResourceId id) const {
return ItemFactory::fromId(resourceInfo.at(id).itemId)->getViewObject();
}
static string getTechName(TechId id) {
switch (id) {
case TechId::BEAST_TAMING: return "beast taming";
case TechId::MATTER_ANIMATION: return "golem animation";
case TechId::NECROMANCY: return "necromancy";
case TechId::HUMANOID_BREEDING: return "humanoid breeding";
case TechId::SPELLCASTING: return "spellcasting";
}
FAIL << "pwofk";
return "";
}
static ViewObject getTechViewObject(TechId id) {
switch (id) {
case TechId::BEAST_TAMING: return ViewObject(ViewId::BEAR, ViewLayer::CREATURE, "");
case TechId::MATTER_ANIMATION: return ViewObject(ViewId::IRON_GOLEM, ViewLayer::CREATURE, "");
case TechId::NECROMANCY: return ViewObject(ViewId::VAMPIRE_LORD, ViewLayer::CREATURE, "");
case TechId::HUMANOID_BREEDING: return ViewObject(ViewId::BILE_DEMON, ViewLayer::CREATURE, "");
case TechId::SPELLCASTING: return ViewObject(ViewId::SCROLL, ViewLayer::CREATURE, "");
}
FAIL << "pwofk";
return ViewObject();
}
static vector<ItemId> marketItems {
ItemId::HEALING_POTION,
ItemId::SLEEP_POTION,
ItemId::BLINDNESS_POTION,
ItemId::INVISIBLE_POTION,
ItemId::POISON_POTION,
ItemId::SLOW_POTION,
ItemId::SPEED_POTION,
ItemId::WARNING_AMULET,
ItemId::HEALING_AMULET,
ItemId::DEFENSE_AMULET,
ItemId::FRIENDLY_ANIMALS_AMULET,
};
void Collective::handleMarket(View* view, int prevItem) {
if (mySquares[SquareType::STOCKPILE].empty()) {
view->presentText("Information", "You need a storage room to use the market.");
return;
}
vector<View::ListElem> options;
vector<PItem> items;
for (ItemId id : marketItems) {
items.push_back(ItemFactory::fromId(id));
options.emplace_back(items.back()->getName() + " $" + convertToString(items.back()->getPrice()),
items.back()->getPrice() > numGold(ResourceId::GOLD) ? View::INACTIVE : View::NORMAL);
}
auto index = view->chooseFromList("Buy items", options, prevItem);
if (!index)
return;
Vec2 dest = chooseRandom(mySquares[SquareType::STOCKPILE]);
takeGold({ResourceId::GOLD, items[*index]->getPrice()});
level->getSquare(dest)->dropItem(std::move(items[*index]));
view->updateView(this);
handleMarket(view, *index);
}
static string getTechLevelName(int level) {
CHECK(level >= 0 && level < 4);
return vector<string>({"basic", "advanced", "expert", "master"})[level];
}
struct SpellLearningInfo {
SpellId id;
int techLevel;
};
vector<SpellLearningInfo> spellLearning {
{ SpellId::HEALING, 0 },
{ SpellId::SUMMON_INSECTS, 0},
{ SpellId::DECEPTION, 1},
{ SpellId::SPEED_SELF, 1},
{ SpellId::STR_BONUS, 1},
{ SpellId::DEX_BONUS, 2},
{ SpellId::FIRE_SPHERE_PET, 2},
{ SpellId::TELEPORT, 2},
{ SpellId::INVISIBILITY, 3},
{ SpellId::WORD_OF_POWER, 3},
};
void Collective::handlePersonalSpells(View* view) {
vector<View::ListElem> options {
View::ListElem("The Keeper can learn spells for use in combat and other situations. ", View::TITLE),
View::ListElem("You can cast them with 's' when you are in control of the Keeper.", View::TITLE)};
vector<SpellId> knownSpells;
for (SpellInfo spell : heart->getSpells())
knownSpells.push_back(spell.id);
for (auto elem : spellLearning) {
SpellInfo spell = Creature::getSpell(elem.id);
View::ElemMod mod = View::NORMAL;
if (!contains(knownSpells, spell.id))
mod = View::INACTIVE;
options.emplace_back(spell.name + " level: " + getTechLevelName(elem.techLevel), mod);
}
view->presentList(capitalFirst(getTechName(TechId::SPELLCASTING)), options);
}
vector<Collective::SpawnInfo> raisingInfo {
{CreatureId::SKELETON, 30, 0},
{CreatureId::ZOMBIE, 50, 0},
{CreatureId::MUMMY, 50, 1},
{CreatureId::VAMPIRE, 50, 2},
{CreatureId::VAMPIRE_LORD, 100, 3},
};
void Collective::handleNecromancy(View* view, int prevItem, bool firstTime) {
int techLevel = techLevels[TechId::NECROMANCY];
set<Vec2> graves = mySquares.at(SquareType::GRAVE);
vector<View::ListElem> options;
bool allInactive = false;
if (minions.size() >= minionLimit) {
allInactive = true;
options.emplace_back("You have reached the limit of the number of minions.", View::TITLE);
} else
if (graves.empty()) {
allInactive = true;
options.emplace_back("You need to build a graveyard and collect corpses to raise undead.", View::TITLE);
} else
if (graves.size() <= minionByType.at(MinionType::UNDEAD).size()) {
allInactive = true;
options.emplace_back("You need to build more graves for your undead to sleep in.", View::TITLE);
}
vector<pair<Vec2, Item*>> corpses;
for (Vec2 pos : graves) {
for (Item* it : level->getSquare(pos)->getItems([](const Item* it) {
return it->getType() == ItemType::CORPSE && it->getCorpseInfo()->canBeRevived; }))
corpses.push_back({pos, it});
}
if (!allInactive && corpses.empty()) {
options.emplace_back("You need to collect some corpses to raise undead.", View::TITLE);
allInactive = true;
}
vector<pair<PCreature, int>> creatures;
for (SpawnInfo info : raisingInfo) {
creatures.push_back({CreatureFactory::fromId(info.id, Tribe::player, MonsterAIFactory::collective(this)),
info.manaCost});
options.emplace_back(creatures.back().first->getName() + " mana: " + convertToString(info.manaCost) +
" level: " + getTechLevelName(info.minLevel),
allInactive || info.minLevel > techLevel || info.manaCost > mana ? View::INACTIVE : View::NORMAL);
}
auto index = view->chooseFromList("Necromancy level: " + getTechLevelName(techLevel) + ", " +
convertToString(corpses.size()) + " bodies available", options, prevItem);
if (!index)
return;
// TODO: try many corpses before failing
auto elem = chooseRandom(corpses);
PCreature& creature = creatures[*index].first;
mana -= creatures[*index].second;
for (Vec2 v : elem.first.neighbors8(true))
if (level->getSquare(v)->canEnter(creature.get())) {
level->getSquare(elem.first)->removeItems({elem.second});
addCreature(creature.get(), MinionType::UNDEAD);
level->addCreature(v, std::move(creature));
break;
}
if (creature)
messageBuffer.addMessage(MessageBuffer::important("You have failed to reanimate the corpse."));
view->updateView(this);
handleNecromancy(view, *index, false);
}
vector<Collective::SpawnInfo> animationInfo {
{CreatureId::CLAY_GOLEM, 30, 0},
{CreatureId::STONE_GOLEM, 50, 1},
{CreatureId::IRON_GOLEM, 50, 2},
{CreatureId::LAVA_GOLEM, 100, 3},
};
void Collective::handleMatterAnimation(View* view) {
handleSpawning(view, TechId::MATTER_ANIMATION, SquareType::LABORATORY,
"You need to build a laboratory to animate golems.", "You need a larger laboratory.", "Golem animation",
MinionType::GOLEM, animationInfo);
}
vector<Collective::SpawnInfo> tamingInfo {
{CreatureId::RAVEN, 5, 0},
{CreatureId::WOLF, 30, 1},
{CreatureId::CAVE_BEAR, 50, 2},
{CreatureId::SPECIAL_MONSTER, 100, 3},
};
void Collective::handleBeastTaming(View* view) {
handleSpawning(view, TechId::BEAST_TAMING, SquareType::ANIMAL_TRAP,
"You need to build cages to trap beasts.", "You need more cages.", "Beast taming",
MinionType::BEAST, tamingInfo);
}
vector<Collective::SpawnInfo> breedingInfo {
{CreatureId::GNOME, 30, 0},
{CreatureId::GOBLIN, 50, 1},
{CreatureId::BILE_DEMON, 80, 2},
{CreatureId::SPECIAL_HUMANOID, 100, 3},
};
void Collective::handleHumanoidBreeding(View* view) {
handleSpawning(view, TechId::HUMANOID_BREEDING, SquareType::BED,
"You need to build beds to breed humanoids.", "You need more beds.", "Humanoid breeding",
MinionType::NORMAL, breedingInfo);
}
void Collective::handleSpawning(View* view, TechId techId, SquareType spawnSquare,
const string& info1, const string& info2, const string& title, MinionType minionType,
vector<SpawnInfo> spawnInfo) {
int techLevel = techLevels[techId];
set<Vec2> cages = mySquares.at(spawnSquare);
int prevItem = 0;
bool allInactive = false;
while (1) {
vector<View::ListElem> options;
if (minions.size() >= minionLimit) {
allInactive = true;
options.emplace_back("You have reached the limit of the number of minions.", View::TITLE);
} else
if (cages.empty()) {
allInactive = true;
options.emplace_back(info1, View::TITLE);
} else
if (cages.size() <= minionByType.at(minionType).size()) {
allInactive = true;
options.emplace_back(info2, View::TITLE);
}
vector<pair<PCreature, int>> creatures;
for (SpawnInfo info : spawnInfo) {
creatures.push_back({CreatureFactory::fromId(info.id, Tribe::player, MonsterAIFactory::collective(this)),
info.manaCost});
options.emplace_back(creatures.back().first->getName() + " mana: " + convertToString(info.manaCost) +
" level: " + getTechLevelName(info.minLevel),
allInactive || info.minLevel > techLevel || info.manaCost > mana ? View::INACTIVE : View::NORMAL);
}
auto index = view->chooseFromList(title + " level: " + getTechLevelName(techLevel), options, prevItem);
if (!index)
return;
Vec2 pos = chooseRandom(cages);
PCreature& creature = creatures[*index].first;
mana -= creatures[*index].second;
for (Vec2 v : pos.neighbors8(true))
if (level->getSquare(v)->canEnter(creature.get())) {
addCreature(creature.get(), minionType);
level->addCreature(v, std::move(creature));
break;
}
if (creature)
messageBuffer.addMessage(MessageBuffer::important("The spell failed."));
view->updateView(this);
prevItem = *index;
}
}
vector<int> techAdvancePoints { 100, 200, 300, 1000};
void Collective::handleLibrary(View* view) {
if (mySquares.at(SquareType::LIBRARY).empty()) {
view->presentText("", "You need to build a library to start research.");
return;
}
if (mySquares.at(SquareType::LIBRARY).size() <= numTotalTech()) {
view->presentText("", "You need a larger library to continue research.");
return;
}
vector<View::ListElem> options;
options.push_back(View::ListElem("You have " + convertToString(int(mana)) + " mana.", View::TITLE));
for (TechId id : techIds) {
string text = getTechName(id) + ": " + getTechLevelName(techLevels.at(id));
int neededPoints = techAdvancePoints[techLevels.at(id)];
if (neededPoints < 1000)
text += " (" + convertToString(neededPoints) + " mana to advance)";
options.emplace_back(text, neededPoints <= mana ? View::NORMAL : View::INACTIVE);
}
auto index = view->chooseFromList("Library", options);
if (!index)
return;
TechId id = techIds[*index];
mana -= techAdvancePoints[techLevels.at(id)];
++techLevels[id];
if (id == TechId::SPELLCASTING)
for (auto elem : spellLearning)
if (elem.techLevel == techLevels[id])
heart->addSpell(elem.id);
view->updateView(this);
handleLibrary(view);
}
int Collective::numTotalTech() const {
int ret = 0;
for (auto id : techIds)
ret += techLevels.at(id);
return ret;
}
void Collective::refreshGameInfo(View::GameInfo& gameInfo) const {
gameInfo.infoType = View::GameInfo::InfoType::BAND;
View::GameInfo::BandInfo& info = gameInfo.bandInfo;
info.name = "KeeperRL";
info.buttons.clear();
for (BuildInfo button : getBuildInfo()) {
switch (button.buildType) {
case BuildInfo::SQUARE: {
BuildInfo::SquareInfo& elem = button.squareInfo;
Optional<pair<ViewObject, int>> cost;
if (elem.cost > 0)
cost = {getResourceViewObject(elem.resourceId), elem.cost};
info.buttons.push_back({
SquareFactory::get(elem.type)->getViewObject(),
elem.name,
cost,
(elem.cost > 0 ? "[" + convertToString(mySquares.at(elem.type).size()) + "]" : ""),
elem.cost <= numGold(elem.resourceId) });
}
break;
case BuildInfo::DIG: {
info.buttons.push_back({
ViewObject(ViewId::DIG_ICON, ViewLayer::LARGE_ITEM, ""),
"dig or cut tree", Nothing(), "", true});
}
break;
case BuildInfo::TRAP: {
BuildInfo::TrapInfo& elem = button.trapInfo;
int numTraps = getTrapItems(elem.type).size();
info.buttons.push_back({
ViewObject(elem.viewId, ViewLayer::LARGE_ITEM, ""),
elem.name,
Nothing(),
"(" + convertToString(numTraps) + " ready)",
numTraps > 0});
}
break;
case BuildInfo::DOOR: {
BuildInfo::DoorInfo& elem = button.doorInfo;
pair<ViewObject, int> cost = {getResourceViewObject(elem.resourceId), elem.cost};
info.buttons.push_back({
ViewObject(elem.viewId, ViewLayer::LARGE_ITEM, ""),
elem.name,
cost,
"[" + convertToString(doors.size()) + "]",
elem.cost <= numGold(elem.resourceId)});
}
break;
case BuildInfo::IMP: {
pair<ViewObject, int> cost = {ViewObject::mana(), getImpCost()};
info.buttons.push_back({
ViewObject(ViewId::IMP, ViewLayer::CREATURE, ""),
"Imp",
cost,
"[" + convertToString(imps.size()) + "]",
getImpCost() <= mana});
break; }
case BuildInfo::DESTROY:
info.buttons.push_back({
ViewObject(ViewId::DESTROY_BUTTON, ViewLayer::CREATURE, ""), "Remove construction", Nothing(), "",
true});
break;
case BuildInfo::GUARD_POST:
info.buttons.push_back({
ViewObject(ViewId::GUARD_POST, ViewLayer::CREATURE, ""), "Guard post", Nothing(), "", true});
break;
}
info.buttons.back().help = button.help;
}
info.activeButton = currentButton;
info.tasks = minionTaskStrings;
for (Creature* c : minions)
if (isInCombat(c))
info.tasks[c] = "fighting";
info.monsterHeader = "Monsters: " + convertToString(minions.size()) + " / " + convertToString(minionLimit);
info.creatures.clear();
for (Creature* c : minions)
info.creatures.push_back(c);
info.enemies.clear();
for (Vec2 v : myTiles)
if (Creature* c = level->getSquare(v)->getCreature())
if (c->getTribe() != Tribe::player)
info.enemies.push_back(c);
info.numGold.clear();
for (auto elem : resourceInfo)
info.numGold.push_back({getResourceViewObject(elem.first), numGold(elem.first), elem.second.name});
info.numGold.push_back({ViewObject::mana(), int(mana), "mana"});
info.numGold.push_back({ViewObject(ViewId::DANGER, ViewLayer::CREATURE, ""), int(getDangerLevel()) + points,
"points"});
info.warning = "";
for (int i : Range(numWarnings))
if (warning[i]) {
info.warning = warningText[i];
break;
}
info.time = heart->getTime();
info.gatheringTeam = gatheringTeam;
info.team.clear();
for (Creature* c : team)
info.team.push_back(c);
info.techButtons.clear();
for (TechId id : techIds) {
info.techButtons.push_back({getTechViewObject(id), getTechName(id)});
}
info.techButtons.push_back({Nothing(), ""});
info.techButtons.push_back({ViewObject(ViewId::LIBRARY, ViewLayer::CREATURE, ""), "library"});
info.techButtons.push_back({ViewObject(ViewId::GOLD, ViewLayer::CREATURE, ""), "black market"});
}
const MapMemory& Collective::getMemory(const Level* l) const {
return memory[l];
}
static ViewObject getTrapObject(TrapType type) {
switch (type) {
case TrapType::BOULDER: return ViewObject(ViewId::UNARMED_BOULDER_TRAP, ViewLayer::LARGE_ITEM, "Unarmed trap");
case TrapType::POISON_GAS: return ViewObject(ViewId::UNARMED_GAS_TRAP, ViewLayer::LARGE_ITEM, "Unarmed trap");
}
return ViewObject(ViewId::UNARMED_GAS_TRAP, ViewLayer::LARGE_ITEM, "Unarmed trap");
}
ViewIndex Collective::getViewIndex(Vec2 pos) const {
ViewIndex index = level->getSquare(pos)->getViewIndex(this);
if (marked.count(pos))
index.setHighlight(HighlightType::BUILD);
if (!index.hasObject(ViewLayer::LARGE_ITEM)) {
if (traps.count(pos))
index.insert(getTrapObject(traps.at(pos).type));
if (guardPosts.count(pos))
index.insert(ViewObject(ViewId::GUARD_POST, ViewLayer::LARGE_ITEM, "Guard post"));
if (doors.count(pos))
index.insert(ViewObject(ViewId::PLANNED_DOOR, ViewLayer::LARGE_ITEM, "Planned door"));
}
if (const Location* loc = level->getLocation(pos)) {
if (loc->isMarkedAsSurprise() && loc->getBounds().middle() == pos && !memory[level].hasViewIndex(pos))
index.insert(ViewObject(ViewId::UNKNOWN_MONSTER, ViewLayer::CREATURE, "Surprise"));
}
return index;
}
bool Collective::staticPosition() const {
return false;
}
Vec2 Collective::getPosition() const {
return heart->getPosition();
}
enum Selection { SELECT, DESELECT, NONE } selection = NONE;
void Collective::addTask(PTask task, Creature* c) {
taken[task.get()] = c;
taskMap[c] = task.get();
addTask(std::move(task));
}
void Collective::addTask(PTask task) {
tasks.push_back(std::move(task));
}
void Collective::delayTask(Task* task, double time) {
CHECK(task->canTransfer());
delayed[task] = time;
// Debug() << "Delaying " << (taken.count(task) ? "taken " : "") << task->getInfo();
if (taken.count(task)) {
taskMap.erase(taken.at(task));
taken.erase(task);
}
}
bool Collective::isDelayed(Task* task, double time) {
if (delayed.count(task)) {
if (delayed.at(task) > time)
return true;
else
delayed.erase(task);
}
return false;
}
void Collective::removeTask(Task* task) {
if (marked.count(task->getPosition()))
marked.erase(task->getPosition());
for (int i : All(tasks))
if (tasks[i].get() == task) {
removeIndex(tasks, i);
break;
}
if (taken.count(task)) {
taskMap.erase(taken.at(task));
taken.erase(task);
}
}
void Collective::markSquare(Vec2 pos, SquareType type, CostInfo cost) {
tasks.push_back(Task::construction(this, pos, type));
marked[pos] = tasks.back().get();
if (cost.value)
completionCost[tasks.back().get()] = cost;
}
void Collective::unmarkSquare(Vec2 pos) {
Task* t = marked.at(pos);
if (completionCost.count(t)) {
returnGold(completionCost.at(t));
completionCost.erase(t);
}
removeTask(t);
marked.erase(pos);
}
int Collective::numGold(ResourceId id) const {
int ret = credit.at(id);
for (Vec2 pos : mySquares.at(resourceInfo.at(id).storageType))
ret += level->getSquare(pos)->getItems(resourceInfo.at(id).predicate).size();
return ret;
}
void Collective::takeGold(CostInfo cost) {
int num = cost.value;
if (num == 0)
return;
CHECK(num > 0);
if (credit.at(cost.id)) {
if (credit.at(cost.id) >= num) {
credit[cost.id] -= num;
return;
} else {
num -= credit.at(cost.id);
credit[cost.id] = 0;
}
}
for (Vec2 pos : randomPermutation(mySquares[resourceInfo.at(cost.id).storageType])) {
vector<Item*> goldHere = level->getSquare(pos)->getItems(resourceInfo.at(cost.id).predicate);
for (Item* it : goldHere) {
level->getSquare(pos)->removeItem(it);
if (--num == 0)
return;
}
}
FAIL << "Didn't have enough gold";
}
void Collective::returnGold(CostInfo amount) {
if (amount.value == 0)
return;
CHECK(amount.value > 0);
if (mySquares[resourceInfo.at(amount.id).storageType].empty()) {
credit[amount.id] += amount.value;
} else
level->getSquare(chooseRandom(mySquares[resourceInfo.at(amount.id).storageType]))->
dropItems(ItemFactory::fromId(resourceInfo.at(amount.id).itemId, amount.value));
}
int Collective::getImpCost() const {
if (imps.size() < startImpNum)
return 0;
return basicImpCost * pow(2, double(imps.size() - startImpNum) / 5);
}
void Collective::possess(const Creature* cr, View* view) {
view->stopClock();
CHECK(contains(creatures, cr));
CHECK(!cr->isDead());
Creature* c = const_cast<Creature*>(cr);
if (c->isSleeping())
c->wakeUp();
freeFromGuardPost(c);
c->pushController(new Player(c, view, model, false, &memory));
possessed = c;
c->getLevel()->setPlayer(c);
}
bool Collective::canBuildDoor(Vec2 pos) const {
if (!level->getSquare(pos)->canConstruct(SquareType::TRIBE_DOOR))
return false;
Rectangle innerRect = level->getBounds().minusMargin(1);
auto wallFun = [=](Vec2 pos) {
return level->getSquare(pos)->canConstruct(SquareType::FLOOR) ||
!pos.inRectangle(innerRect); };
return !traps.count(pos) && pos.inRectangle(innerRect) &&
((wallFun(pos - Vec2(0, 1)) && wallFun(pos - Vec2(0, -1))) ||
(wallFun(pos - Vec2(1, 0)) && wallFun(pos - Vec2(-1, 0))));
}
bool Collective::canPlacePost(Vec2 pos) const {
return !guardPosts.count(pos) && !traps.count(pos) &&
level->getSquare(pos)->canEnterEmpty(Creature::getDefault()) && memory[level].hasViewIndex(pos);
}
void Collective::freeFromGuardPost(const Creature* c) {
for (auto& elem : guardPosts)
if (elem.second.attender == c)
elem.second.attender = nullptr;
}
void Collective::processInput(View* view) {
CollectiveAction action = view->getClick();
switch (action.getType()) {
case CollectiveAction::GATHER_TEAM:
if (gatheringTeam && !team.empty()) {
possess(team[0], view);
gatheringTeam = false;
for (Creature* c : team) {
freeFromGuardPost(c);
if (c->isSleeping())
c->wakeUp();
}
} else
gatheringTeam = true;
break;
case CollectiveAction::DRAW_LEVEL_MAP: view->drawLevelMap(level, this); break;
case CollectiveAction::CANCEL_TEAM: gatheringTeam = false; team.clear(); break;
case CollectiveAction::MARKET: handleMarket(view); break;
case CollectiveAction::TECHNOLOGY:
if (action.getNum() < techIds.size())
switch (techIds[action.getNum()]) {
case TechId::NECROMANCY: handleNecromancy(view); break;
case TechId::SPELLCASTING: handlePersonalSpells(view); break;
case TechId::MATTER_ANIMATION: handleMatterAnimation(view); break;
case TechId::BEAST_TAMING: handleBeastTaming(view); break;
case TechId::HUMANOID_BREEDING: handleHumanoidBreeding(view); break;
default: break;
};
if (action.getNum() == techIds.size() + 1)
handleLibrary(view);
if (action.getNum() == techIds.size() + 2)
handleMarket(view);
break;
case CollectiveAction::ROOM_BUTTON: currentButton = action.getNum(); break;
case CollectiveAction::CREATURE_BUTTON:
if (!gatheringTeam)
possess(action.getCreature(), view);
else {
if (contains(team, action.getCreature()))
removeElement(team, action.getCreature());
else
team.push_back(const_cast<Creature*>(action.getCreature()));
}
break;
case CollectiveAction::CREATURE_DESCRIPTION: messageBuffer.addMessage(MessageBuffer::important(
action.getCreature()->getDescription())); break;
case CollectiveAction::POSSESS: {
Vec2 pos = action.getPosition();
if (!pos.inRectangle(level->getBounds()))
return;
if (Creature* c = level->getSquare(pos)->getCreature())
if (contains(minions, c)) {
possess(c, view);
break;
}
}
break;
case CollectiveAction::GO_TO: {
Vec2 pos = action.getPosition();
if (!pos.inRectangle(level->getBounds()))
break;
switch (getBuildInfo()[currentButton].buildType) {
case BuildInfo::IMP:
if (mana >= getImpCost() && selection == NONE) {
selection = SELECT;
PCreature imp = CreatureFactory::fromId(CreatureId::IMP, Tribe::player,
MonsterAIFactory::collective(this));
for (Vec2 v : pos.neighbors8(true))
if (v.inRectangle(level->getBounds()) && level->getSquare(v)->canEnter(imp.get())
&& canSee(v)) {
mana -= getImpCost();
addCreature(imp.get(), MinionType::IMP);
level->addCreature(v, std::move(imp));
break;
}
}
break;
case BuildInfo::TRAP: {
TrapType trapType = getBuildInfo()[currentButton].trapInfo.type;
if (getTrapItems(trapType).size() > 0 && canPlacePost(pos) && myTiles.count(pos)){
traps[pos] = {trapType, false, false};
trapMap[trapType].push_back(pos);
updateTraps();
}
}
break;
case BuildInfo::DOOR: {
BuildInfo::DoorInfo info = getBuildInfo()[currentButton].doorInfo;
if (numGold(info.resourceId) >= info.cost && canBuildDoor(pos)){
doors[pos] = {{info.resourceId, info.cost}, false, false};
updateTraps();
}
}
break;
case BuildInfo::DESTROY:
selection = SELECT;
if (level->getSquare(pos)->canDestroy() && myTiles.count(pos))
level->getSquare(pos)->destroy(10000);
level->getSquare(pos)->removeTriggers();
if (Creature* c = level->getSquare(pos)->getCreature())
if (c->getName() == "boulder")
c->die(nullptr, false);
if (traps.count(pos)) {
removeElement(trapMap.at(traps.at(pos).type), pos);
traps.erase(pos);
}
if (doors.count(pos))
doors.erase(pos);
break;
case BuildInfo::GUARD_POST:
if (guardPosts.count(pos) && selection != SELECT) {
guardPosts.erase(pos);
selection = DESELECT;
}
else if (canPlacePost(pos) && guardPosts.size() < minions.size() && selection != DESELECT) {
guardPosts[pos] = {nullptr};
selection = SELECT;
}
break;
case BuildInfo::DIG:
if (marked.count(pos) && selection != SELECT) {
unmarkSquare(pos);
selection = DESELECT;
} else
if (!marked.count(pos) && selection != DESELECT) {
if (level->getSquare(pos)->canConstruct(SquareType::TREE_TRUNK)) {
markSquare(pos, SquareType::TREE_TRUNK, {ResourceId::GOLD, 0});
selection = SELECT;
} else
if (level->getSquare(pos)->canConstruct(SquareType::FLOOR) || !memory[level].hasViewIndex(pos)) {
markSquare(pos, SquareType::FLOOR, { ResourceId::GOLD, 0});
selection = SELECT;
}
}
break;
case BuildInfo::SQUARE:
if (marked.count(pos) && selection != SELECT) {
unmarkSquare(pos);
selection = DESELECT;
} else {
BuildInfo::SquareInfo info = getBuildInfo()[currentButton].squareInfo;
bool diggingSquare = !memory[level].hasViewIndex(pos) ||
(level->getSquare(pos)->canConstruct(info.type));
if (!marked.count(pos) && selection != DESELECT && diggingSquare &&
numGold(info.resourceId) >= info.cost &&
(info.type != SquareType::TRIBE_DOOR || canBuildDoor(pos)) &&
(info.type == SquareType::FLOOR || canSee(pos))) {
markSquare(pos, info.type, {info.resourceId, info.cost});
selection = SELECT;
takeGold({info.resourceId, info.cost});
}
}
break;
}
}
break;
case CollectiveAction::BUTTON_RELEASE: selection = NONE; break;
case CollectiveAction::IDLE: break;
}
}
void Collective::onConstructed(Vec2 pos, SquareType type) {
if (!contains({SquareType::ANIMAL_TRAP, SquareType::TREE_TRUNK}, type))
myTiles.insert(pos);
CHECK(!mySquares[type].count(pos));
mySquares[type].insert(pos);
if (contains({SquareType::FLOOR, SquareType::BRIDGE}, type))
locked.clear();
if (marked.count(pos))
marked.erase(pos);
if (contains({SquareType::TRIBE_DOOR}, type) && doors.count(pos)) {
doors.at(pos).built = true;
doors.at(pos).marked = false;
}
}
void Collective::onPickedUp(Vec2 pos, vector<Item*> items) {
CHECK(!items.empty());
for (Item* it : items)
markedItems.erase(it);
}
void Collective::onCantPickItem(vector<Item*> items) {
for (Item* it : items)
markedItems.erase(it);
}
void Collective::onBrought(Vec2 pos, vector<Item*> items) {
}
void Collective::onAppliedItem(Vec2 pos, Item* item) {
CHECK(item->getTrapType());
if (traps.count(pos)) {
traps[pos].marked = false;
traps[pos].armed = true;
}
}
void Collective::onAppliedSquare(Vec2 pos) {
if (mySquares.at(SquareType::LIBRARY).count(pos)) {
mana += 1 + max(0., 1 - double(getDangerLevel()) / 1000);
}
if (mySquares.at(SquareType::LABORATORY).count(pos))
if (Random.roll(30)) {
level->getSquare(pos)->dropItems(ItemFactory::potions().random());
Statistics::add(StatId::POTION_PRODUCED);
}
if (mySquares.at(SquareType::WORKSHOP).count(pos))
if (Random.roll(40)) {
vector<PItem> items = ItemFactory::workshop().random();
if (items[0]->getType() == ItemType::WEAPON)
Statistics::add(StatId::WEAPON_PRODUCED);
if (items[0]->getType() == ItemType::ARMOR)
Statistics::add(StatId::ARMOR_PRODUCED);
level->getSquare(pos)->dropItems(std::move(items));
}
}
void Collective::onAppliedItemCancel(Vec2 pos) {
traps.at(pos).marked = false;
}
Vec2 Collective::getHeartPos() const {
return heart->getPosition();
}
double Collective::getDangerLevel() const {
double ret = 0;