persona-3-dual
A DS demake of Persona 3
Loading...
Searching...
No Matches
BattleSystem.cpp
Go to the documentation of this file.
1#include "BattleSystem.hpp"
3#include "core/logger.hpp"
4#include "data/audioDb.hpp"
6
7#include <cstdlib>
8#include <ctime>
9
11{
12 active = true;
14
15 if (musicCmpt != nullptr)
16 {
18 }
19
20 this->player = new Player(msg.player);
21 battleParticipants.push_back(this->player);
22 this->partyMembers.push_back(this->player);
23
24 for (CharacterProfile& characterProfile : msg.characterProfiles)
25 {
26 PartyMember* partyMember = new PartyMember(characterProfile);
27 this->partyMembers.push_back(partyMember);
28 battleParticipants.push_back(partyMember);
29 }
30
31 for (EnemyProfile& enemyProfile : msg.enemyProfiles)
32 {
33 Enemy* enemy = new Enemy(enemyProfile);
34 this->enemies.push_back(enemy);
35 battleParticipants.push_back(enemy);
36 }
37
39
40 turnsTaken = 0;
42 selectedSkill = nullptr;
43 pendingAlert.clear();
48 personaBeforeSwitch = nullptr;
49
50 logMessage(LogSeverity::DEBUG, "Battle started with enemies count: " + std::to_string(enemies.size()));
51
53
54 if (battleParticipants.empty())
55 {
56 logMessage(LogSeverity::ERROR, "No battle participants configured in ExecuteBattle");
57 active = false;
58 return;
59 }
60
62
64 phase = currentParticipantTurn->getInitalTurnPhase();
65}
66
68{
69 active = false;
70}
71
72void BattleSystem::update(ae::q20_12_t)
73{
74 switch (phase)
75 {
77 {
78 PartyMember* actor = static_cast<PartyMember*>(currentParticipantTurn);
79
80 // render battleMenu
81 battleMenuCmpt->loadActionOptions(&actions, actor->name);
83 selectedBattleOption = battleMenuCmpt->consumeSelectedBattleOption();
84
86 {
88 {
91 }
93 {
94 TurnResult turnResult = guard.resolve(actor, nullptr);
95 applyResult(turnResult);
97 }
99 {
101 }
103 {
105 {
106 return;
107 }
109 }
110 }
111 break;
112 }
113
115 {
116 PartyMember* actor = static_cast<PartyMember*>(currentParticipantTurn);
117
118 // render battleMenu
119 battleMenuCmpt->loadSkillOptions(actor->curPersona);
120 //TODO: why not just return nullptr if nothing happens instead of setting -1 manually everywhere?
121
123 selectedBattleOption = battleMenuCmpt->consumeSelectedBattleOption();
124
125 if (selectedBattleOption != -1)
126 {
128
129 s32* resource;
130 if (s->skillRace == SkillRace::mag)
131 {
132 resource = &actor->sp;
133 }
134 else
135 {
136 resource = &actor->hp;
137 }
138
139 bool canAfford = *resource >= s->cost;
140 if (canAfford)
141 {
142 *resource -= s->cost;
143 selectedSkill = s;
146 }
147 else
148 {
149 pendingAlert = (s->skillRace == SkillRace::mag) ? "Not enough SP\n" : "Not enough HP\n";
151 battleMenuCmpt->resetLoadedOptions();
153 }
154 }
155
156 if (battleMenuCmpt->consumeCancel())
157 {
159 }
160 break;
161 }
162
164 {
165 Player* actor = static_cast<Player*>(currentParticipantTurn);
166
167 //inital capture of start persona of this turn, so that if we switch personas and
168 //then switch back to the same old starting persona it wont count it as a switch
169 if (personaBeforeSwitch == nullptr)
170 {
172 }
173
174 battleMenuCmpt->loadPersonaOptions(&actor->personas);
176 selectedBattleOption = battleMenuCmpt->consumeSelectedBattleOption();
177
178 if (selectedBattleOption != -1)
179 {
180 if (actor->curPersona == actor->personas[selectedBattleOption])
181 {
182 pendingAlert = "Already using this Persona\n";
184 }
185 else
186 {
189 pendingAlert = "Switched to: " + actor->curPersona->name + "\n";
191 }
192
193 battleMenuCmpt->resetLoadedOptions();
195 }
196
197 if (battleMenuCmpt->consumeCancel())
198 {
200 }
201 break;
202 }
203
205 {
206 PartyMember* actor = static_cast<PartyMember*>(currentParticipantTurn);
207
208 bool healTarget = selectedSkill && (selectedSkill->skillType == SkillType::Heal ||
209 selectedSkill->skillType == SkillType::MultiHeal);
210
211 etl::vector<BattleParticipant*, 13> targets;
212 if (healTarget)
213 {
214 for (PartyMember* partyMember : partyMembers)
215 {
216 targets.push_back(partyMember);
217 }
218 }
219 else
220 {
221 for (Enemy* enemy : enemies)
222 {
223 targets.push_back(enemy);
224 }
225 }
226
227 etl::erase_if(targets, [](BattleParticipant* t) { return t->hp <= 0; });
228
229 battleMenuCmpt->loadTargetOptions(&targets, healTarget);
231 selectedBattleOption = battleMenuCmpt->consumeSelectedBattleOption();
232
233 if (selectedBattleOption != -1)
234 {
235 if (isSingleTarget(selectedSkill->skillType))
236 {
237 BattleParticipant* selectedTarget = targets[selectedBattleOption];
238
239 targets.clear();
240 targets.push_back(selectedTarget);
241 }
242
243 // Check so you cant heal target that has max hp
244 if (selectedSkill &&
245 (selectedSkill->skillType == SkillType::Heal || selectedSkill->skillType == SkillType::MultiHeal))
246 {
247 bool canHealAnyTarget = false;
248 for (BattleParticipant* target : targets)
249 {
250 if (target->hp < target->maxHp)
251 {
252 canHealAnyTarget = true;
253 break;
254 }
255 }
256 if (!canHealAnyTarget)
257 {
258 return;
259 }
260 }
261
262 bool usingBaseAttack = selectedSkill == actor->baseAttackAction;
263
264 for (BattleParticipant* target : targets)
265 {
266 TurnResult turnResult =
267 (usingBaseAttack) ? attack.resolve(actor, target) : persona.resolve(actor, target, selectedSkill);
268 applyResult(turnResult, target);
269 }
270
271 advanceTurn();
272 }
273
274 if (battleMenuCmpt->consumeCancel())
275 {
278 }
279 break;
280 }
281
283 {
284 battleMenuCmpt->loadAllOutAttackConfirmation();
286 selectedBattleOption = battleMenuCmpt->consumeSelectedBattleOption();
287
288 if (selectedBattleOption != -1)
289 {
291
292 //if yes
293 if (selectedBattleOption == 0)
294 {
295 etl::vector<BattleParticipant*, 13> aliveEnemies = getAliveEnemies();
296
297 uint8_t participantCount = 0;
298 for (PartyMember* partyMember : partyMembers)
299 {
300 if (partyMember->canParticipateInAllOutAttack())
301 {
302 participantCount++;
303 }
304 }
305
306 for (BattleParticipant* enemy : aliveEnemies)
307 {
308 u32 damage = BattleCalcs::allOutAttack(*player, *enemy, participantCount);
309 enemy->knockedDown = false;
310 TurnResult turnResult = {true, -(s32)damage, false, enemy->name + ": "};
311 applyResult(turnResult, enemy);
312 }
313
314 advanceTurn();
315 } //no
316 else
317 {
318 currentParticipantTurn->oneMore = false;
319 battleMenuCmpt->resetLoadedOptions();
321 }
322 }
323 break;
324 }
325
327 {
328 battleMenuCmpt->loadAlertOptions(pendingAlert);
329 if (battleMenuCmpt->isAlertExpired(120))
330 {
331 pendingAlert.clear();
332 battleMenuCmpt->resetLoadedOptions();
334 }
335 break;
336 }
337
339 {
340 Enemy* enemy = static_cast<Enemy*>(currentParticipantTurn);
341 Skill* skill = enemy->pickSkill();
342 etl::vector<BattleParticipant*, 13> targets;
343 //TODO: branch in future if using healing / buff
344 for (PartyMember* partyMember : partyMembers)
345 {
346 targets.push_back(partyMember);
347 }
348
349 BattleParticipant* target = enemy->pickTarget(targets);
350 TurnResult turnResult = enemy->resolve(target, skill);
351 applyResult(turnResult, target);
352 advanceTurn();
353 //cant be set in advanceTurn, needs to be specifically cleared when an enemy has recoverd
355 break;
356 }
357
359 break;
360 }
361
362 return;
363}
364
366{
367 logMessage(LogSeverity::DEBUG, "Battle shutdown");
368
369 if (musicCmpt != nullptr)
370 {
371 musicCmpt->stopMusic();
372 }
373
374 active = false;
375
376 turnsTaken = 0;
378
379 currentParticipantTurn = nullptr;
380
381 selectedSkill = nullptr;
382
383 pendingAlert.clear();
384
385 pendingPersonaSwitch = false;
387 personaBeforeSwitch = nullptr;
388
390
391 for (BattleParticipant* participant : battleParticipants)
392 {
393 delete participant;
394 }
395
396 battleParticipants.clear();
397 partyMembers.clear();
398 enemies.clear();
399 player = nullptr;
400}
401
403{
404 musicCmpt = music;
405}
406
408{
409 if (!turnResult.log.empty())
410 {
411 pendingAlert += turnResult.log + "\n";
412 }
413
414 if (turnResult.hit && target && turnResult.hpDelta != 0)
415 {
416 s32 hpBefore = target->hp;
417 s32 actuallyHealedHp = turnResult.hpDelta;
418 target->hp += turnResult.hpDelta;
419
420 if (target->hp > target->maxHp)
421 {
422 target->hp = target->maxHp;
423 actuallyHealedHp = target->maxHp - hpBefore;
424 }
425
426 char buf[48];
427 if (turnResult.hpDelta < 0)
428 {
429 std::sprintf(buf, "Damage: %ld\n", (long)-turnResult.hpDelta);
430 }
431 else
432 {
433 std::sprintf(buf, "HP healed: %ld\n", (long)actuallyHealedHp);
434 }
435 pendingAlert += buf;
436
437 std::sprintf(buf, "%s HP: %ld\n", target->name.c_str(), (long)target->hp);
438 pendingAlert += buf;
439 }
440
441 if (turnResult.oneMore)
442 {
443 pendingAlert += "One More!\n";
444 currentParticipantTurn->oneMore = true;
445 }
446}
447
449{
451
452 //all out attack availability check
454 {
456 battleMenuCmpt->resetLoadedOptions();
458 return;
459 }
460
461 pendingAlert += "Previous attacker: " + currentParticipantTurn->name + "\n";
462
463 selectedSkill = nullptr;
464
466 pendingPersonaSwitch = false;
467
468 if (currentParticipantTurn->oneMore)
469 {
470 currentParticipantTurn->oneMore = false;
471 BattlePhase nextPhase = currentParticipantTurn->getInitalTurnPhase();
472
473 setNextPhase(nextPhase);
474 return;
475 }
476
478 personaBeforeSwitch = nullptr;
479
480 currentParticipantTurn->knockedDown = false;
481
482 if (battleParticipants.empty())
483 {
484 logMessage(LogSeverity::ERROR, "No battle participants");
485 shutdown();
486 return;
487 }
488
489 u32 next = (currentParticipantIndex + 1) % battleParticipants.size();
490 u32 checked = 0;
491 while (battleParticipants.at(next)->hp <= 0 && checked < battleParticipants.size())
492 {
493 next = (next + 1) % battleParticipants.size();
494 checked++;
495 }
496
497 if (checked >= battleParticipants.size())
498 {
499 logMessage(LogSeverity::WARNING, "Found no living battle participants");
500 shutdown();
501 return;
502 }
503
505 turnsTaken++;
507
508 logMessage(LogSeverity::DEBUG, "Turn advanced to: " + currentParticipantTurn->name);
509
511 BattlePhase nextPhase = currentParticipantTurn->getInitalTurnPhase();
512
513 setNextPhase(nextPhase);
514}
515
517{
518 if (!pendingAlert.empty())
519 {
520 alertReturnPhase = nextPhase;
521 battleMenuCmpt->resetLoadedOptions();
523 }
524 else
525 {
526 phase = nextPhase;
527 }
528}
529
530// TODO:: potentially rework since this would do a double turn if called again after 1st turn
532{
533 // random boost from 1.2 to 1.4 that priorizes party
534 ae::q20_12_t boost = ae::q20_12_t{1.2} + MathManager::getInstance().randFrac() * ae::q20_12_t{0.2};
535
536 for (BattleParticipant* battleParticipant : battleParticipants)
537 {
538 battleParticipant->setCurrentTurnOrderAgility(boost);
539 }
540
542 std::sort(enemies.begin(), enemies.end(), getParticipantByHigherAgility);
543
544 battleParticipants.clear();
545
547 {
548 for (auto p : partyMembers)
549 {
550 battleParticipants.push_back(p);
551 }
552 for (auto e : enemies)
553 {
554 battleParticipants.push_back(e);
555 }
556 }
558 {
559 for (auto e : enemies)
560 {
561 battleParticipants.push_back(e);
562 }
563 for (auto p : partyMembers)
564 {
565 battleParticipants.push_back(p);
566 }
567 }
568 else
569 {
570 std::merge(partyMembers.begin(),
571 partyMembers.end(),
572 enemies.begin(),
573 enemies.end(),
574 std::back_inserter(battleParticipants),
576 }
577}
578
580{
581 for (u32 i = 0; i < battleParticipants.size(); i++)
582 {
583 if (battleParticipants.at(i)->hp > 0)
584 {
585 continue;
586 }
587
589
590 dead->onDead(battleResult);
591
592 if (battleResult.playerDied)
593 {
595 shutdown();
596 return;
597 }
598 }
599
600 bool enemiesAlive = false;
601 for (BattleParticipant* enemy : enemies)
602 {
603 if (enemy->hp > 0)
604 {
605 enemiesAlive = true;
606 break;
607 }
608 }
609
610 if (!enemiesAlive)
611 {
613 ae::broadcastEvent(battleResult);
614 shutdown();
615 return;
616 }
617}
618
619etl::vector<BattleParticipant*, 13> BattleSystem::getAliveEnemies()
620{
621 etl::vector<BattleParticipant*, 13> alive;
622 for (BattleParticipant* enemy : enemies)
623 {
624 if (enemy->hp > 0)
625 {
626 alive.push_back(enemy);
627 }
628 }
629 return alive;
630}
631
633{
634 uint8_t aliveCount = 0;
635 uint8_t knockedDownCount = 0;
636 for (BattleParticipant* enemy : enemies)
637 {
638 if (enemy->hp > 0)
639 {
640 aliveCount++;
641 if (enemy->knockedDown)
642 {
643 knockedDownCount++;
644 }
645 }
646 }
647
648 if (knockedDownCount >= aliveCount)
649 {
650 return true;
651 }
652
653 return false;
654}
655
657{
658 switch (type)
659 {
662 case SkillType::Heal:
663 case SkillType::Buff:
665 return true;
666 default:
667 return false;
668 }
669}
BattlePhase
System for managing battle logic & states.
SkillType
Definition SkillType.hpp:4
@ RegularAttack
Definition SkillType.hpp:5
@ MASS_DESTRUCTION
Definition audioDb.hpp:27
static BattleMenu * getInstance()
etl::vector< PartyMember *, 4 > partyMembers
void init() override
BattlePhase phase
PersonaBase * personaBeforeSwitch
bool allEnemiesKnockedDown()
Evaluates if an All-Out Attack condition is met.
void calculateTurnOrder()
Calculates the initial turn queue at the start of an encounter.
void shutdown() override
bool allOutAttackWasPossibleThisKnockDown
static constexpr u32 ACTION_PERSONA
std::string pendingAlert
BattlePhase alertReturnPhase
etl::vector< BattleParticipant *, 13 > battleParticipants
void setMusicComponent(MusicComponent *music)
static bool getParticipantByHigherAgility(BattleParticipant *a, BattleParticipant *b)
Sorting predicate used to order combatants by agility.
bool isSingleTarget(SkillType type)
Determines if a skill targets a single entity.
static constexpr u32 ACTION_GUARD
Skill * selectedSkill
u32 currentParticipantIndex
void handleDeadParticipants()
Sweeps the field for dead participants and evaluates encounter end conditions.
void advanceTurn()
Progresses the battle state machine to the next logical step.
BattleStartCondition battleStartCondition
void on_receive(const Event::ExecuteBattle &msg)
ETL message handler that initializes and starts a new battle.
bool switchedPersonaThisTurn
void update(ae::q20_12_t) override
Core update loop that processes the battle state machine and turn resolution.
etl::vector< BattleParticipant *, 13 > getAliveEnemies()
Filters the enemy roster for living combatants.
PersonaAction persona
void setNextPhase(BattlePhase nextPhase)
Safely transitions the state machine to a new BattlePhase.
BattleParticipant * currentParticipantTurn
static constexpr u32 ACTION_SWITCH
std::array< ActionBase *, 4 > actions
AttackAction attack
bool pendingPersonaSwitch
static constexpr u32 ACTION_ATTACK
etl::vector< Enemy *, 8 > enemies
BattleMenu * battleMenuCmpt
Event::BattleResult battleResult
MusicComponent * musicCmpt
void applyResult(const TurnResult &r, BattleParticipant *target=nullptr)
Resolves the mathematical and state changes of a combat action against a target.
void logMessage(LogSeverity severity, std::string_view message, std::source_location location)
Logs a diagnostic message and halts only for fatal messages.
Definition logger.cpp:110
Util to handle error logging.
static u32 allOutAttack(Player &attacker, BattleParticipant &defender, u32 participantCount)
Calculates damage of an All out attack.
Participant of battle.
virtual void onDead(Event::BattleResult &battleResult)=0
Holds character data which a battleParticipant is created from.
Definition Enemy.hpp:9
BattleParticipant * pickTarget(etl::vector< BattleParticipant *, 13 > &partyMembers)
Definition Enemy.cpp:34
TurnResult resolve(BattleParticipant *target, Skill *skill)
Definition Enemy.cpp:66
Skill * pickSkill()
Definition Enemy.cpp:28
Holds data on how the battle concluded.
Event payload to start the BattleSystem.
etl::vector< CharacterProfile, 4 > & characterProfiles
All party members currently on the field.
CharacterProfile & player
The main player character. We need to specifically know them for some things all the time.
BattleStartCondition battleStartCondition
Condition like player advantage, enemy advantage, or even. Used to decide turn order.
etl::vector< EnemyProfile, 8 > & enemyProfiles
All enemies currently on the field.
etl::vector< PersonaBase *, 13 > personas
virtual bool actorCanUse(ActionBase *action)
PersonaBase * curPersona
std::string name
Skill ** skills
s32 cost
Definition Skill.hpp:12
SkillRace skillRace
Definition Skill.hpp:17
Result of a singular turn. Note that currently multi target skills do use a seperate turn result for ...
std::string log