]> git.localhorst.tv Git - l2e.git/blob - src/battle/BattleState.cpp
randomized monsters' attack target selection
[l2e.git] / src / battle / BattleState.cpp
1 /*
2  * BattleState.cpp
3  *
4  *  Created on: Aug 5, 2012
5  *      Author: holy
6  */
7
8 #include "BattleState.h"
9
10 #include "PartyLayout.h"
11 #include "states/SelectMoveAction.h"
12 #include "states/PerformAttacks.h"
13 #include "../app/Application.h"
14 #include "../app/Input.h"
15 #include "../common/Ikari.h"
16 #include "../common/Inventory.h"
17 #include "../common/Item.h"
18 #include "../common/Spell.h"
19 #include "../geometry/operators.h"
20 #include "../graphics/Frame.h"
21 #include "../graphics/Sprite.h"
22
23 #include <algorithm>
24 #include <cassert>
25 #include <cstdlib>
26 #include <stdexcept>
27
28 using app::Application;
29 using app::Input;
30 using common::Inventory;
31 using common::Item;
32 using common::Spell;
33 using geometry::Point;
34 using geometry::Vector;
35 using graphics::Menu;
36
37 using std::rand;
38 using std::vector;
39
40 namespace battle {
41
42 void BattleState::AddMonster(const Monster &m) {
43         if (monsters.size() >= monstersLayout->NumPositions()) {
44                 throw std::overflow_error("too many monsters for layout");
45         }
46         monsters.push_back(m);
47 }
48
49 void BattleState::AddHero(const Hero &h) {
50         if (numHeroes >= 4 || numHeroes >= (int)heroesLayout->NumPositions()) {
51                 throw std::overflow_error("too many heroes for layout");
52         }
53         heroes[numHeroes] = h;
54         ++numHeroes;
55 }
56
57 void BattleState::NextHero() {
58         ++activeHero;
59         while (activeHero < numHeroes && heroes[activeHero].Health() == 0) {
60                 ++activeHero;
61         }
62 }
63
64 void BattleState::PreviousHero() {
65         --activeHero;
66         while (activeHero >= 0 && heroes[activeHero].Health() == 0) {
67                 --activeHero;
68         }
69 }
70
71 void BattleState::SwapHeroes(int lhs, int rhs) {
72         if (lhs < 0 || lhs >= numHeroes || rhs < 0 || rhs >= numHeroes || lhs == rhs) return;
73         std::swap(heroes[lhs], heroes[rhs]);
74 }
75
76
77 void BattleState::Resize(int w, int h) {
78
79 }
80
81
82 void BattleState::EnterState(Application &ctrl, SDL_Surface *screen) {
83         for (int i(0); i < 4; ++i) {
84                 heroes[i].Position() = heroesLayout->CalculatePosition(i, background->w, background->h);
85                 heroes[i].SpellMenu() = res->spellMenuPrototype;
86                 heroes[i].UpdateSpellMenu();
87                 heroes[i].IkariMenu() = res->ikariMenuPrototype;
88                 heroes[i].UpdateIkariMenu(res);
89                 heroTags[i] = HeroTag(this, i);
90                 smallHeroTags[i] = SmallHeroTag(this, i);
91         }
92
93         for (int i(0); i < int(monsters.size()); ++i) {
94                 monsters[i].Position() = monstersLayout->CalculatePosition(i, background->w, background->h);
95         }
96
97         int tagHeight(attackTypeMenu.Height());
98         int tagWidth(attackTypeMenu.Width() * 2 + attackTypeMenu.Width() / 2);
99         int xOffset((Width() - 2 * tagWidth) / 2);
100         heroTagPositions[0] = Point<int>(xOffset, Height() - 2 * tagHeight);
101         heroTagPositions[1] = Point<int>(xOffset + tagWidth, Height() - 2 * tagHeight);
102         heroTagPositions[2] = Point<int>(xOffset, Height() - tagHeight);
103         heroTagPositions[3] = Point<int>(xOffset + tagWidth, Height() - tagHeight);
104
105         tagHeight = res->normalFont->CharHeight() * 4 + res->smallHeroTagFrame->BorderHeight() * 2;
106         tagWidth = res->normalFont->CharWidth() * 6 + res->smallHeroTagFrame->BorderWidth() * 2;
107         xOffset = (Width() - 4 * tagWidth) / 2;
108         int yOffset(Height() - tagHeight);
109         smallHeroTagPositions[0] = Point<int>(xOffset, yOffset);
110         smallHeroTagPositions[1] = Point<int>(xOffset + 2 * tagWidth, yOffset);
111         smallHeroTagPositions[2] = Point<int>(xOffset + tagWidth, yOffset);
112         smallHeroTagPositions[3] = Point<int>(xOffset + 3 * tagWidth, yOffset);
113
114         itemMenu = res->itemMenuPrototype;
115         LoadInventory();
116 }
117
118 void BattleState::LoadInventory() {
119         const Inventory &inv(*res->inventory);
120         itemMenu.Clear();
121         itemMenu.Reserve(inv.MaxItems());
122         for (int i(0); i < inv.MaxItems(); ++i) {
123                 const Item *item(inv.ItemAt(i));
124                 if (item) {
125                         itemMenu.Add(item->Name(), item, item->CanUseInBattle(), item->MenuIcon(), inv.ItemCountAt(i));
126                 } else {
127                         itemMenu.AddEmptyEntry();
128                 }
129         }
130         ClearAllAttacks();
131 }
132
133 void BattleState::ExitState(Application &ctrl, SDL_Surface *screen) {
134
135 }
136
137 void BattleState::ResumeState(Application &ctrl, SDL_Surface *screen) {
138         if (ranAway) {
139                 ctrl.PopState(); // quit the battle scene
140                 return;
141         }
142         if (Victory()) {
143                 // TODO: push victory state
144                 ctrl.PopState();
145                 return;
146         }
147         if (Defeat()) {
148                 // TODO: push defeat state
149                 ctrl.PopState();
150                 return;
151         }
152         // TODO: this should not push a state while quitting
153         if (AttackSelectionDone()) {
154                 ctrl.PushState(new PerformAttacks(this));
155         } else {
156                 ctrl.PushState(new SelectMoveAction(this));
157         }
158 }
159
160 bool BattleState::Victory() const {
161         for (int i(0); i < MaxMonsters(); ++i) {
162                 if (MonsterAt(i).Health() > 0) return false;
163         }
164         return true;
165 }
166
167 bool BattleState::Defeat() const {
168         for (int i(0); i < NumHeroes(); ++i) {
169                 if (HeroAt(i).Health() > 0) return false;
170         }
171         return true;
172 }
173
174 void BattleState::PauseState(Application &ctrl, SDL_Surface *screen) {
175
176 }
177
178
179 class OrderCompare {
180         public:
181                 OrderCompare(BattleState *battle) : battle(battle) { }
182                 bool operator ()(const BattleState::Order &lhs, const BattleState::Order &rhs) {
183                         int lagl(lhs.isMonster ? battle->MonsterAt(lhs.index).GetStats().Agility() : battle->HeroAt(lhs.index).GetStats().Agility());
184                         int ragl(rhs.isMonster ? battle->MonsterAt(rhs.index).GetStats().Agility() : battle->HeroAt(rhs.index).GetStats().Agility());
185                         return lagl > ragl;
186                 }
187         private:
188                 BattleState *battle;
189 };
190
191 void BattleState::CalculateAttackOrder() {
192         attackOrder.reserve(monsters.size() + NumHeroes());
193         for (int i(0); i < NumHeroes(); ++i) {
194                 attackOrder.push_back(Order(i, false));
195         }
196         for (vector<Monster>::size_type i(0), end(monsters.size()); i < end; ++i) {
197                 attackOrder.push_back(Order(i, true));
198                 MonsterAt(i).GetAttackChoice() = AttackChoice(this);
199         }
200         std::sort(attackOrder.begin(), attackOrder.end(), OrderCompare(this));
201 }
202
203 void BattleState::NextAttack() {
204         if (Victory() || Defeat()) {
205                 attackCursor = attackOrder.size();
206                 return;
207         }
208         ++attackCursor;
209         while (attackCursor < int(attackOrder.size())) {
210                 if (attackOrder[attackCursor].isMonster) {
211                         if (MonsterAt(attackOrder[attackCursor].index).Health() > 0) break;
212                 } else {
213                         if (HeroAt(attackOrder[attackCursor].index).Health() > 0) break;
214                 }
215                 ++attackCursor;
216         }
217 }
218
219 bool BattleState::AttacksFinished() const {
220         return attackCursor >= int(attackOrder.size())
221                         || Victory() || Defeat();
222 }
223
224 void BattleState::CalculateDamage() {
225         if (CurrentAttack().isMonster) {
226                 DecideMonsterAttack(MonsterAt(CurrentAttack().index));
227         }
228         AttackChoice &ac(CurrentAttack().isMonster ? MonsterAt(CurrentAttack().index).GetAttackChoice() : HeroAt(CurrentAttack().index).GetAttackChoice());
229         if (ac.GetType() == AttackChoice::DEFEND) return;
230         TargetSelection &ts(ac.Selection());
231
232         // TODO: this only evaluates SWORD type attacks
233         if (CurrentAttack().isMonster) {
234                 const Stats &attackerStats(MonsterAt(CurrentAttack().index).GetStats());
235                 if (ts.TargetsEnemies()) {
236                         for (int i(0); i < MaxMonsters(); ++i) {
237                                 if (ts.IsSelected(i)) {
238                                         if (MonsterAt(i).Health() > 0) {
239                                                 const Stats &defenderStats(MonsterAt(i).GetStats());
240                                                 Uint16 damage(CalculateDamage(attackerStats, defenderStats));
241                                                 ts.SetBad(i, damage);
242                                         } else {
243                                                 ts.Unselect(i);
244                                         }
245                                 }
246                         }
247                 } else {
248                         for (int i(0); i < NumHeroes(); ++i) {
249                                 if (ts.IsSelected(i)) {
250                                         if (HeroAt(i).Health() > 0) {
251                                                 const Stats &defenderStats(HeroAt(i).GetStats());
252                                                 Uint16 damage(CalculateDamage(attackerStats, defenderStats));
253                                                 ts.SetBad(i, damage);
254                                         } else {
255                                                 ts.Unselect(i);
256                                         }
257                                 }
258                         }
259                 }
260         } else {
261                 const Stats &attackerStats(HeroAt(CurrentAttack().index).GetStats());
262                 bool hitSome(false);
263                 if (ts.TargetsEnemies()) {
264                         for (int i(0); i < MaxMonsters(); ++i) {
265                                 if (ts.IsSelected(i)) {
266                                         if (MonsterAt(i).Health() > 0) {
267                                                 const Stats &defenderStats(MonsterAt(i).GetStats());
268                                                 Uint16 damage(CalculateDamage(attackerStats, defenderStats));
269                                                 ts.SetBad(i, damage);
270                                                 hitSome = true;
271                                         } else {
272                                                 ts.Unselect(i);
273                                         }
274                                 }
275                         }
276                         if (hitSome) return;
277                         for (int i(0); i < MaxMonsters(); ++i) {
278                                 if (MonsterAt(i).Health() > 0) {
279                                         const Stats &defenderStats(MonsterAt(i).GetStats());
280                                         Uint16 damage(CalculateDamage(attackerStats, defenderStats));
281                                         ts.SetBad(i, damage);
282                                         break;
283                                 }
284                         }
285                 } else {
286                         for (int i(0); i < NumHeroes(); ++i) {
287                                 if (ts.IsSelected(i)) {
288                                         if (HeroAt(i).Health() > 0) {
289                                                 const Stats &defenderStats(HeroAt(i).GetStats());
290                                                 Uint16 damage(CalculateDamage(attackerStats, defenderStats));
291                                                 ts.SetBad(i, damage);
292                                                 hitSome = true;
293                                         } else {
294                                                 ts.Unselect(i);
295                                         }
296                                 }
297                         }
298                         if (hitSome) return;
299                         for (int i(0); i < NumHeroes(); ++i) {
300                                 if (HeroAt(i).Health() > 0) {
301                                         const Stats &defenderStats(HeroAt(i).GetStats());
302                                         Uint16 damage(CalculateDamage(attackerStats, defenderStats));
303                                         ts.SetBad(i, damage);
304                                         break;
305                                 }
306                         }
307                 }
308         }
309 }
310
311 void BattleState::DecideMonsterAttack(Monster &m) {
312         AttackChoice &ac(m.GetAttackChoice());
313         TargetSelection &ts(ac.Selection());
314         ac.Reset();
315         // TODO: run monster's attack script
316         int target(rand() % NumHeroes());
317         while (!HeroPositionOccupied(target)) {
318                 target = rand() % NumHeroes();
319         }
320         ac.SetType(AttackChoice::SWORD);
321         ts.SelectHeroes();
322         ts.SetSingle();
323         ts.Select(target);
324 }
325
326 Uint16 BattleState::CalculateDamage(const Stats &attacker, const Stats &defender) const {
327         // TODO: find out real formula and add some randomness
328         return attacker.Attack() / 2 - defender.Defense() / 4;
329 }
330
331 void BattleState::ApplyDamage() {
332         if (attackCursor < 0) return;
333         AttackChoice &ac(CurrentAttack().isMonster ? MonsterAt(CurrentAttack().index).GetAttackChoice() : HeroAt(CurrentAttack().index).GetAttackChoice());
334         TargetSelection &ts(ac.Selection());
335         if (ts.TargetsEnemies()) {
336                 for (int i(0); i < MaxMonsters(); ++i) {
337                         Monster &monster(MonsterAt(i));
338                         if (ts.IsBad(i)) {
339                                 monster.SubtractHealth(ts.GetAmount(i));
340                                 if (monster.Health() == 0) {
341                                         expReward += monster.ExpReward();
342                                         goldReward += monster.GoldReward();
343                                 }
344                         }
345                 }
346         } else {
347                 for (int i(0); i < NumHeroes(); ++i) {
348                         Hero &hero(HeroAt(i));
349                         if (ts.IsBad(i)) {
350                                 hero.SubtractHealth(ts.GetAmount(i));
351                         }
352                 }
353         }
354 }
355
356 AttackChoice &BattleState::CurrentAttackAttackChoice() {
357         if (CurrentAttack().isMonster) {
358                 return MonsterAt(CurrentAttack().index).GetAttackChoice();
359         } else {
360                 return HeroAt(CurrentAttack().index).GetAttackChoice();
361         }
362 }
363
364 void BattleState::ClearAllAttacks() {
365         attackCursor = -1;
366         activeHero = -1;
367         for (int i(0); i < NumHeroes(); ++i) {
368                 HeroAt(i).GetAttackChoice() = AttackChoice(this);
369         }
370         for (int i(0); i < MaxMonsters(); ++i) {
371                 MonsterAt(i).GetAttackChoice() = AttackChoice(this);
372         }
373         attackOrder.clear();
374 }
375
376
377 void BattleState::HandleEvents(const Input &input) {
378
379 }
380
381 void BattleState::UpdateWorld(float deltaT) {
382
383 }
384
385 void BattleState::Render(SDL_Surface *screen) {
386         assert(screen);
387         Vector<int> offset(CalculateScreenOffset(screen));
388         RenderBackground(screen, offset);
389         RenderMonsters(screen, offset);
390 }
391
392 void BattleState::RenderBackground(SDL_Surface *screen, const Vector<int> &offset) {
393         assert(screen);
394         // black for now
395         SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
396         SDL_Rect destRect;
397         destRect.x = offset.X();
398         destRect.y = offset.Y();
399         destRect.w = background->w;
400         destRect.h = background->h;
401         SDL_BlitSurface(background, 0, screen, &destRect);
402 }
403
404 void BattleState::RenderMonsters(SDL_Surface *screen, const Vector<int> &offset) {
405         assert(screen);
406         for (vector<Monster>::size_type i(0), end(monsters.size()); i < end; ++i) {
407                 if (MonsterPositionOccupied(i)) {
408                         if (monsters[i].GetAnimation().Running()) {
409                                 monsters[i].GetAnimation().DrawCenter(screen, monsters[i].Position() + offset);
410                         } else {
411                                 monsters[i].Sprite()->DrawCenter(screen, monsters[i].Position() + offset);
412                         }
413                 }
414         }
415 }
416
417 void BattleState::RenderHeroes(SDL_Surface *screen, const Vector<int> &offset) {
418         assert(screen);
419         for (int i(0); i < numHeroes; ++i) {
420                 if (heroes[i].GetAnimation().Running()) {
421                         heroes[i].GetAnimation().DrawCenter(screen, heroes[i].Position() + offset);
422                 } else {
423                         int row(heroes[i].Health() > 0 ? 0 : 2);
424                         heroes[i].Sprite()->DrawCenter(screen, heroes[i].Position() + offset, 1, row);
425                 }
426         }
427 }
428
429 void BattleState::RenderHeroTags(SDL_Surface *screen, const Vector<int> &offset) {
430         assert(screen);
431         int tagHeight(attackTypeMenu.Height());
432         int tagWidth(attackTypeMenu.Width() * 2 + attackTypeMenu.Width() / 2);
433
434         for (int i(0); i < numHeroes; ++i) {
435                 heroTags[i].Render(screen, tagWidth, tagHeight, heroTagPositions[i] + offset, (int)i == activeHero);
436         }
437 }
438
439 void BattleState::RenderSmallHeroTags(SDL_Surface *screen, const Vector<int> &offset) {
440         assert(screen);
441         int tagHeight(res->normalFont->CharHeight() * 4 + res->smallHeroTagFrame->BorderHeight() * 2);
442         int tagWidth(res->normalFont->CharWidth() * 6 + res->smallHeroTagFrame->BorderWidth() * 2);
443
444         SDL_Rect rect;
445         rect.x = offset.X();
446         rect.y = offset.Y() + Height() - tagHeight;
447         rect.w = Width();
448         rect.h = tagHeight;
449         SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format, 0, 0, 0));
450         rect.y += res->normalFont->CharHeight() / 8;
451         rect.h -= res->normalFont->CharHeight() / 4;
452         SDL_FillRect(screen, &rect, res->heroesBgColor);
453
454         for (int i(0); i < numHeroes; ++i) {
455                 smallHeroTags[i].Render(screen, tagWidth, tagHeight, smallHeroTagPositions[i] + offset);
456         }
457 }
458
459 }