Used ClangFormat style guide I'm happy with.
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Deukhoofd 2019-11-28 12:55:22 +01:00
parent 3b685ae782
commit a8730d983f
Signed by: Deukhoofd
GPG Key ID: ADF2E9256009EDCE
91 changed files with 946 additions and 1121 deletions

121
.clang-format Normal file
View File

@ -0,0 +1,121 @@
# ClangFormatConfigureSource: 'LLVM'
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Merge
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 1
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
...

View File

@ -5,31 +5,26 @@
#include <vector> #include <vector>
#include "../TurnChoices/BaseTurnChoice.hpp" #include "../TurnChoices/BaseTurnChoice.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ChoiceQueue { class ChoiceQueue {
std::vector<BaseTurnChoice*> _queue; std::vector<BaseTurnChoice*> _queue;
size_t _current = 0; size_t _current = 0;
public: public:
bool HasCompletedQueue = false; bool HasCompletedQueue = false;
explicit ChoiceQueue(std::vector<BaseTurnChoice*> queue) explicit ChoiceQueue(std::vector<BaseTurnChoice*> queue) : _queue(std::move(queue)) {}
:_queue(std::move(queue)){}
BaseTurnChoice* Dequeue(){ BaseTurnChoice* Dequeue() {
auto b = _queue[_current]; auto b = _queue[_current];
_current++; _current++;
return b; return b;
} }
[[nodiscard]] bool HasNext() const{ [[nodiscard]] bool HasNext() const { return _current < _queue.size(); }
return _current < _queue.size();
}
std::vector<BaseTurnChoice*>& GetInnerQueue(){ std::vector<BaseTurnChoice*>& GetInnerQueue() { return _queue; }
return _queue;
}
}; };
} }
#endif // CREATURELIB_CHOICEQUEUE_HPP
#endif //CREATURELIB_CHOICEQUEUE_HPP

View File

@ -1,16 +1,16 @@
#include "TurnHandler.hpp" #include "TurnHandler.hpp"
#include "../Models/Battle.hpp"
#include "../../Core/Exceptions/NotImplementedException.hpp" #include "../../Core/Exceptions/NotImplementedException.hpp"
#include "../Models/Battle.hpp"
#include "../ScriptHandling/ScriptMacros.cpp" #include "../ScriptHandling/ScriptMacros.cpp"
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
void TurnHandler::RunTurn(Battle* battle, ChoiceQueue* queue) { void TurnHandler::RunTurn(Battle* battle, ChoiceQueue* queue) {
for (auto choice: queue->GetInnerQueue()){ for (auto choice : queue->GetInnerQueue()) {
HOOK(OnBeforeTurn, choice, choice); HOOK(OnBeforeTurn, choice, choice);
} }
while (queue->HasNext()){ while (queue->HasNext()) {
if (!battle->HasRecalledSlots()){ if (!battle->HasRecalledSlots()) {
return; return;
} }
auto item = queue->Dequeue(); auto item = queue->Dequeue();
@ -20,9 +20,8 @@ void TurnHandler::RunTurn(Battle* battle, ChoiceQueue* queue) {
queue->HasCompletedQueue = true; queue->HasCompletedQueue = true;
} }
void TurnHandler::ExecuteChoice(BaseTurnChoice *choice) { void TurnHandler::ExecuteChoice(BaseTurnChoice* choice) {
if (choice == nullptr) if (choice == nullptr) {
{
return; return;
} }
auto choiceKind = choice->GetKind(); auto choiceKind = choice->GetKind();
@ -31,35 +30,33 @@ void TurnHandler::ExecuteChoice(BaseTurnChoice *choice) {
} }
auto user = choice->GetUser(); auto user = choice->GetUser();
// If the user is fainted, we don't want to execute its choice. // If the user is fainted, we don't want to execute its choice.
if (user->IsFainted()){ if (user->IsFainted()) {
return; return;
} }
auto battle = user->GetBattle(); auto battle = user->GetBattle();
// If the user is not in the field, we don't want to execute its choice. // If the user is not in the field, we don't want to execute its choice.
if (!battle->CreatureInField(user)){ if (!battle->CreatureInField(user)) {
return; return;
} }
// If the choice is not valid, we don't want to execute it. // If the choice is not valid, we don't want to execute it.
if (!battle->CanUse(choice)){ if (!battle->CanUse(choice)) {
return; return;
} }
switch (choiceKind){ switch (choiceKind) {
case TurnChoiceKind::Pass: throw NotReachableException(); case TurnChoiceKind::Pass: throw NotReachableException();
case TurnChoiceKind::Attack: case TurnChoiceKind::Attack: return ExecuteAttackChoice(dynamic_cast<AttackTurnChoice*>(choice));
return ExecuteAttackChoice(dynamic_cast<AttackTurnChoice*>(choice));
case TurnChoiceKind::Item: case TurnChoiceKind::Item:
case TurnChoiceKind::Switch: case TurnChoiceKind::Switch:
case TurnChoiceKind::RunAway: case TurnChoiceKind::RunAway: throw NotImplementedException();
throw NotImplementedException();
} }
} }
void TurnHandler::ExecuteAttackChoice(AttackTurnChoice *choice) { void TurnHandler::ExecuteAttackChoice(AttackTurnChoice* choice) {
auto attackName = choice->GetAttack()->GetAttack()->GetName(); auto attackName = choice->GetAttack()->GetAttack()->GetName();
HOOK(ChangeAttack, choice, choice, attackName); HOOK(ChangeAttack, choice, choice, attackName);
if (attackName != choice->GetAttack()->GetAttack()->GetName()){ if (attackName != choice->GetAttack()->GetAttack()->GetName()) {
//TODO: Change attack // TODO: Change attack
} }
// FIXME: Resolve all targets // FIXME: Resolve all targets
@ -69,36 +66,37 @@ void TurnHandler::ExecuteAttackChoice(AttackTurnChoice *choice) {
auto attack = new ExecutingAttack(targets, 1, choice->GetUser(), choice->GetAttack(), choice->GetAttackScript()); auto attack = new ExecutingAttack(targets, 1, choice->GetUser(), choice->GetAttack(), choice->GetAttackScript());
bool prevented = false; bool prevented = false;
HOOK(PreventAttack, attack, attack, prevented); HOOK(PreventAttack, attack, attack, prevented);
if (prevented){ if (prevented) {
return; return;
} }
//HOOK: override targets // HOOK: override targets
if (!choice->GetAttack()->TryUse(1)){ if (!choice->GetAttack()->TryUse(1)) {
return; return;
} }
//HOOK: check if attack fails // HOOK: check if attack fails
bool fail = false; bool fail = false;
HOOK(FailAttack, attack, attack, fail); HOOK(FailAttack, attack, attack, fail);
if (fail){ if (fail) {
//TODO: Fail handling. // TODO: Fail handling.
return; return;
} }
HOOK(StopBeforeAttack, attack, attack); HOOK(StopBeforeAttack, attack, attack);
HOOK(OnBeforeAttack, attack, attack); HOOK(OnBeforeAttack, attack, attack);
for (auto& kv: attack->GetTargets()){ for (auto& kv : attack->GetTargets()) {
HandleAttackForTarget(attack, kv.first, kv.second); HandleAttackForTarget(attack, kv.first, kv.second);
} }
//TODO: We currently delete this, but we probably want to store this in a log, so scripts can look it up. // TODO: We currently delete this, but we probably want to store this in a log, so scripts can look it up.
delete attack; delete attack;
} }
void TurnHandler::HandleAttackForTarget(ExecutingAttack* attack, Creature *target, const ExecutingAttack::TargetData &targetData) { void TurnHandler::HandleAttackForTarget(ExecutingAttack* attack, Creature* target,
const ExecutingAttack::TargetData& targetData) {
auto user = attack->GetUser(); auto user = attack->GetUser();
ScriptSource* targetSource = target; ScriptSource* targetSource = target;
@ -106,19 +104,19 @@ void TurnHandler::HandleAttackForTarget(ExecutingAttack* attack, Creature *targe
bool fail = false; bool fail = false;
HOOK(FailIncomingAttack, targetSource, attack, target, fail); HOOK(FailIncomingAttack, targetSource, attack, target, fail);
if (fail){ if (fail) {
//TODO: Fail handling. // TODO: Fail handling.
return; return;
} }
bool invulnerable = fail; bool invulnerable = fail;
HOOK(IsInvulnerable, targetSource, attack, target, invulnerable); HOOK(IsInvulnerable, targetSource, attack, target, invulnerable);
if (invulnerable){ if (invulnerable) {
//TODO: We should probably do something when a target is invulnerable. // TODO: We should probably do something when a target is invulnerable.
return; return;
} }
if (!targetData.IsHit()){ if (!targetData.IsHit()) {
HOOK(OnAttackMiss, targetSource, attack, target); HOOK(OnAttackMiss, targetSource, attack, target);
return; return;
} }
@ -129,11 +127,11 @@ void TurnHandler::HandleAttackForTarget(ExecutingAttack* attack, Creature *targe
auto attackData = attack->GetAttack()->GetAttack(); auto attackData = attack->GetAttack()->GetAttack();
auto library = user->GetBattle()->GetLibrary(); auto library = user->GetBattle()->GetLibrary();
auto dmgLibrary = library->GetDamageLibrary(); auto dmgLibrary = library->GetDamageLibrary();
for (uint8_t hitIndex = 0; hitIndex < numHits; hitIndex++){ for (uint8_t hitIndex = 0; hitIndex < numHits; hitIndex++) {
if (user->IsFainted()){ if (user->IsFainted()) {
break; break;
} }
if (target->IsFainted()){ if (target->IsFainted()) {
// STOP, STOP! HE'S ALREADY DEAD ;_; // STOP, STOP! HE'S ALREADY DEAD ;_;
break; break;
} }
@ -146,28 +144,27 @@ void TurnHandler::HandleAttackForTarget(ExecutingAttack* attack, Creature *targe
hit.SetBasePower(dmgLibrary->GetBasePower(attack, target, hitIndex)); hit.SetBasePower(dmgLibrary->GetBasePower(attack, target, hitIndex));
hit.SetDamage(dmgLibrary->GetDamage(attack, target, hitIndex)); hit.SetDamage(dmgLibrary->GetDamage(attack, target, hitIndex));
if (attackData->GetCategory() == Library::AttackCategory::Status){ if (attackData->GetCategory() == Library::AttackCategory::Status) {
HOOK(OnStatusMove, userSource, attack, target, hitIndex); HOOK(OnStatusMove, userSource, attack, target, hitIndex);
} } else {
else{
auto damage = hit.GetDamage(); auto damage = hit.GetDamage();
if (damage > target->GetCurrentHealth()){ if (damage > target->GetCurrentHealth()) {
damage = target->GetCurrentHealth(); damage = target->GetCurrentHealth();
hit.SetDamage(damage); hit.SetDamage(damage);
} }
if (damage > 0){ if (damage > 0) {
target->Damage(damage, DamageSource::AttackDamage); target->Damage(damage, DamageSource::AttackDamage);
bool preventSecondary = false; bool preventSecondary = false;
HOOK(PreventSecondaryEffects, targetSource, attack, target, hitIndex, preventSecondary); HOOK(PreventSecondaryEffects, targetSource, attack, target, hitIndex, preventSecondary);
if (!preventSecondary){ if (!preventSecondary) {
HOOK(OnSecondaryEffect, userSource, attack, target, hitIndex); HOOK(OnSecondaryEffect, userSource, attack, target, hitIndex);
} }
} }
} }
} }
if (!user->IsFainted()){ if (!user->IsFainted()) {
HOOK(OnAfterHits, userSource, attack, target); HOOK(OnAfterHits, userSource, attack, target);
} }
} }

View File

@ -1,9 +1,9 @@
#ifndef CREATURELIB_TURNHANDLER_HPP #ifndef CREATURELIB_TURNHANDLER_HPP
#define CREATURELIB_TURNHANDLER_HPP #define CREATURELIB_TURNHANDLER_HPP
#include "ChoiceQueue.hpp"
#include "../TurnChoices/AttackTurnChoice.hpp"
#include "../Models/ExecutingAttack.hpp" #include "../Models/ExecutingAttack.hpp"
#include "../TurnChoices/AttackTurnChoice.hpp"
#include "ChoiceQueue.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class Battle; class Battle;
@ -12,10 +12,12 @@ namespace CreatureLib::Battling {
static void ExecuteChoice(BaseTurnChoice* choice); static void ExecuteChoice(BaseTurnChoice* choice);
static void ExecuteAttackChoice(AttackTurnChoice* choice); static void ExecuteAttackChoice(AttackTurnChoice* choice);
static void HandleAttackForTarget(ExecutingAttack* attack, Creature* target, const ExecutingAttack::TargetData& targetData); static void HandleAttackForTarget(ExecutingAttack* attack, Creature* target,
const ExecutingAttack::TargetData& targetData);
public: public:
static void RunTurn(Battle* battle, ChoiceQueue* queue); static void RunTurn(Battle* battle, ChoiceQueue* queue);
}; };
} }
#endif //CREATURELIB_TURNHANDLER_HPP #endif // CREATURELIB_TURNHANDLER_HPP

View File

@ -1,18 +1,17 @@
#include "TurnOrdering.hpp" #include "TurnOrdering.hpp"
#include "../TurnChoices/AttackTurnChoice.hpp"
#include "../Models/Battle.hpp"
#include <algorithm> #include <algorithm>
#include "../Models/Battle.hpp"
#include "../TurnChoices/AttackTurnChoice.hpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace Battling; using namespace Battling;
bool ___ChoiceOrderFunc(const BaseTurnChoice* a, const BaseTurnChoice* b, Core::Random& rand){ bool ___ChoiceOrderFunc(const BaseTurnChoice* a, const BaseTurnChoice* b, Core::Random& rand) {
auto aKind = a->GetKind(); auto aKind = a->GetKind();
auto bKind = b->GetKind(); auto bKind = b->GetKind();
if (aKind != bKind) if (aKind != bKind)
return aKind > bKind; return aKind > bKind;
if (aKind == TurnChoiceKind::Attack){ if (aKind == TurnChoiceKind::Attack) {
auto aPriority = dynamic_cast<const AttackTurnChoice*>(a)->GetPriority(); auto aPriority = dynamic_cast<const AttackTurnChoice*>(a)->GetPriority();
auto bPriority = dynamic_cast<const AttackTurnChoice*>(b)->GetPriority(); auto bPriority = dynamic_cast<const AttackTurnChoice*>(b)->GetPriority();
if (aPriority != bPriority) if (aPriority != bPriority)
@ -27,9 +26,9 @@ bool ___ChoiceOrderFunc(const BaseTurnChoice* a, const BaseTurnChoice* b, Core::
return randomValue == 0; return randomValue == 0;
} }
void TurnOrdering::OrderChoices(std::vector<BaseTurnChoice *> &vec, Core::Random& rand) { void TurnOrdering::OrderChoices(std::vector<BaseTurnChoice*>& vec, Core::Random& rand) {
auto comp = [&](const BaseTurnChoice * a,const BaseTurnChoice * b)-> bool { auto comp = [&](const BaseTurnChoice* a, const BaseTurnChoice* b) -> bool {
return ___ChoiceOrderFunc(a,b,rand); return ___ChoiceOrderFunc(a, b, rand);
}; };
std::sort(vec.begin(), vec.end(), comp); std::sort(vec.begin(), vec.end(), comp);
} }

View File

@ -1,9 +1,9 @@
#ifndef CREATURELIB_TURNORDERING_HPP #ifndef CREATURELIB_TURNORDERING_HPP
#define CREATURELIB_TURNORDERING_HPP #define CREATURELIB_TURNORDERING_HPP
#include "../TurnChoices/BaseTurnChoice.hpp"
#include "../../Core/Random.hpp"
#include <vector> #include <vector>
#include "../../Core/Random.hpp"
#include "../TurnChoices/BaseTurnChoice.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class TurnOrdering { class TurnOrdering {
@ -12,4 +12,4 @@ namespace CreatureLib::Battling {
}; };
} }
#endif //CREATURELIB_TURNORDERING_HPP #endif // CREATURELIB_TURNORDERING_HPP

View File

@ -1,16 +1,13 @@
#include <cassert>
#include "BattleLibrary.hpp" #include "BattleLibrary.hpp"
#include <cassert>
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
BattleLibrary::BattleLibrary(CreatureLib::Library::DataLibrary *staticLib, BattleLibrary::BattleLibrary(CreatureLib::Library::DataLibrary* staticLib, BattleStatCalculator* statCalculator,
BattleStatCalculator *statCalculator, DamageLibrary* damageLibrary, CriticalLibrary* criticalLibrary,
DamageLibrary* damageLibrary, ScriptResolver* scriptResolver)
CriticalLibrary* criticalLibrary, ScriptResolver* scriptResolver) : _staticLib(staticLib), _statCalculator(statCalculator), _damageLibrary(damageLibrary),
: _staticLib(staticLib), _statCalculator(statCalculator), _criticalLibrary(criticalLibrary), _scriptResolver(scriptResolver) {}
_damageLibrary(damageLibrary), _criticalLibrary(criticalLibrary),
_scriptResolver(scriptResolver)
{}
BattleLibrary::~BattleLibrary() { BattleLibrary::~BattleLibrary() {
delete _staticLib; delete _staticLib;
@ -20,40 +17,27 @@ BattleLibrary::~BattleLibrary() {
delete _scriptResolver; delete _scriptResolver;
} }
const CreatureLib::Library::LibrarySettings& BattleLibrary::GetSettings() const { const CreatureLib::Library::LibrarySettings& BattleLibrary::GetSettings() const { return _staticLib->GetSettings(); }
return _staticLib->GetSettings();
}
const BattleStatCalculator *BattleLibrary::GetStatCalculator() const { const BattleStatCalculator* BattleLibrary::GetStatCalculator() const { return _statCalculator; }
return _statCalculator;
}
const CreatureLib::Library::SpeciesLibrary* BattleLibrary::GetSpeciesLibrary() const { const CreatureLib::Library::SpeciesLibrary* BattleLibrary::GetSpeciesLibrary() const {
return _staticLib->GetSpeciesLibrary(); return _staticLib->GetSpeciesLibrary();
} }
const CreatureLib::Library::ItemLibrary* BattleLibrary::GetItemLibrary() const { const CreatureLib::Library::ItemLibrary* BattleLibrary::GetItemLibrary() const { return _staticLib->GetItemLibrary(); }
return _staticLib->GetItemLibrary();
}
const CreatureLib::Library::AttackLibrary *BattleLibrary::GetAttackLibrary() const { const CreatureLib::Library::AttackLibrary* BattleLibrary::GetAttackLibrary() const {
return _staticLib->GetAttackLibrary(); return _staticLib->GetAttackLibrary();
} }
const CreatureLib::Library::TypeLibrary *BattleLibrary::GetTypeLibrary() const { const CreatureLib::Library::TypeLibrary* BattleLibrary::GetTypeLibrary() const { return _staticLib->GetTypeLibrary(); }
return _staticLib->GetTypeLibrary();
}
const DamageLibrary *BattleLibrary::GetDamageLibrary() const { const DamageLibrary* BattleLibrary::GetDamageLibrary() const { return _damageLibrary; }
return _damageLibrary;
}
const CriticalLibrary *BattleLibrary::GetCriticalLibrary() const { const CriticalLibrary* BattleLibrary::GetCriticalLibrary() const { return _criticalLibrary; }
return _criticalLibrary;
}
Script* BattleLibrary::LoadScript(ScriptResolver::ScriptCategory category, const std::string &scriptName) { Script* BattleLibrary::LoadScript(ScriptResolver::ScriptCategory category, const std::string& scriptName) {
assert(this->_scriptResolver != nullptr); assert(this->_scriptResolver != nullptr);
return _scriptResolver->LoadScript(category, scriptName); return _scriptResolver->LoadScript(category, scriptName);
} }

View File

@ -1,11 +1,11 @@
#ifndef CREATURELIB_BATTLELIBRARY_HPP #ifndef CREATURELIB_BATTLELIBRARY_HPP
#define CREATURELIB_BATTLELIBRARY_HPP #define CREATURELIB_BATTLELIBRARY_HPP
#include "BattleStatCalculator.hpp"
#include "../../Library/DataLibrary.hpp" #include "../../Library/DataLibrary.hpp"
#include "DamageLibrary.hpp"
#include "CriticalLibrary.hpp"
#include "../ScriptHandling/ScriptResolver.hpp" #include "../ScriptHandling/ScriptResolver.hpp"
#include "BattleStatCalculator.hpp"
#include "CriticalLibrary.hpp"
#include "DamageLibrary.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class BattleLibrary { class BattleLibrary {
@ -14,9 +14,10 @@ namespace CreatureLib::Battling {
DamageLibrary* _damageLibrary; DamageLibrary* _damageLibrary;
CriticalLibrary* _criticalLibrary; CriticalLibrary* _criticalLibrary;
ScriptResolver* _scriptResolver; ScriptResolver* _scriptResolver;
public: public:
BattleLibrary(Library::DataLibrary* staticLib, BattleStatCalculator* statCalculator, DamageLibrary* damageLibrary, BattleLibrary(Library::DataLibrary* staticLib, BattleStatCalculator* statCalculator,
CriticalLibrary* criticalLibrary, ScriptResolver* scriptResolver); DamageLibrary* damageLibrary, CriticalLibrary* criticalLibrary, ScriptResolver* scriptResolver);
~BattleLibrary(); ~BattleLibrary();
[[nodiscard]] const Library::LibrarySettings& GetSettings() const; [[nodiscard]] const Library::LibrarySettings& GetSettings() const;
@ -33,4 +34,4 @@ namespace CreatureLib::Battling {
}; };
} }
#endif //CREATURELIB_BATTLELIBRARY_HPP #endif // CREATURELIB_BATTLELIBRARY_HPP

View File

@ -1,54 +1,49 @@
#include "BattleStatCalculator.hpp" #include "BattleStatCalculator.hpp"
#include "../Models/Creature.hpp"
#include "../../Core/Exceptions/NotImplementedException.hpp" #include "../../Core/Exceptions/NotImplementedException.hpp"
#include "../Models/Creature.hpp"
using namespace CreatureLib; using namespace CreatureLib;
Core::StatisticSet<uint32_t> Core::StatisticSet<uint32_t> Battling::BattleStatCalculator::CalculateFlatStats(Battling::Creature* creature) const {
Battling::BattleStatCalculator::CalculateFlatStats(Battling::Creature *creature) const { return Core::StatisticSet<uint32_t>(CalculateFlatStat(creature, Core::Statistic::Health),
return Core::StatisticSet<uint32_t>(
CalculateFlatStat(creature, Core::Statistic::Health),
CalculateFlatStat(creature, Core::Statistic::PhysicalAttack), CalculateFlatStat(creature, Core::Statistic::PhysicalAttack),
CalculateFlatStat(creature, Core::Statistic::PhysicalDefense), CalculateFlatStat(creature, Core::Statistic::PhysicalDefense),
CalculateFlatStat(creature, Core::Statistic::MagicalAttack), CalculateFlatStat(creature, Core::Statistic::MagicalAttack),
CalculateFlatStat(creature, Core::Statistic::MagicalDefense), CalculateFlatStat(creature, Core::Statistic::MagicalDefense),
CalculateFlatStat(creature, Core::Statistic::Speed) CalculateFlatStat(creature, Core::Statistic::Speed));
);
} }
Core::StatisticSet<uint32_t> Core::StatisticSet<uint32_t> Battling::BattleStatCalculator::CalculateBoostedStats(Battling::Creature* creature) const {
Battling::BattleStatCalculator::CalculateBoostedStats(Battling::Creature *creature) const { return Core::StatisticSet<uint32_t>(CalculateBoostedStat(creature, Core::Statistic::Health),
return Core::StatisticSet<uint32_t>(
CalculateBoostedStat(creature, Core::Statistic::Health),
CalculateBoostedStat(creature, Core::Statistic::PhysicalAttack), CalculateBoostedStat(creature, Core::Statistic::PhysicalAttack),
CalculateBoostedStat(creature, Core::Statistic::PhysicalDefense), CalculateBoostedStat(creature, Core::Statistic::PhysicalDefense),
CalculateBoostedStat(creature, Core::Statistic::MagicalAttack), CalculateBoostedStat(creature, Core::Statistic::MagicalAttack),
CalculateBoostedStat(creature, Core::Statistic::MagicalDefense), CalculateBoostedStat(creature, Core::Statistic::MagicalDefense),
CalculateBoostedStat(creature, Core::Statistic::Speed) CalculateBoostedStat(creature, Core::Statistic::Speed));
);
} }
uint32_t CalculateHealthStat(Battling::Creature *creature){ uint32_t CalculateHealthStat(Battling::Creature* creature) {
auto level = creature->GetLevel(); auto level = creature->GetLevel();
auto a = (creature->GetBaseStat(Core::Statistic::Health) + creature->GetStatPotential(Core::Statistic::Health)) * 2 + auto a =
(creature->GetBaseStat(Core::Statistic::Health) + creature->GetStatPotential(Core::Statistic::Health)) * 2 +
floor(sqrt(creature->GetStatExperience(Core::Statistic::Health) / 4)) * level; floor(sqrt(creature->GetStatExperience(Core::Statistic::Health) / 4)) * level;
return floor(a / 100) + level + 10; return floor(a / 100) + level + 10;
} }
uint32_t CalculateOtherStat(Battling::Creature *creature, Core::Statistic stat){ uint32_t CalculateOtherStat(Battling::Creature* creature, Core::Statistic stat) {
auto level = creature->GetLevel(); auto level = creature->GetLevel();
auto a = (creature->GetBaseStat(stat) + creature->GetStatPotential(stat)) * 2 + auto a = (creature->GetBaseStat(stat) + creature->GetStatPotential(stat)) * 2 +
floor(sqrt(creature->GetStatExperience(stat) / 4)) * level; floor(sqrt(creature->GetStatExperience(stat) / 4)) * level;
return floor(a / 100) + 10; return floor(a / 100) + 10;
} }
uint32_t Battling::BattleStatCalculator::CalculateFlatStat(Battling::Creature* creature, Core::Statistic stat) const {
uint32_t Battling::BattleStatCalculator::CalculateFlatStat(Battling::Creature *creature, Core::Statistic stat) const{
if (stat == Core::Statistic::Health) if (stat == Core::Statistic::Health)
return CalculateHealthStat(creature); return CalculateHealthStat(creature);
return CalculateOtherStat(creature, stat); return CalculateOtherStat(creature, stat);
} }
uint32_t Battling::BattleStatCalculator::CalculateBoostedStat(Battling::Creature *creature, Core::Statistic stat) const{ uint32_t Battling::BattleStatCalculator::CalculateBoostedStat(Battling::Creature* creature,
Core::Statistic stat) const {
throw NotImplementedException(); throw NotImplementedException();
} }

View File

@ -4,18 +4,18 @@
#include "../../Core/StatisticSet.hpp" #include "../../Core/StatisticSet.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
//predeclare BattleCreature class // predeclare BattleCreature class
class Creature; class Creature;
class BattleStatCalculator { class BattleStatCalculator {
public: public:
virtual ~BattleStatCalculator() = default; virtual ~BattleStatCalculator() = default;
virtual Core::StatisticSet<uint32_t > CalculateFlatStats(Creature* creature) const; virtual Core::StatisticSet<uint32_t> CalculateFlatStats(Creature* creature) const;
virtual Core::StatisticSet<uint32_t > CalculateBoostedStats(Creature* creature) const; virtual Core::StatisticSet<uint32_t> CalculateBoostedStats(Creature* creature) const;
virtual uint32_t CalculateFlatStat(Creature* creature, Core::Statistic stat) const; virtual uint32_t CalculateFlatStat(Creature* creature, Core::Statistic stat) const;
virtual uint32_t CalculateBoostedStat(Creature* creature, Core::Statistic stat) const; virtual uint32_t CalculateBoostedStat(Creature* creature, Core::Statistic stat) const;
}; };
} }
#endif //CREATURELIB_BATTLESTATCALCULATOR_HPP #endif // CREATURELIB_BATTLESTATCALCULATOR_HPP

View File

@ -1,9 +1,9 @@
#include "CriticalLibrary.hpp" #include "CriticalLibrary.hpp"
#include "../Models/Battle.hpp" #include "../Models/Battle.hpp"
bool CreatureLib::Battling::CriticalLibrary::IsCritical(CreatureLib::Battling::ExecutingAttack *attack, bool CreatureLib::Battling::CriticalLibrary::IsCritical(CreatureLib::Battling::ExecutingAttack* attack,
CreatureLib::Battling::Creature *target, uint8_t hit) const { CreatureLib::Battling::Creature* target, uint8_t hit) const {
auto rand = target->GetBattle()->GetRandom(); auto rand = target->GetBattle()->GetRandom();
//HOOK: Increase chance for critical hits. // HOOK: Increase chance for critical hits.
return rand.Get(10) <= 0; return rand.Get(10) <= 0;
} }

View File

@ -11,5 +11,4 @@ namespace CreatureLib::Battling {
}; };
} }
#endif // CREATURELIB_CRITICALLIBRARY_HPP
#endif //CREATURELIB_CRITICALLIBRARY_HPP

View File

@ -1,66 +1,64 @@
#include "DamageLibrary.hpp" #include "DamageLibrary.hpp"
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
int DamageLibrary::GetDamage(ExecutingAttack *attack, Creature *target, uint8_t hitIndex) const{ int DamageLibrary::GetDamage(ExecutingAttack* attack, Creature* target, uint8_t hitIndex) const {
auto levelMod = static_cast<float>(2 * attack->GetUser()->GetLevel()); auto levelMod = static_cast<float>(2 * attack->GetUser()->GetLevel());
auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex); auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex);
auto bp = hit.GetBasePower(); auto bp = hit.GetBasePower();
auto statMod = GetStatModifier(attack, target, hitIndex); auto statMod = GetStatModifier(attack, target, hitIndex);
//HOOK: Modify stat modifier // HOOK: Modify stat modifier
int damage = static_cast<int>((((levelMod * static_cast<float>(bp) * statMod) / 50) + 2) int damage = static_cast<int>((((levelMod * static_cast<float>(bp) * statMod) / 50) + 2) *
* GetDamageModifier(attack, target, hitIndex)); GetDamageModifier(attack, target, hitIndex));
//HOOK: Override damage // HOOK: Override damage
return damage; return damage;
} }
int DamageLibrary::GetBasePower(ExecutingAttack *attack, Creature *target, uint8_t hitIndex) const{ int DamageLibrary::GetBasePower(ExecutingAttack* attack, Creature* target, uint8_t hitIndex) const {
auto bp = attack->GetAttack()->GetAttack()->GetBasePower(); auto bp = attack->GetAttack()->GetAttack()->GetBasePower();
//HOOK: modify base power. // HOOK: modify base power.
return bp; return bp;
} }
float DamageLibrary::GetStatModifier(ExecutingAttack *attack, Creature *target, uint8_t hitIndex) const{ float DamageLibrary::GetStatModifier(ExecutingAttack* attack, Creature* target, uint8_t hitIndex) const {
auto user = attack->GetUser(); auto user = attack->GetUser();
//HOOK: allow overriding for which users stat we use. // HOOK: allow overriding for which users stat we use.
auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex); auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex);
Core::Statistic offensiveStat; Core::Statistic offensiveStat;
Core::Statistic defensiveStat; Core::Statistic defensiveStat;
if (attack->GetAttack()->GetAttack()->GetCategory() == Library::AttackCategory::Physical){ if (attack->GetAttack()->GetAttack()->GetCategory() == Library::AttackCategory::Physical) {
offensiveStat = Core::Statistic::PhysicalAttack; offensiveStat = Core::Statistic::PhysicalAttack;
defensiveStat = Core::Statistic::PhysicalDefense; defensiveStat = Core::Statistic::PhysicalDefense;
} } else {
else{
offensiveStat = Core::Statistic::MagicalAttack; offensiveStat = Core::Statistic::MagicalAttack;
defensiveStat = Core::Statistic::MagicalDefense; defensiveStat = Core::Statistic::MagicalDefense;
} }
auto bypassDefensive = hit.IsCritical() && target->GetStatBoost(defensiveStat) > 0; auto bypassDefensive = hit.IsCritical() && target->GetStatBoost(defensiveStat) > 0;
//HOOK: allow bypassing defensive stat modifiers. // HOOK: allow bypassing defensive stat modifiers.
auto bypassOffensive = hit.IsCritical() && user->GetStatBoost(offensiveStat) < 0; auto bypassOffensive = hit.IsCritical() && user->GetStatBoost(offensiveStat) < 0;
//HOOK: Allow bypassing offensive stat modifiers. // HOOK: Allow bypassing offensive stat modifiers.
float offensiveValue; float offensiveValue;
float defensiveValue; float defensiveValue;
if (bypassOffensive){ if (bypassOffensive) {
offensiveValue = user->GetFlatStat(offensiveStat); offensiveValue = user->GetFlatStat(offensiveStat);
} else{ } else {
offensiveValue = user->GetBoostedStat(offensiveStat); offensiveValue = user->GetBoostedStat(offensiveStat);
} }
if (bypassDefensive){ if (bypassDefensive) {
defensiveValue = target->GetFlatStat(defensiveStat); defensiveValue = target->GetFlatStat(defensiveStat);
} else{ } else {
defensiveValue = target->GetBoostedStat(defensiveStat); defensiveValue = target->GetBoostedStat(defensiveStat);
} }
return offensiveValue / defensiveValue; return offensiveValue / defensiveValue;
} }
float DamageLibrary::GetDamageModifier(ExecutingAttack *attack, Creature *target, uint8_t hitIndex) const{ float DamageLibrary::GetDamageModifier(ExecutingAttack* attack, Creature* target, uint8_t hitIndex) const {
float mod = 1; float mod = 1;
auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex); auto hit = attack->GetAttackDataForTarget(target).GetHit(hitIndex);
mod *= hit.GetEffectiveness(); mod *= hit.GetEffectiveness();
//HOOK: Modify damage modifier. // HOOK: Modify damage modifier.
return mod; return mod;
} }

View File

@ -4,7 +4,7 @@
#include "../Models/Creature.hpp" #include "../Models/Creature.hpp"
#include "../Models/ExecutingAttack.hpp" #include "../Models/ExecutingAttack.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class DamageLibrary { class DamageLibrary {
public: public:
virtual ~DamageLibrary() = default; virtual ~DamageLibrary() = default;
@ -16,5 +16,4 @@ namespace CreatureLib::Battling{
}; };
} }
#endif // CREATURELIB_DAMAGELIBRARY_HPP
#endif //CREATURELIB_DAMAGELIBRARY_HPP

View File

@ -2,10 +2,7 @@
#define CREATURELIB_ATTACKLEARNMETHOD_HPP #define CREATURELIB_ATTACKLEARNMETHOD_HPP
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
enum class AttackLearnMethod { enum class AttackLearnMethod { Unknown, Level };
Unknown,
Level
};
} }
#endif //CREATURELIB_ATTACKLEARNMETHOD_HPP #endif // CREATURELIB_ATTACKLEARNMETHOD_HPP

View File

@ -1,25 +1,22 @@
#include "Battle.hpp" #include "Battle.hpp"
#include "../Flow/TurnHandler.hpp"
#include "../TurnChoices/AttackTurnChoice.hpp"
#include "../Flow/TurnOrdering.hpp"
#include "../../Core/Exceptions/NotImplementedException.hpp" #include "../../Core/Exceptions/NotImplementedException.hpp"
#include "../Flow/TurnHandler.hpp"
#include "../Flow/TurnOrdering.hpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
const BattleLibrary *Battle::GetLibrary() const { const BattleLibrary* Battle::GetLibrary() const { return _library; }
return _library;
}
bool Battle::CanUse(const BaseTurnChoice *choice) { bool Battle::CanUse(const BaseTurnChoice* choice) {
if (choice->GetKind() == TurnChoiceKind::Attack){ if (choice->GetKind() == TurnChoiceKind::Attack) {
//HOOK: change number of uses needed. // HOOK: change number of uses needed.
return dynamic_cast<const AttackTurnChoice*>(choice)->GetAttack()->GetRemainingUses() > 1; return dynamic_cast<const AttackTurnChoice*>(choice)->GetAttack()->GetRemainingUses() > 1;
} }
return true; return true;
} }
bool Battle::TrySetChoice(BaseTurnChoice *choice) { bool Battle::TrySetChoice(BaseTurnChoice* choice) {
if (!CanUse(choice)) if (!CanUse(choice))
return false; return false;
choice->GetUser()->GetBattleSide()->SetChoice(choice); choice->GetUser()->GetBattleSide()->SetChoice(choice);
@ -28,24 +25,24 @@ bool Battle::TrySetChoice(BaseTurnChoice *choice) {
} }
void Battle::CheckChoicesSetAndRun() { void Battle::CheckChoicesSetAndRun() {
for (auto side: _sides){ for (auto side : _sides) {
if (!side->AllChoicesSet()){ if (!side->AllChoicesSet()) {
return; return;
} }
} }
auto choices = std::vector<BaseTurnChoice*>(_numberOfSides * _creaturesPerSide); auto choices = std::vector<BaseTurnChoice*>(_numberOfSides * _creaturesPerSide);
auto i = 0; auto i = 0;
for (auto side: _sides){ for (auto side : _sides) {
for (BaseTurnChoice* choice: side->GetChoices()){ for (BaseTurnChoice* choice : side->GetChoices()) {
if (choice->GetKind() == TurnChoiceKind::Attack){ if (choice->GetKind() == TurnChoiceKind::Attack) {
auto attack = dynamic_cast<const AttackTurnChoice*>(choice)->GetAttack(); auto attack = dynamic_cast<const AttackTurnChoice*>(choice)->GetAttack();
uint8_t uses = 1; uint8_t uses = 1;
//HOOK: change number of uses needed. // HOOK: change number of uses needed.
if (attack->GetRemainingUses() < uses){ if (attack->GetRemainingUses() < uses) {
//TODO: Implement default move // TODO: Implement default move
throw NotImplementedException("Not enough remaining uses, change to default move."); throw NotImplementedException("Not enough remaining uses, change to default move.");
} }
//HOOK: Check if we need to change the move // HOOK: Check if we need to change the move
} }
choices[i] = choice; choices[i] = choice;
i++; i++;
@ -60,39 +57,31 @@ void Battle::CheckChoicesSetAndRun() {
_currentTurnQueue = nullptr; _currentTurnQueue = nullptr;
} }
ChoiceQueue* Battle::GetCurrentTurnQueue() const { ChoiceQueue* Battle::GetCurrentTurnQueue() const { return _currentTurnQueue; }
return _currentTurnQueue;
}
Core::Random &Battle::GetRandom(){ Core::Random& Battle::GetRandom() { return _random; }
return _random;
}
bool Battle::CreatureInField(const Creature *creature) const { bool Battle::CreatureInField(const Creature* creature) const {
for (auto s: _sides){ for (auto s : _sides) {
if (s->CreatureOnSide(creature)) if (s->CreatureOnSide(creature))
return true; return true;
} }
return false; return false;
} }
bool Battle::HasRecalledSlots() const { bool Battle::HasRecalledSlots() const { return _numberOfRecalledSlots > 0; }
return _numberOfRecalledSlots > 0;
}
void Battle::ForceRecall(uint8_t side, uint8_t index) { void Battle::ForceRecall(uint8_t side, uint8_t index) {
_numberOfRecalledSlots++; _numberOfRecalledSlots++;
//TODO: Switch out. // TODO: Switch out.
} }
void Battle::FillRecall(uint8_t side, uint8_t, Creature *c) { void Battle::FillRecall(uint8_t side, uint8_t, Creature* c) {
_numberOfRecalledSlots--; _numberOfRecalledSlots--;
//TODO: switch in. // TODO: switch in.
if (_numberOfRecalledSlots == 0 && _currentTurnQueue != nullptr){ if (_numberOfRecalledSlots == 0 && _currentTurnQueue != nullptr) {
TurnHandler::RunTurn(this, _currentTurnQueue); TurnHandler::RunTurn(this, _currentTurnQueue);
} }
} }
void Battle::GetActiveScripts(std::vector<ScriptWrapper> &scripts) { void Battle::GetActiveScripts(std::vector<ScriptWrapper>& scripts) { scripts.emplace_back(&_volatile); }
scripts.emplace_back(&_volatile);
}

View File

@ -2,14 +2,14 @@
#define CREATURELIB_BATTLE_HPP #define CREATURELIB_BATTLE_HPP
#include <vector> #include <vector>
#include "BattleSide.hpp" #include "../Flow/ChoiceQueue.hpp"
#include "../Library/BattleLibrary.hpp" #include "../Library/BattleLibrary.hpp"
#include "../TurnChoices/BaseTurnChoice.hpp" #include "../TurnChoices/BaseTurnChoice.hpp"
#include "../Flow/ChoiceQueue.hpp" #include "BattleSide.hpp"
#include "Target.hpp" #include "Target.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class Battle : public ScriptSource{ class Battle : public ScriptSource {
const BattleLibrary* _library; const BattleLibrary* _library;
uint8_t _numberOfSides; uint8_t _numberOfSides;
uint8_t _creaturesPerSide; uint8_t _creaturesPerSide;
@ -19,6 +19,7 @@ namespace CreatureLib::Battling {
uint8_t _numberOfRecalledSlots = 0; uint8_t _numberOfRecalledSlots = 0;
ScriptSet _volatile; ScriptSet _volatile;
public: public:
[[nodiscard]] const BattleLibrary* GetLibrary() const; [[nodiscard]] const BattleLibrary* GetLibrary() const;
@ -32,7 +33,7 @@ namespace CreatureLib::Battling {
bool CreatureInField(const Creature* creature) const; bool CreatureInField(const Creature* creature) const;
Creature* GetTarget(const Target& target){ Creature* GetTarget(const Target& target) {
return _sides[target.GetSideIndex()]->GetCreature(target.GetCreatureIndex()); return _sides[target.GetSideIndex()]->GetCreature(target.GetCreatureIndex());
} }
@ -42,9 +43,8 @@ namespace CreatureLib::Battling {
void FillRecall(uint8_t side, uint8_t, Creature* c); void FillRecall(uint8_t side, uint8_t, Creature* c);
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override; void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override;
}; };
} }
#endif // CREATURELIB_BATTLE_HPP
#endif //CREATURELIB_BATTLE_HPP

View File

@ -1,47 +1,39 @@
#include "BattleSide.hpp" #include "BattleSide.hpp"
#include "../../Core/Exceptions/CreatureException.hpp"
#include <algorithm> #include <algorithm>
#include "../../Core/Exceptions/CreatureException.hpp"
#include "Battle.hpp" #include "Battle.hpp"
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
bool BattleSide::AllChoicesSet() const { bool BattleSide::AllChoicesSet() const { return _choicesSet == _creaturesPerSide; }
return _choicesSet == _creaturesPerSide;
}
void BattleSide::ResetChoices() { void BattleSide::ResetChoices() {
_choicesSet = 0; _choicesSet = 0;
for (uint8_t i = 0; i < _creaturesPerSide; i++){ for (uint8_t i = 0; i < _creaturesPerSide; i++) {
_choices[i] = nullptr; _choices[i] = nullptr;
} }
} }
const std::vector<BaseTurnChoice *>& BattleSide::GetChoices() const{ const std::vector<BaseTurnChoice*>& BattleSide::GetChoices() const { return _choices; }
return _choices;
}
void BattleSide::SetChoice(BaseTurnChoice *choice) { void BattleSide::SetChoice(BaseTurnChoice* choice) {
auto find = std::find(_creatures.begin(), _creatures.end(), choice->GetUser()); auto find = std::find(_creatures.begin(), _creatures.end(), choice->GetUser());
if (find ==_creatures.end()) if (find == _creatures.end())
throw CreatureException("User not found"); throw CreatureException("User not found");
uint8_t index = std::distance(_creatures.begin(),find); uint8_t index = std::distance(_creatures.begin(), find);
_choices[index] = choice; _choices[index] = choice;
_choicesSet++; _choicesSet++;
} }
void BattleSide::SetCreature(Creature *creature, uint8_t index) { void BattleSide::SetCreature(Creature* creature, uint8_t index) { _creatures[index] = creature; }
_creatures[index] = creature;
}
bool BattleSide::CreatureOnSide(const Creature *creature) const { bool BattleSide::CreatureOnSide(const Creature* creature) const {
return std::find(_creatures.begin(), _creatures.end(), creature) != _creatures.end(); return std::find(_creatures.begin(), _creatures.end(), creature) != _creatures.end();
} }
Creature *BattleSide::GetCreature(uint8_t index) const { Creature* BattleSide::GetCreature(uint8_t index) const { return _creatures[index]; }
return _creatures[index];
}
void BattleSide::GetActiveScripts(std::vector<ScriptWrapper> &scripts) { void BattleSide::GetActiveScripts(std::vector<ScriptWrapper>& scripts) {
scripts.emplace_back(&_volatile); scripts.emplace_back(&_volatile);
_battle->GetActiveScripts(scripts); _battle->GetActiveScripts(scripts);
} }

View File

@ -2,21 +2,22 @@
#define CREATURELIB_BATTLESIDE_HPP #define CREATURELIB_BATTLESIDE_HPP
#include <vector> #include <vector>
#include "Creature.hpp"
#include "../TurnChoices/BaseTurnChoice.hpp" #include "../TurnChoices/BaseTurnChoice.hpp"
#include "Creature.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class BattleSide : public ScriptSource{ class BattleSide : public ScriptSource {
uint8_t _creaturesPerSide; uint8_t _creaturesPerSide;
std::vector<Creature*> _creatures; std::vector<Creature*> _creatures;
std::vector<BaseTurnChoice*> _choices; std::vector<BaseTurnChoice*> _choices;
uint8_t _choicesSet = 0; uint8_t _choicesSet = 0;
ScriptSet _volatile; ScriptSet _volatile;
Battle* _battle; Battle* _battle;
public: public:
explicit BattleSide(Battle* battle, uint8_t creaturesPerSide) explicit BattleSide(Battle* battle, uint8_t creaturesPerSide)
: _creaturesPerSide(creaturesPerSide), _creatures(creaturesPerSide), _choices(creaturesPerSide), _battle(battle) : _creaturesPerSide(creaturesPerSide), _creatures(creaturesPerSide), _choices(creaturesPerSide),
{ _battle(battle) {
ResetChoices(); ResetChoices();
} }
@ -31,10 +32,8 @@ namespace CreatureLib::Battling{
Creature* GetCreature(uint8_t index) const; Creature* GetCreature(uint8_t index) const;
bool CreatureOnSide(const Creature* creature) const; bool CreatureOnSide(const Creature* creature) const;
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override; void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override;
}; };
} }
#endif // CREATURELIB_BATTLESIDE_HPP
#endif //CREATURELIB_BATTLESIDE_HPP

View File

@ -1 +0,0 @@
#include "BattleTeam.hpp"

View File

@ -1,10 +0,0 @@
#ifndef CREATURELIB_BATTLETEAM_HPP
#define CREATURELIB_BATTLETEAM_HPP
class BattleTeam {
};
#endif //CREATURELIB_BATTLETEAM_HPP

View File

@ -1,7 +1,7 @@
#include "CreateCreature.hpp" #include "CreateCreature.hpp"
#include "../../Core/Exceptions/CreatureException.hpp"
#include "../Library/BattleLibrary.hpp"
#include <utility> #include <utility>
#include "../Library/BattleLibrary.hpp"
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
@ -10,24 +10,24 @@ CreateCreature* CreateCreature::WithVariant(std::string variant) {
return this; return this;
} }
CreateCreature *CreateCreature::WithNickname(std::string nickname) { CreateCreature* CreateCreature::WithNickname(std::string nickname) {
this->_nickname = std::move(nickname); this->_nickname = std::move(nickname);
return this; return this;
} }
CreateCreature *CreateCreature::WithStatPotential(CreatureLib::Core::Statistic stat, uint32_t value) { CreateCreature* CreateCreature::WithStatPotential(CreatureLib::Core::Statistic stat, uint32_t value) {
switch (stat){ switch (stat) {
case Core::Health:_healthPotential = value; case Core::Health: _healthPotential = value;
case Core::PhysicalAttack: _physAttackPotential = value; case Core::PhysicalAttack: _physAttackPotential = value;
case Core::PhysicalDefense: _physDefensePotential = value; case Core::PhysicalDefense: _physDefensePotential = value;
case Core::MagicalAttack: _magAttackPotential = value; case Core::MagicalAttack: _magAttackPotential = value;
case Core::MagicalDefense:_magDefensePotential = value; case Core::MagicalDefense: _magDefensePotential = value;
case Core::Speed: _speedPotential = value; case Core::Speed: _speedPotential = value;
} }
return this; return this;
} }
CreateCreature * CreateCreature::WithStatPotentials(uint32_t health, uint32_t physAttack, uint32_t physDefense, CreateCreature* CreateCreature::WithStatPotentials(uint32_t health, uint32_t physAttack, uint32_t physDefense,
uint32_t magAttack, uint32_t magDefense, uint32_t speed) { uint32_t magAttack, uint32_t magDefense, uint32_t speed) {
_healthPotential = health; _healthPotential = health;
_physAttackPotential = physAttack; _physAttackPotential = physAttack;
@ -39,20 +39,19 @@ CreateCreature * CreateCreature::WithStatPotentials(uint32_t health, uint32_t ph
} }
CreateCreature* CreateCreature::WithStatExperience(Core::Statistic stat, uint32_t value) { CreateCreature* CreateCreature::WithStatExperience(Core::Statistic stat, uint32_t value) {
switch (stat){ switch (stat) {
case Core::Health:_healthExperience = value; case Core::Health: _healthExperience = value;
case Core::PhysicalAttack: _physAttackExperience = value; case Core::PhysicalAttack: _physAttackExperience = value;
case Core::PhysicalDefense: _physDefenseExperience = value; case Core::PhysicalDefense: _physDefenseExperience = value;
case Core::MagicalAttack: _magAttackExperience = value; case Core::MagicalAttack: _magAttackExperience = value;
case Core::MagicalDefense:_magDefenseExperience = value; case Core::MagicalDefense: _magDefenseExperience = value;
case Core::Speed: _speedExperience = value; case Core::Speed: _speedExperience = value;
} }
return this; return this;
} }
CreateCreature * CreateCreature* CreateCreature::WithStatExperiences(uint32_t health, uint32_t physAttack, uint32_t physDefense,
CreateCreature::WithStatExperiences(uint32_t health, uint32_t physAttack, uint32_t physDefense, uint32_t magAttack, uint32_t magAttack, uint32_t magDefense, uint32_t speed) {
uint32_t magDefense, uint32_t speed) {
_healthExperience = health; _healthExperience = health;
_physAttackExperience = physAttack; _physAttackExperience = physAttack;
_physDefenseExperience = physDefense; _physDefenseExperience = physDefense;
@ -62,12 +61,12 @@ CreateCreature::WithStatExperiences(uint32_t health, uint32_t physAttack, uint32
return this; return this;
} }
CreateCreature *CreateCreature::WithGender(Library::Gender gender) { CreateCreature* CreateCreature::WithGender(Library::Gender gender) {
this->_gender = gender; this->_gender = gender;
return this; return this;
} }
CreateCreature *CreateCreature::WithAttack(const std::string& attackName, AttackLearnMethod learnMethod) { CreateCreature* CreateCreature::WithAttack(const std::string& attackName, AttackLearnMethod learnMethod) {
if (_attacks.size() >= _library->GetSettings().GetMaximalMoves()) if (_attacks.size() >= _library->GetSettings().GetMaximalMoves())
throw CreatureException("You have already set the maximum amount of allowed moves."); throw CreatureException("You have already set the maximum amount of allowed moves.");
@ -76,44 +75,42 @@ CreateCreature *CreateCreature::WithAttack(const std::string& attackName, Attack
return this; return this;
} }
Creature *CreateCreature::Create() { Creature* CreateCreature::Create() {
_hasCreated = true; _hasCreated = true;
auto rand = Core::Random(); auto rand = Core::Random();
auto species = this->_library->GetSpeciesLibrary()->GetSpecies(this->_species); auto species = this->_library->GetSpeciesLibrary()->GetSpecies(this->_species);
auto variant = species->GetVariant(this->_variant); auto variant = species->GetVariant(this->_variant);
int8_t talent; int8_t talent;
if (this->_talent.empty()){ if (this->_talent.empty()) {
talent = variant->GetRandomTalent(&rand); talent = variant->GetRandomTalent(&rand);
} } else {
else{
talent = variant->GetTalentIndex(this->_talent); talent = variant->GetTalentIndex(this->_talent);
} }
auto identifier = this->_identifier; auto identifier = this->_identifier;
if (identifier == 0){ if (identifier == 0) {
identifier = rand.Get(); identifier = rand.Get();
} }
auto gender = this->_gender; auto gender = this->_gender;
if (gender == static_cast<Library::Gender >(-1)){ if (gender == static_cast<Library::Gender>(-1)) {
gender = species->GetRandomGender(rand); gender = species->GetRandomGender(rand);
} }
const Library::Item* heldItem = nullptr; const Library::Item* heldItem = nullptr;
if (!this->_heldItem.empty()){ if (!this->_heldItem.empty()) {
heldItem = _library->GetItemLibrary()->GetItem(this->_heldItem); heldItem = _library->GetItemLibrary()->GetItem(this->_heldItem);
} }
//FIXME: implement experience // FIXME: implement experience
auto experience = 0; auto experience = 0;
auto statExperience = Core::StatisticSet(_healthExperience, _physAttackExperience,_physDefenseExperience, _magAttackExperience, auto statExperience = Core::StatisticSet(_healthExperience, _physAttackExperience, _physDefenseExperience,
_magDefenseExperience, _speedExperience); _magAttackExperience, _magDefenseExperience, _speedExperience);
auto statPotential = Core::StatisticSet(_healthPotential, _physAttackPotential,_physDefensePotential, _magAttackPotential, auto statPotential = Core::StatisticSet(_healthPotential, _physAttackPotential, _physDefensePotential,
_magDefensePotential, _speedPotential); _magAttackPotential, _magDefensePotential, _speedPotential);
auto attacks = std::vector<LearnedAttack*>(_attacks.size()); auto attacks = std::vector<LearnedAttack*>(_attacks.size());
for (auto kv: _attacks){ for (auto kv : _attacks) {
attacks.push_back(new LearnedAttack(std::get<0>(kv), std::get<1>(kv))); attacks.push_back(new LearnedAttack(std::get<0>(kv), std::get<1>(kv)));
} }
return new Creature(species, variant, _level, experience, statExperience,statPotential, identifier,gender, _coloring, return new Creature(species, variant, _level, experience, statExperience, statPotential, identifier, gender,
heldItem, _nickname, talent, attacks); _coloring, heldItem, _nickname, talent, attacks);
} }

View File

@ -1,13 +1,12 @@
#ifndef CREATURELIB_CREATECREATURE_HPP #ifndef CREATURELIB_CREATECREATURE_HPP
#define CREATURELIB_CREATECREATURE_HPP #define CREATURELIB_CREATECREATURE_HPP
#include "../../Library/DataLibrary.hpp" #include "../../Library/DataLibrary.hpp"
#include "Creature.hpp" #include "Creature.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class CreateCreature { class CreateCreature {
const BattleLibrary *_library; const BattleLibrary* _library;
std::string _species; std::string _species;
std::string _variant = "default"; std::string _variant = "default";
uint8_t _level; uint8_t _level;
@ -37,26 +36,22 @@ namespace CreatureLib::Battling {
bool _hasCreated; bool _hasCreated;
public: public:
CreateCreature(const BattleLibrary *library, std::string species, uint8_t level) CreateCreature(const BattleLibrary* library, std::string species, uint8_t level)
: _library(library), _species(std::move(species)), _level(level) : _library(library), _species(std::move(species)), _level(level) {}
{
}
CreateCreature* WithVariant(std::string variant); CreateCreature* WithVariant(std::string variant);
CreateCreature* WithNickname(std::string nickname); CreateCreature* WithNickname(std::string nickname);
CreateCreature* WithStatPotential(Core::Statistic stat, uint32_t value); CreateCreature* WithStatPotential(Core::Statistic stat, uint32_t value);
CreateCreature* WithStatPotentials(uint32_t health, uint32_t physAttack, uint32_t physDefense, uint32_t magAttack, CreateCreature* WithStatPotentials(uint32_t health, uint32_t physAttack, uint32_t physDefense,
uint32_t magDefense,uint32_t speed); uint32_t magAttack, uint32_t magDefense, uint32_t speed);
CreateCreature* WithStatExperience(Core::Statistic stat, uint32_t value); CreateCreature* WithStatExperience(Core::Statistic stat, uint32_t value);
CreateCreature* WithStatExperiences(uint32_t health, uint32_t physAttack, uint32_t physDefense, uint32_t magAttack, CreateCreature* WithStatExperiences(uint32_t health, uint32_t physAttack, uint32_t physDefense,
uint32_t magDefense,uint32_t speed); uint32_t magAttack, uint32_t magDefense, uint32_t speed);
CreateCreature* WithGender(Library::Gender gender); CreateCreature* WithGender(Library::Gender gender);
CreateCreature* WithAttack(const std::string& attackName, AttackLearnMethod learnMethod); CreateCreature* WithAttack(const std::string& attackName, AttackLearnMethod learnMethod);
Creature* Create(); Creature* Create();
}; };
} }
#endif // CREATURELIB_CREATECREATURE_HPP
#endif //CREATURELIB_CREATECREATURE_HPP

View File

@ -1,6 +1,6 @@
#include "Creature.hpp"
#include <algorithm> #include <algorithm>
#include <utility> #include <utility>
#include "Creature.hpp"
#include "../Models/Battle.hpp" #include "../Models/Battle.hpp"
using namespace CreatureLib; using namespace CreatureLib;
@ -8,64 +8,48 @@ using namespace CreatureLib;
Battling::Creature::Creature(const Library::CreatureSpecies* species, const Library::SpeciesVariant* variant, Battling::Creature::Creature(const Library::CreatureSpecies* species, const Library::SpeciesVariant* variant,
uint8_t level, uint32_t experience, Core::StatisticSet<uint8_t> statExp, uint8_t level, uint32_t experience, Core::StatisticSet<uint8_t> statExp,
Core::StatisticSet<uint8_t> statPotential, uint32_t uid, Library::Gender gender, Core::StatisticSet<uint8_t> statPotential, uint32_t uid, Library::Gender gender,
uint8_t coloring, const Library::Item *heldItem, std::string nickname, int8_t talent, uint8_t coloring, const Library::Item* heldItem, std::string nickname, int8_t talent,
std::vector<LearnedAttack *> attacks) std::vector<LearnedAttack*> attacks)
: : __Species(species), __Variant(variant), __Level(level), __Experience(experience), __StatExperience(statExp),
__Species(species), __StatPotential(statPotential), __UniqueIdentifier(uid), __Gender(gender), __Coloring(coloring),
__Variant(variant), __HeldItem(heldItem), _nickname(std::move(nickname)), _talentIndex(talent), _hasOverridenTalent(false),
__Level(level), _attacks(std::move(attacks)) {
__Experience(experience),
__StatExperience(statExp),
__StatPotential(statPotential),
__UniqueIdentifier(uid),
__Gender(gender),
__Coloring(coloring),
__HeldItem(heldItem),
_nickname(std::move(nickname)),
_talentIndex(talent),
_hasOverridenTalent(false),
_attacks(std::move(attacks))
{
__CurrentHealth = GetBoostedStat(Core::Statistic::Health); __CurrentHealth = GetBoostedStat(Core::Statistic::Health);
} }
void Battling::Creature::ChangeLevel(int8_t amount) { void Battling::Creature::ChangeLevel(int8_t amount) {
this->__Level += amount; this->__Level += amount;
RecalculateFlatStats(); RecalculateFlatStats();
} }
void Battling::Creature::SetBattle(Battling::Battle *battle) { void Battling::Creature::SetBattle(Battling::Battle* battle) { this->_battle = battle; }
this->_battle = battle;
}
void Battling::Creature::SetBattleLibrary(Battling::BattleLibrary *library) { void Battling::Creature::SetBattleLibrary(Battling::BattleLibrary* library) {
this->_library = library; this->_library = library;
_activeTalent = _library->LoadScript(ScriptResolver::ScriptCategory::Talent, GetActiveTalent()); _activeTalent = _library->LoadScript(ScriptResolver::ScriptCategory::Talent, GetActiveTalent());
} }
const std::string &Battling::Creature::GetNickname() const { const std::string& Battling::Creature::GetNickname() const {
if (_nickname.empty()) if (_nickname.empty())
return __Species->GetName(); return __Species->GetName();
return _nickname; return _nickname;
} }
const std::string &Battling::Creature::GetActiveTalent() const { const std::string& Battling::Creature::GetActiveTalent() const {
if (_hasOverridenTalent){ if (_hasOverridenTalent) {
return _overridenTalentName; return _overridenTalentName;
} }
return __Variant->GetTalent(_talentIndex); return __Variant->GetTalent(_talentIndex);
} }
void Battling::Creature::SetBattleData(Battling::Battle *battle, Battling::BattleSide *side) { void Battling::Creature::SetBattleData(Battling::Battle* battle, Battling::BattleSide* side) {
_battle = battle; _battle = battle;
_side = side; _side = side;
} }
//region Stat APIs // region Stat APIs
void Battling::Creature::ChangeStatBoost(Core::Statistic stat, int8_t diffAmount){ void Battling::Creature::ChangeStatBoost(Core::Statistic stat, int8_t diffAmount) {
if (diffAmount > 0) if (diffAmount > 0)
this->_statBoost.IncreaseStatBy(stat, diffAmount); this->_statBoost.IncreaseStatBy(stat, diffAmount);
else else
@ -73,29 +57,17 @@ void Battling::Creature::ChangeStatBoost(Core::Statistic stat, int8_t diffAmount
this->RecalculateBoostedStat(stat); this->RecalculateBoostedStat(stat);
} }
uint32_t Battling::Creature::GetFlatStat(Core::Statistic stat) const{ uint32_t Battling::Creature::GetFlatStat(Core::Statistic stat) const { return _flatStats.GetStat(stat); }
return _flatStats.GetStat(stat);
}
uint32_t Battling::Creature::GetBoostedStat(Core::Statistic stat) const{ uint32_t Battling::Creature::GetBoostedStat(Core::Statistic stat) const { return _boostedStats.GetStat(stat); }
return _boostedStats.GetStat(stat);
}
uint32_t Battling::Creature::GetBaseStat(Core::Statistic stat) const { uint32_t Battling::Creature::GetBaseStat(Core::Statistic stat) const { return __Variant->GetStatistic(stat); }
return __Variant->GetStatistic(stat);
}
uint32_t Battling::Creature::GetStatPotential(Core::Statistic stat) const { uint32_t Battling::Creature::GetStatPotential(Core::Statistic stat) const { return __StatPotential.GetStat(stat); }
return __StatPotential.GetStat(stat);
}
uint32_t Battling::Creature::GetStatExperience(Core::Statistic stat) const { uint32_t Battling::Creature::GetStatExperience(Core::Statistic stat) const { return __StatExperience.GetStat(stat); }
return __StatExperience.GetStat(stat);
}
int8_t Battling::Creature::GetStatBoost(Core::Statistic stat) const { int8_t Battling::Creature::GetStatBoost(Core::Statistic stat) const { return _statBoost.GetStat(stat); }
return _statBoost.GetStat(stat);
}
void Battling::Creature::RecalculateFlatStats() { void Battling::Creature::RecalculateFlatStats() {
this->_flatStats = this->_library->GetStatCalculator()->CalculateFlatStats(this); this->_flatStats = this->_library->GetStatCalculator()->CalculateFlatStats(this);
@ -116,36 +88,30 @@ void Battling::Creature::RecalculateBoostedStat(Core::Statistic stat) {
this->_boostedStats.SetStat(stat, s); this->_boostedStats.SetStat(stat, s);
} }
//endregion // endregion
Battling::Battle *Battling::Creature::GetBattle() const{ Battling::Battle* Battling::Creature::GetBattle() const { return _battle; }
return _battle;
}
Battling::BattleSide *Battling::Creature::GetBattleSide() const { Battling::BattleSide* Battling::Creature::GetBattleSide() const { return _side; }
return _side;
}
bool Battling::Creature::IsFainted() const { bool Battling::Creature::IsFainted() const { return this->__CurrentHealth <= 0; }
return this->__CurrentHealth <= 0;
}
void Battling::Creature::Damage(uint32_t damage, Battling::DamageSource source) { void Battling::Creature::Damage(uint32_t damage, Battling::DamageSource source) {
if (damage > __CurrentHealth){ if (damage > __CurrentHealth) {
damage = __CurrentHealth; damage = __CurrentHealth;
} }
// HOOK: On Damage // HOOK: On Damage
__CurrentHealth -= damage; __CurrentHealth -= damage;
} }
void Battling::Creature::OverrideActiveTalent(const std::string& talent){ void Battling::Creature::OverrideActiveTalent(const std::string& talent) {
_hasOverridenTalent = true; _hasOverridenTalent = true;
_overridenTalentName = talent; _overridenTalentName = talent;
_activeTalent = this->_library->LoadScript(ScriptResolver::ScriptCategory::Talent, talent); _activeTalent = this->_library->LoadScript(ScriptResolver::ScriptCategory::Talent, talent);
} }
const std::vector<uint8_t>& Battling::Creature::GetTypes() const { const std::vector<uint8_t>& Battling::Creature::GetTypes() const {
//HOOK: override types. // HOOK: override types.
return this->__Variant->GetTypes(); return this->__Variant->GetTypes();
} }
@ -154,7 +120,7 @@ bool Battling::Creature::HasType(uint8_t type) const {
return std::find(t.begin(), t.end(), type) != t.end(); return std::find(t.begin(), t.end(), type) != t.end();
} }
void Battling::Creature::GetActiveScripts(std::vector<ScriptWrapper> &scripts) { void Battling::Creature::GetActiveScripts(std::vector<ScriptWrapper>& scripts) {
scripts.emplace_back(&_activeTalent); scripts.emplace_back(&_activeTalent);
scripts.emplace_back(&_status); scripts.emplace_back(&_status);
scripts.emplace_back(&_volatile); scripts.emplace_back(&_volatile);

View File

@ -4,37 +4,36 @@
#include "../../GenericTemplates.cpp" #include "../../GenericTemplates.cpp"
#include "../../Library/CreatureData/CreatureSpecies.hpp" #include "../../Library/CreatureData/CreatureSpecies.hpp"
#include "../../Library/Items/Item.hpp" #include "../../Library/Items/Item.hpp"
#include "LearnedAttack.hpp"
#include "DamageSource.hpp"
#include "../ScriptHandling/ScriptSet.hpp"
#include "../ScriptHandling/ScriptAggregator.hpp" #include "../ScriptHandling/ScriptAggregator.hpp"
#include "../ScriptHandling/ScriptSet.hpp"
#include "../ScriptHandling/ScriptSource.hpp" #include "../ScriptHandling/ScriptSource.hpp"
#include "DamageSource.hpp"
#include "LearnedAttack.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
// Forward declare battle class // Forward declare battle class
class Battle; class Battle;
class BattleSide; class BattleSide;
class BattleLibrary; class BattleLibrary;
class Creature : public ScriptSource{ class Creature : public ScriptSource {
GetProperty(const Library::CreatureSpecies*, Species); GetProperty(const Library::CreatureSpecies*, Species);
GetProperty(const Library::SpeciesVariant*, Variant) GetProperty(const Library::SpeciesVariant*, Variant);
GetProperty(uint8_t, Level); GetProperty(uint8_t, Level);
GetProperty(uint32_t, Experience); GetProperty(uint32_t, Experience);
GetProperty(Core::StatisticSet<uint8_t >, StatExperience); GetProperty(Core::StatisticSet<uint8_t>, StatExperience);
GetProperty(Core::StatisticSet<uint8_t >, StatPotential); GetProperty(Core::StatisticSet<uint8_t>, StatPotential);
GetProperty(uint32_t, UniqueIdentifier); GetProperty(uint32_t, UniqueIdentifier);
GetProperty(Library::Gender, Gender); GetProperty(Library::Gender, Gender);
GetProperty(uint8_t, Coloring); GetProperty(uint8_t, Coloring);
GetProperty(const Library::Item*, HeldItem); GetProperty(const Library::Item*, HeldItem);
GetProperty(uint32_t, CurrentHealth); GetProperty(uint32_t, CurrentHealth);
private: private:
Core::StatisticSet<int8_t > _statBoost; Core::StatisticSet<int8_t> _statBoost;
Core::StatisticSet<uint32_t > _flatStats; Core::StatisticSet<uint32_t> _flatStats;
Core::StatisticSet<uint32_t > _boostedStats; Core::StatisticSet<uint32_t> _boostedStats;
Battle* _battle; Battle* _battle;
BattleSide* _side; BattleSide* _side;
@ -54,9 +53,9 @@ namespace CreatureLib::Battling{
public: public:
Creature(const Library::CreatureSpecies* species, const Library::SpeciesVariant* variant, uint8_t level, Creature(const Library::CreatureSpecies* species, const Library::SpeciesVariant* variant, uint8_t level,
uint32_t experience, Core::StatisticSet<uint8_t > statExp, Core::StatisticSet<uint8_t > statPotential, uint32_t experience, Core::StatisticSet<uint8_t> statExp, Core::StatisticSet<uint8_t> statPotential,
uint32_t uid, Library::Gender gender, uint8_t coloring, const Library::Item* heldItem, std::string nickname, uint32_t uid, Library::Gender gender, uint8_t coloring, const Library::Item* heldItem,
int8_t talent, std::vector<LearnedAttack*> attacks); std::string nickname, int8_t talent, std::vector<LearnedAttack*> attacks);
virtual ~Creature() = default; virtual ~Creature() = default;
@ -75,10 +74,9 @@ namespace CreatureLib::Battling{
void Damage(uint32_t damage, DamageSource source); void Damage(uint32_t damage, DamageSource source);
void OverrideActiveTalent(const std::string& talent); void OverrideActiveTalent(const std::string& talent);
void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override;
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override; // region Stat APIs
//region Stat APIs
void SetBattle(Battle* battle); void SetBattle(Battle* battle);
void SetBattleLibrary(BattleLibrary* library); void SetBattleLibrary(BattleLibrary* library);
@ -95,11 +93,8 @@ namespace CreatureLib::Battling{
void RecalculateFlatStat(Core::Statistic); void RecalculateFlatStat(Core::Statistic);
void RecalculateBoostedStat(Core::Statistic); void RecalculateBoostedStat(Core::Statistic);
//endregion // endregion
}; };
} }
#endif // CREATURELIB_CREATURE_HPP
#endif //CREATURELIB_CREATURE_HPP

View File

@ -4,29 +4,27 @@
#include <array> #include <array>
#include "Creature.hpp" #include "Creature.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
template <int max> template <int max> class CreatureParty {
class CreatureParty {
std::array<Creature*, max> _party; std::array<Creature*, max> _party;
public: public:
CreatureParty(std::array<Creature*, max> party) : _party(party){ CreatureParty(std::array<Creature*, max> party) : _party(party) {}
}
Creature* GetAtIndex(int index) const{ Creature* GetAtIndex(int index) const { return _party[index]; }
return _party[index];
}
void Switch(int a, int b){ void Switch(int a, int b) {
auto ca = _party[a]; auto ca = _party[a];
_party[a] = _party[b]; _party[a] = _party[b];
_party[b] = ca; _party[b] = ca;
} }
bool HasAvailableCreatures() const{ bool HasAvailableCreatures() const {
for (Creature* c: _party){ for (Creature* c : _party) {
if (c == nullptr) continue; if (c == nullptr)
if (c->IsFainted()) continue; continue;
if (c->IsFainted())
continue;
return true; return true;
} }
return false; return false;
@ -34,5 +32,4 @@ namespace CreatureLib::Battling{
}; };
} }
#endif // CREATURELIB_CREATUREPARTY_HPP
#endif //CREATURELIB_CREATUREPARTY_HPP

View File

@ -9,4 +9,4 @@ namespace CreatureLib::Battling {
}; };
} }
#endif //CREATURELIB_DAMAGESOURCE_HPP #endif // CREATURELIB_DAMAGESOURCE_HPP

View File

@ -2,63 +2,55 @@
#define CREATURELIB_EXECUTINGATTACK_HPP #define CREATURELIB_EXECUTINGATTACK_HPP
#include <cstdint> #include <cstdint>
#include <vector>
#include <unordered_map> #include <unordered_map>
#include <vector>
#include "Creature.hpp" #include "Creature.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class ExecutingAttack : public ScriptSource { class ExecutingAttack : public ScriptSource {
public: public:
class HitData{ class HitData {
bool _critical = false; bool _critical = false;
uint8_t _basePower = 0; uint8_t _basePower = 0;
float _effectiveness = 1; float _effectiveness = 1;
uint32_t _damage = 0; uint32_t _damage = 0;
uint8_t _type = 0; uint8_t _type = 0;
public: public:
HitData(){} HitData() {}
[[nodiscard]] inline bool IsCritical() const{ return _critical;} [[nodiscard]] inline bool IsCritical() const { return _critical; }
[[nodiscard]] inline uint8_t GetBasePower() const{ return _basePower;} [[nodiscard]] inline uint8_t GetBasePower() const { return _basePower; }
[[nodiscard]] inline float GetEffectiveness() const{ return _effectiveness;} [[nodiscard]] inline float GetEffectiveness() const { return _effectiveness; }
[[nodiscard]] inline uint32_t GetDamage() const{ return _damage;} [[nodiscard]] inline uint32_t GetDamage() const { return _damage; }
[[nodiscard]] inline uint8_t GetType() const {return _type;} [[nodiscard]] inline uint8_t GetType() const { return _type; }
inline void SetCritical(bool value) {_critical = value;} inline void SetCritical(bool value) { _critical = value; }
inline void SetBasePower(uint8_t value) { _basePower = value; } inline void SetBasePower(uint8_t value) { _basePower = value; }
inline void SetEffectiveness(float value) {_effectiveness = value;} inline void SetEffectiveness(float value) { _effectiveness = value; }
inline void SetDamage(uint32_t value) { _damage = value;} inline void SetDamage(uint32_t value) { _damage = value; }
inline void SetType(uint8_t value) {_type = value;} inline void SetType(uint8_t value) { _type = value; }
}; };
class TargetData { class TargetData {
bool _isHit = true; bool _isHit = true;
std::vector<HitData> _hits; std::vector<HitData> _hits;
public: public:
explicit TargetData(uint8_t numberOfHits) : _hits(numberOfHits) explicit TargetData(uint8_t numberOfHits) : _hits(numberOfHits) {
{ for (uint8_t i = 0; i < numberOfHits; i++) {
for (uint8_t i = 0; i < numberOfHits; i++){
_hits[i] = HitData(); _hits[i] = HitData();
} }
} }
TargetData()= default; TargetData() = default;
const HitData& GetHit(uint8_t index) const{ const HitData& GetHit(uint8_t index) const { return _hits[index]; }
return _hits[index];
}
HitData* GetHitPtr(uint8_t index){ HitData* GetHitPtr(uint8_t index) { return &_hits[index]; }
return &_hits[index];
}
uint8_t GetNumberOfHits() const{ uint8_t GetNumberOfHits() const { return _hits.size(); }
return _hits.size();
}
bool IsHit() const{
return _isHit;
}
bool IsHit() const { return _isHit; }
}; };
private: private:
@ -66,45 +58,35 @@ namespace CreatureLib::Battling {
Creature* _user; Creature* _user;
LearnedAttack* _attack; LearnedAttack* _attack;
Script* _script; Script* _script;
public: public:
ExecutingAttack(const std::vector<Creature*>& targets, uint8_t numberHits, Creature* user, LearnedAttack* attack, ExecutingAttack(const std::vector<Creature*>& targets, uint8_t numberHits, Creature* user,
Script* script) LearnedAttack* attack, Script* script)
: _user(user), _attack(attack), _script(script) : _user(user), _attack(attack), _script(script) {
{
_targets.reserve(targets.size()); _targets.reserve(targets.size());
for (auto target: targets){ for (auto target : targets) {
_targets.insert({target, TargetData(numberHits)}); _targets.insert({target, TargetData(numberHits)});
} }
} }
virtual ~ExecutingAttack() = default; virtual ~ExecutingAttack() = default;
TargetData& GetAttackDataForTarget(Creature* creature){ TargetData& GetAttackDataForTarget(Creature* creature) { return _targets[creature]; }
return _targets[creature];
}
bool IsCreatureTarget(Creature* creature){ bool IsCreatureTarget(Creature* creature) { return _targets.find(creature) != _targets.end(); }
return _targets.find(creature) != _targets.end();
}
const std::unordered_map<Creature*, TargetData>& GetTargets(){ const std::unordered_map<Creature*, TargetData>& GetTargets() { return _targets; }
return _targets;
}
Creature* GetUser(){ Creature* GetUser() { return _user; }
return _user;
}
LearnedAttack* GetAttack(){ LearnedAttack* GetAttack() { return _attack; }
return _attack;
}
protected: protected:
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override { void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override {
scripts.emplace_back(&_script); scripts.emplace_back(&_script);
GetUser()->GetActiveScripts(scripts); GetUser()->GetActiveScripts(scripts);
} }
}; };
} }
#endif //CREATURELIB_EXECUTINGATTACK_HPP #endif // CREATURELIB_EXECUTINGATTACK_HPP

View File

@ -1,48 +1,32 @@
#include "LearnedAttack.hpp" #include "LearnedAttack.hpp"
CreatureLib::Battling::LearnedAttack::LearnedAttack(CreatureLib::Library::AttackData *attack, uint8_t maxUses, AttackLearnMethod learnMethod) CreatureLib::Battling::LearnedAttack::LearnedAttack(CreatureLib::Library::AttackData* attack, uint8_t maxUses,
:_attack(attack), _maxUses(maxUses), _remainingUses(maxUses), _learnMethod(learnMethod) AttackLearnMethod learnMethod)
{ : _attack(attack), _maxUses(maxUses), _remainingUses(maxUses), _learnMethod(learnMethod) {}
} CreatureLib::Battling::LearnedAttack::LearnedAttack(const CreatureLib::Library::AttackData* attack,
AttackLearnMethod learnMethod)
: _attack(attack), _maxUses(attack->GetBaseUsages()), _remainingUses(_maxUses), _learnMethod(learnMethod) {}
CreatureLib::Battling::LearnedAttack::LearnedAttack(const CreatureLib::Library::AttackData *attack, AttackLearnMethod learnMethod) const CreatureLib::Library::AttackData* CreatureLib::Battling::LearnedAttack::GetAttack() const { return _attack; }
: _attack(attack), _maxUses(attack->GetBaseUsages()), _remainingUses(_maxUses), _learnMethod(learnMethod)
{}
uint8_t CreatureLib::Battling::LearnedAttack::GetMaxUses() const { return _maxUses; }
const CreatureLib::Library::AttackData *CreatureLib::Battling::LearnedAttack::GetAttack() const { uint8_t CreatureLib::Battling::LearnedAttack::GetRemainingUses() const { return _remainingUses; }
return _attack;
}
uint8_t CreatureLib::Battling::LearnedAttack::GetMaxUses() const {
return _maxUses;
}
uint8_t CreatureLib::Battling::LearnedAttack::GetRemainingUses() const {
return _remainingUses;
}
CreatureLib::Battling::AttackLearnMethod CreatureLib::Battling::LearnedAttack::GetLearnMethod() const { CreatureLib::Battling::AttackLearnMethod CreatureLib::Battling::LearnedAttack::GetLearnMethod() const {
return _learnMethod; return _learnMethod;
} }
bool CreatureLib::Battling::LearnedAttack::TryUse(uint8_t uses) { bool CreatureLib::Battling::LearnedAttack::TryUse(uint8_t uses) {
if (uses > _remainingUses) return false; if (uses > _remainingUses)
return false;
_remainingUses -= uses; _remainingUses -= uses;
return true; return true;
} }
void CreatureLib::Battling::LearnedAttack::DecreaseUses(uint8_t amount) { void CreatureLib::Battling::LearnedAttack::DecreaseUses(uint8_t amount) { _remainingUses -= amount; }
_remainingUses -= amount;
}
void CreatureLib::Battling::LearnedAttack::RestoreUses(uint8_t amount) { void CreatureLib::Battling::LearnedAttack::RestoreUses(uint8_t amount) { _remainingUses += amount; }
_remainingUses += amount;
}
void CreatureLib::Battling::LearnedAttack::RestoreUses() {
_remainingUses = _maxUses;
}
void CreatureLib::Battling::LearnedAttack::RestoreUses() { _remainingUses = _maxUses; }

View File

@ -4,12 +4,13 @@
#include "../../Library/Attacks/AttackData.hpp" #include "../../Library/Attacks/AttackData.hpp"
#include "AttackLearnMethod.hpp" #include "AttackLearnMethod.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class LearnedAttack { class LearnedAttack {
const Library::AttackData* _attack; const Library::AttackData* _attack;
uint8_t _maxUses; uint8_t _maxUses;
uint8_t _remainingUses; uint8_t _remainingUses;
AttackLearnMethod _learnMethod; AttackLearnMethod _learnMethod;
public: public:
LearnedAttack(Library::AttackData* attack, uint8_t maxUses, AttackLearnMethod learnMethod); LearnedAttack(Library::AttackData* attack, uint8_t maxUses, AttackLearnMethod learnMethod);
LearnedAttack(const Library::AttackData* attack, AttackLearnMethod learnMethod); LearnedAttack(const Library::AttackData* attack, AttackLearnMethod learnMethod);
@ -26,5 +27,4 @@ namespace CreatureLib::Battling{
}; };
} }
#endif // CREATURELIB_LEARNEDATTACK_HPP
#endif //CREATURELIB_LEARNEDATTACK_HPP

View File

@ -8,17 +8,14 @@ namespace CreatureLib::Battling {
class Target { class Target {
uint8_t _side; uint8_t _side;
uint8_t _creature; uint8_t _creature;
public: public:
Target(uint8_t side, uint8_t creature) : _side(side), _creature(creature){} Target(uint8_t side, uint8_t creature) : _side(side), _creature(creature) {}
uint8_t GetSideIndex() const{ uint8_t GetSideIndex() const { return _side; }
return _side;
}
uint8_t GetCreatureIndex() const{ uint8_t GetCreatureIndex() const { return _creature; }
return _creature;
}
}; };
} }
#endif //CREATURELIB_TARGET_HPP #endif // CREATURELIB_TARGET_HPP

View File

@ -6,43 +6,42 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class BaseTurnChoice; class BaseTurnChoice;
class AttackTurnChoice; class AttackTurnChoice;
class ExecutingAttack; class ExecutingAttack;
class Creature; class Creature;
class Script{ class Script {
const std::string _name; const std::string _name;
public: public:
explicit Script(std::string name) :_name(std::move(name)){} explicit Script(std::string name) : _name(std::move(name)) {}
virtual ~Script() = default; virtual ~Script() = default;
virtual void Stack(){}; virtual void Stack(){};
const std::string& GetName(){ const std::string& GetName() { return _name; }
return _name;
}
virtual void OnBeforeTurn(const BaseTurnChoice* choice){}; virtual void OnBeforeTurn(const BaseTurnChoice* choice){};
virtual void ChangeAttack(AttackTurnChoice* choice, std::string& attack){}; virtual void ChangeAttack(AttackTurnChoice* choice, std::string& attack){};
virtual void PreventAttack(ExecutingAttack* attack,bool& result){}; virtual void PreventAttack(ExecutingAttack* attack, bool& result){};
virtual void FailAttack(ExecutingAttack* attack, bool& failed){}; virtual void FailAttack(ExecutingAttack* attack, bool& failed){};
virtual void StopBeforeAttack(ExecutingAttack* attack){}; virtual void StopBeforeAttack(ExecutingAttack* attack){};
virtual void OnBeforeAttack(ExecutingAttack* attack){}; virtual void OnBeforeAttack(ExecutingAttack* attack){};
virtual void FailIncomingAttack(ExecutingAttack* attack, Creature* target, bool& result){}; virtual void FailIncomingAttack(ExecutingAttack* attack, Creature* target, bool& result){};
virtual void IsInvulnerable(ExecutingAttack* attack, Creature* target , bool& result){}; virtual void IsInvulnerable(ExecutingAttack* attack, Creature* target, bool& result){};
virtual void OnAttackMiss(ExecutingAttack* attack, Creature* target){}; virtual void OnAttackMiss(ExecutingAttack* attack, Creature* target){};
virtual void ChangeAttackType(ExecutingAttack* attack, Creature* target, uint8_t hitNumber, uint8_t& type){}; virtual void ChangeAttackType(ExecutingAttack* attack, Creature* target, uint8_t hitNumber, uint8_t& type){};
virtual void OnStatusMove(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber){}; virtual void OnStatusMove(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber){};
virtual void PreventSecondaryEffects(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber, bool& result){}; virtual void PreventSecondaryEffects(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber,
bool& result){};
virtual void OnSecondaryEffect(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber){}; virtual void OnSecondaryEffect(const ExecutingAttack* attack, Creature* target, uint8_t hitNumber){};
virtual void OnAfterHits(const ExecutingAttack* attack, Creature* target){}; virtual void OnAfterHits(const ExecutingAttack* attack, Creature* target){};
}; };
} }
#endif //CREATURELIB_SCRIPT_HPP #endif // CREATURELIB_SCRIPT_HPP

View File

@ -3,36 +3,34 @@
#include <any> #include <any>
#include <queue> #include <queue>
#include "../../Core/Exceptions/NotReachableException.hpp"
#include "Script.hpp" #include "Script.hpp"
#include "ScriptSet.hpp" #include "ScriptSet.hpp"
#include "../../Core/Exceptions/NotReachableException.hpp"
#include "ScriptWrapper.hpp" #include "ScriptWrapper.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ScriptAggregator{ class ScriptAggregator {
std::vector<ScriptWrapper> _scripts; std::vector<ScriptWrapper> _scripts;
int _index = 0; int _index = 0;
bool _isSetSet = false; bool _isSetSet = false;
const std::vector<Script*>* _setScripts; const std::vector<Script*>* _setScripts;
int _setIndex; int _setIndex;
public: public:
ScriptAggregator(std::vector<ScriptWrapper> scripts) : _scripts(std::move(scripts)){ ScriptAggregator(std::vector<ScriptWrapper> scripts) : _scripts(std::move(scripts)){};
};
bool HasNext(){ bool HasNext() { return _index < _scripts.size() || (_isSetSet && _setIndex < _setScripts->size()); }
return _index < _scripts.size() || (_isSetSet && _setIndex < _setScripts->size());
}
Script* GetNext(){ Script* GetNext() {
// We can probably do this in a cleaner version once C++ 20 drops with Coroutine support. // We can probably do this in a cleaner version once C++ 20 drops with Coroutine support.
if (_isSetSet){ if (_isSetSet) {
if (_setIndex >= _setScripts->size()){ if (_setIndex >= _setScripts->size()) {
_isSetSet = false; _isSetSet = false;
return GetNext(); return GetNext();
} }
auto s = _setScripts->at(_setIndex); auto s = _setScripts->at(_setIndex);
_setIndex++; _setIndex++;
if (_setIndex >= _setScripts->size()){ if (_setIndex >= _setScripts->size()) {
_isSetSet = false; _isSetSet = false;
} }
return s; return s;
@ -41,13 +39,12 @@ namespace CreatureLib::Battling{
return nullptr; return nullptr;
auto next = _scripts[_index]; auto next = _scripts[_index];
_index++; _index++;
if (!next.IsSet()){ if (!next.IsSet()) {
auto scriptPtr = next.GetScript(); auto scriptPtr = next.GetScript();
if (scriptPtr == nullptr) if (scriptPtr == nullptr)
return GetNext(); return GetNext();
return *scriptPtr; return *scriptPtr;
} } else {
else{
auto set = next.GetScriptSet(); auto set = next.GetScriptSet();
if (set->Count() == 0) if (set->Count() == 0)
return GetNext(); return GetNext();
@ -61,4 +58,4 @@ namespace CreatureLib::Battling{
}; };
} }
#endif //CREATURELIB_SCRIPTAGGREGATOR_HPP #endif // CREATURELIB_SCRIPTAGGREGATOR_HPP

View File

@ -1,11 +1,10 @@
#define HOOK(hookName, source, ... ) \ #define HOOK(hookName, source, ...) \
{ \ { \
auto aggregator = source -> GetScriptIterator(); \ auto aggregator = source->GetScriptIterator(); \
while (aggregator.HasNext()){ \ while (aggregator.HasNext()) { \
auto next = aggregator.GetNext(); \ auto next = aggregator.GetNext(); \
if (next == nullptr) continue; \ if (next == nullptr) \
next->hookName(__VA_ARGS__); \ continue; \
} \ next->hookName(__VA_ARGS__); \
} } \
}

View File

@ -1,3 +1 @@
#include "ScriptResolver.hpp" #include "ScriptResolver.hpp"

View File

@ -4,12 +4,12 @@
#include <string> #include <string>
#include "Script.hpp" #include "Script.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ScriptResolver { class ScriptResolver {
public: public:
virtual ~ScriptResolver() = default; virtual ~ScriptResolver() = default;
enum class ScriptCategory{ enum class ScriptCategory {
Attack, Attack,
Talent, Talent,
Status, Status,
@ -19,11 +19,8 @@ namespace CreatureLib::Battling{
}; };
virtual Script* LoadScript(ScriptCategory category, const std::string& scriptName){ virtual Script* LoadScript(ScriptCategory category, const std::string& scriptName) { return nullptr; };
return nullptr;
};
}; };
} }
#endif // CREATURELIB_SCRIPTRESOLVER_HPP
#endif //CREATURELIB_SCRIPTRESOLVER_HPP

View File

@ -5,14 +5,15 @@
#include <unordered_map> #include <unordered_map>
#include "Script.hpp" #include "Script.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ScriptSet{ class ScriptSet {
std::vector<Script*> _scripts; std::vector<Script*> _scripts;
std::unordered_map<std::string, size_t> _lookup; std::unordered_map<std::string, size_t> _lookup;
public: public:
void Add(Script* script){ void Add(Script* script) {
auto f = _lookup.find(script->GetName()); auto f = _lookup.find(script->GetName());
if (f != _lookup.end()){ if (f != _lookup.end()) {
_scripts[f.operator*().second]->Stack(); _scripts[f.operator*().second]->Stack();
return; return;
} }
@ -20,22 +21,18 @@ namespace CreatureLib::Battling{
_lookup.insert({script->GetName(), _scripts.size() - 1}); _lookup.insert({script->GetName(), _scripts.size() - 1});
} }
void Remove(const std::string& key){ void Remove(const std::string& key) {
auto find = _lookup.find(key); auto find = _lookup.find(key);
if (find != _lookup.end()){ if (find != _lookup.end()) {
_scripts.erase(_scripts.begin() + find.operator*().second); _scripts.erase(_scripts.begin() + find.operator*().second);
_lookup.erase(key); _lookup.erase(key);
} }
} }
size_t Count() const{ size_t Count() const { return _scripts.size(); }
return _scripts.size();
}
const std::vector<Script *> * GetIterator() const{ const std::vector<Script*>* GetIterator() const { return &_scripts; }
return &_scripts;
}
}; };
} }
#endif //CREATURELIB_SCRIPTSET_HPP #endif // CREATURELIB_SCRIPTSET_HPP

View File

@ -5,15 +5,17 @@
#include "ScriptAggregator.hpp" #include "ScriptAggregator.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ScriptSource { class ScriptSource {
bool _areScriptsInitialized = false; bool _areScriptsInitialized = false;
std::vector<ScriptWrapper> _scripts; std::vector<ScriptWrapper> _scripts;
protected: protected:
virtual void GetActiveScripts(std::vector<ScriptWrapper>& scripts) = 0; virtual void GetActiveScripts(std::vector<ScriptWrapper>& scripts) = 0;
public: public:
ScriptAggregator GetScriptIterator(){ ScriptAggregator GetScriptIterator() {
if (!_areScriptsInitialized){ if (!_areScriptsInitialized) {
GetActiveScripts(_scripts); GetActiveScripts(_scripts);
_areScriptsInitialized = true; _areScriptsInitialized = true;
} }
@ -22,4 +24,4 @@ namespace CreatureLib::Battling{
}; };
} }
#endif //CREATURELIB_SCRIPTSOURCE_HPP #endif // CREATURELIB_SCRIPTSOURCE_HPP

View File

@ -1,3 +1 @@
#include "ScriptWrapper.hpp" #include "ScriptWrapper.hpp"

View File

@ -1,5 +1,3 @@
#ifndef CREATURELIB_SCRIPTWRAPPER_HPP #ifndef CREATURELIB_SCRIPTWRAPPER_HPP
#define CREATURELIB_SCRIPTWRAPPER_HPP #define CREATURELIB_SCRIPTWRAPPER_HPP
@ -7,27 +5,21 @@
#include "Script.hpp" #include "Script.hpp"
#include "ScriptSet.hpp" #include "ScriptSet.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class ScriptWrapper { class ScriptWrapper {
std::variant<Script**, ScriptSet*> _value; std::variant<Script**, ScriptSet*> _value;
bool _isSet; bool _isSet;
public: public:
ScriptWrapper(Script** s) : _value(s), _isSet(false){} ScriptWrapper(Script** s) : _value(s), _isSet(false) {}
ScriptWrapper(ScriptSet* s) : _value(s), _isSet(true){} ScriptWrapper(ScriptSet* s) : _value(s), _isSet(true) {}
bool IsSet() const{ bool IsSet() const { return _isSet; }
return _isSet;
}
Script** GetScript() const{ Script** GetScript() const { return std::get<Script**>(_value); }
return std::get<Script**>(_value);
}
ScriptSet* GetScriptSet() const{ ScriptSet* GetScriptSet() const { return std::get<ScriptSet*>(_value); }
return std::get<ScriptSet*>(_value);
}
}; };
} }
#endif // CREATURELIB_SCRIPTWRAPPER_HPP
#endif //CREATURELIB_SCRIPTWRAPPER_HPP

View File

@ -1,48 +1,39 @@
#ifndef CREATURELIB_ATTACKTURNCHOICE_HPP #ifndef CREATURELIB_ATTACKTURNCHOICE_HPP
#define CREATURELIB_ATTACKTURNCHOICE_HPP #define CREATURELIB_ATTACKTURNCHOICE_HPP
#include "BaseTurnChoice.hpp"
#include "../Models/LearnedAttack.hpp" #include "../Models/LearnedAttack.hpp"
#include "../Models/Target.hpp" #include "../Models/Target.hpp"
#include "BaseTurnChoice.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class AttackTurnChoice : public BaseTurnChoice { class AttackTurnChoice : public BaseTurnChoice {
LearnedAttack* _attack; LearnedAttack* _attack;
Target _target; Target _target;
Script* _attackScript; Script* _attackScript;
public: public:
AttackTurnChoice(Creature* user, LearnedAttack* attack, const Target& target) AttackTurnChoice(Creature* user, LearnedAttack* attack, const Target& target)
: BaseTurnChoice(user), _attack(attack), _target(target){} : BaseTurnChoice(user), _attack(attack), _target(target) {}
inline LearnedAttack* GetAttack() const{ inline LearnedAttack* GetAttack() const { return _attack; }
return _attack;
}
TurnChoiceKind GetKind() const override { TurnChoiceKind GetKind() const override { return TurnChoiceKind ::Attack; }
return TurnChoiceKind ::Attack;
}
int8_t GetPriority() const{ int8_t GetPriority() const {
//HOOK: Change priority // HOOK: Change priority
return _attack->GetAttack()->GetPriority(); return _attack->GetAttack()->GetPriority();
} }
const Target& GetTarget() const{ const Target& GetTarget() const { return _target; }
return _target;
}
Script* GetAttackScript(){ Script* GetAttackScript() { return _attackScript; }
return _attackScript;
}
protected: protected:
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override { void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override {
scripts.emplace_back(&_attackScript); scripts.emplace_back(&_attackScript);
GetUser()->GetActiveScripts(scripts); GetUser()->GetActiveScripts(scripts);
} }
}; };
} }
#endif // CREATURELIB_ATTACKTURNCHOICE_HPP
#endif //CREATURELIB_ATTACKTURNCHOICE_HPP

View File

@ -1,24 +1,23 @@
#ifndef CREATURELIB_BASETURNCHOICE_HPP #ifndef CREATURELIB_BASETURNCHOICE_HPP
#define CREATURELIB_BASETURNCHOICE_HPP #define CREATURELIB_BASETURNCHOICE_HPP
#include "TurnChoiceKind.hpp"
#include "../ScriptHandling/ScriptSource.hpp" #include "../ScriptHandling/ScriptSource.hpp"
#include "TurnChoiceKind.hpp"
namespace CreatureLib::Battling{ namespace CreatureLib::Battling {
class Creature; class Creature;
class BaseTurnChoice : public ScriptSource { class BaseTurnChoice : public ScriptSource {
Creature* _user; Creature* _user;
protected: protected:
BaseTurnChoice(Creature* user) : _user(user){}; BaseTurnChoice(Creature* user) : _user(user){};
public: public:
virtual ~BaseTurnChoice() = default; virtual ~BaseTurnChoice() = default;
[[nodiscard]] virtual TurnChoiceKind GetKind() const = 0; [[nodiscard]] virtual TurnChoiceKind GetKind() const = 0;
[[nodiscard]] inline Creature* GetUser() const{ [[nodiscard]] inline Creature* GetUser() const { return _user; }
return _user;
}
}; };
} }
#endif // CREATURELIB_BASETURNCHOICE_HPP
#endif //CREATURELIB_BASETURNCHOICE_HPP

View File

@ -4,19 +4,15 @@
#include "BaseTurnChoice.hpp" #include "BaseTurnChoice.hpp"
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
class PassTurnChoice : public BaseTurnChoice{ class PassTurnChoice : public BaseTurnChoice {
public: public:
PassTurnChoice(Creature* c) : BaseTurnChoice(c){} PassTurnChoice(Creature* c) : BaseTurnChoice(c) {}
TurnChoiceKind GetKind() const override { TurnChoiceKind GetKind() const override { return TurnChoiceKind ::Pass; }
return TurnChoiceKind ::Pass;
}
protected: protected:
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override { void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override { GetUser()->GetActiveScripts(scripts); }
GetUser()->GetActiveScripts(scripts);
}
}; };
} }
#endif //CREATURELIB_PASSTURNCHOICE_HPP #endif // CREATURELIB_PASSTURNCHOICE_HPP

View File

@ -4,12 +4,6 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Battling { namespace CreatureLib::Battling {
enum class TurnChoiceKind : uint8_t { enum class TurnChoiceKind : uint8_t { Pass, Attack, Item, Switch, RunAway };
Pass,
Attack,
Item,
Switch,
RunAway
};
} }
#endif //CREATURELIB_TURNCHOICEKIND_HPP #endif // CREATURELIB_TURNCHOICEKIND_HPP

View File

@ -4,15 +4,13 @@
#include <exception> #include <exception>
#include <string> #include <string>
class CreatureException : std::exception{ class CreatureException : std::exception {
std::string _error; std::string _error;
public:
CreatureException(std::string error){}
const char *what() const noexcept override { public:
return _error.c_str(); CreatureException(std::string error) {}
}
const char* what() const noexcept override { return _error.c_str(); }
}; };
#endif // CREATURELIB_CREATUREEXCEPTION_HPP
#endif //CREATURELIB_CREATUREEXCEPTION_HPP

View File

@ -3,10 +3,10 @@
#include "CreatureException.hpp" #include "CreatureException.hpp"
class NotImplementedException : CreatureException{ class NotImplementedException : CreatureException {
public: public:
NotImplementedException(std::string error) : CreatureException(error){} NotImplementedException(std::string error) : CreatureException(error) {}
NotImplementedException() : CreatureException("Not Implemented"){} NotImplementedException() : CreatureException("Not Implemented") {}
}; };
#endif //CREATURELIB_NOTIMPLEMENTEDEXCEPTION_HPP #endif // CREATURELIB_NOTIMPLEMENTEDEXCEPTION_HPP

View File

@ -3,9 +3,9 @@
#include "CreatureException.hpp" #include "CreatureException.hpp"
class NotReachableException : CreatureException{ class NotReachableException : CreatureException {
public: public:
NotReachableException() : CreatureException("Not Reachable"){}; NotReachableException() : CreatureException("Not Reachable"){};
}; };
#endif //CREATURELIB_NOTREACHABLEEXCEPTION_HPP #endif // CREATURELIB_NOTREACHABLEEXCEPTION_HPP

View File

@ -2,7 +2,8 @@
#include <limits> #include <limits>
// Seed parameterless constructor with current milliseconds since epoch. // Seed parameterless constructor with current milliseconds since epoch.
CreatureLib::Core::Random::Random() : _rng(std::mt19937(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count())){} CreatureLib::Core::Random::Random()
: _rng(std::mt19937(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count())) {}
float CreatureLib::Core::Random::GetFloat() { float CreatureLib::Core::Random::GetFloat() {
return static_cast<float>(_rng()) / (static_cast<float>(std::mt19937::max() - std::mt19937::min()) - 0.5f); return static_cast<float>(_rng()) / (static_cast<float>(std::mt19937::max() - std::mt19937::min()) - 0.5f);
@ -13,18 +14,13 @@ double CreatureLib::Core::Random::GetDouble() {
} }
int32_t CreatureLib::Core::Random::Get() { int32_t CreatureLib::Core::Random::Get() {
return static_cast<int32_t >(GetDouble() * static_cast<float>(std::numeric_limits<int32_t >::max())); return static_cast<int32_t>(GetDouble() * static_cast<float>(std::numeric_limits<int32_t>::max()));
} }
int32_t CreatureLib::Core::Random::Get(int32_t max) { int32_t CreatureLib::Core::Random::Get(int32_t max) {
return static_cast<int32_t >(GetDouble() * static_cast<float>(max)); return static_cast<int32_t>(GetDouble() * static_cast<float>(max));
} }
int32_t CreatureLib::Core::Random::Get(int32_t min, int32_t max) { int32_t CreatureLib::Core::Random::Get(int32_t min, int32_t max) {
return static_cast<int32_t >(GetDouble() * static_cast<float>(max - min) + min); return static_cast<int32_t>(GetDouble() * static_cast<float>(max - min) + min);
} }

View File

@ -1,13 +1,14 @@
#ifndef CREATURELIB_RANDOM_HPP #ifndef CREATURELIB_RANDOM_HPP
#define CREATURELIB_RANDOM_HPP #define CREATURELIB_RANDOM_HPP
#include <cstdint>
#include <chrono> #include <chrono>
#include <cstdint>
#include <random> #include <random>
using namespace std::chrono; using namespace std::chrono;
namespace CreatureLib::Core { namespace CreatureLib::Core {
class Random { class Random {
private: private:
std::mt19937 _rng; std::mt19937 _rng;
public: public:
Random(); Random();
explicit Random(int32_t seed) : _rng(seed){}; explicit Random(int32_t seed) : _rng(seed){};
@ -20,4 +21,4 @@ namespace CreatureLib::Core {
}; };
} }
#endif //CREATURELIB_RANDOM_HPP #endif // CREATURELIB_RANDOM_HPP

View File

@ -3,7 +3,7 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Core{ namespace CreatureLib::Core {
enum Statistic : uint8_t { enum Statistic : uint8_t {
Health, Health,
PhysicalAttack, PhysicalAttack,
@ -14,4 +14,4 @@ namespace CreatureLib::Core{
}; };
} }
#endif //CREATURELIB_STATISTIC_HPP #endif // CREATURELIB_STATISTIC_HPP

View File

@ -1,12 +1,12 @@
#ifndef CREATURELIB_STATISTICSET_HPP #ifndef CREATURELIB_STATISTICSET_HPP
#define CREATURELIB_STATISTICSET_HPP #define CREATURELIB_STATISTICSET_HPP
#include <stdint.h>
#include <exception> #include <exception>
#include "Statistic.hpp" #include <stdint.h>
#include "../GenericTemplates.cpp" #include "../GenericTemplates.cpp"
#include "Exceptions/NotReachableException.hpp" #include "Exceptions/NotReachableException.hpp"
#include "Statistic.hpp"
namespace CreatureLib::Core{ namespace CreatureLib::Core {
template <class T> template <class T>
class StatisticSet { class StatisticSet {
protected: protected:
@ -16,25 +16,23 @@ namespace CreatureLib::Core{
T _magicalAttack; T _magicalAttack;
T _magicalDefense; T _magicalDefense;
T _speed; T _speed;
public: public:
StatisticSet(T health, T physicalAttack, T physicalDefense, T magicalAttack, T magicalDefense, T speed) StatisticSet(T health, T physicalAttack, T physicalDefense, T magicalAttack, T magicalDefense, T speed)
: _health(health), _physicalAttack(physicalAttack), : _health(health), _physicalAttack(physicalAttack), _physicalDefense(physicalDefense),
_physicalDefense(physicalDefense), _magicalAttack(magicalAttack), _magicalAttack(magicalAttack), _magicalDefense(magicalDefense), _speed(speed) {}
_magicalDefense(magicalDefense), _speed(speed){}
StatisticSet() StatisticSet()
: _health(0), _physicalAttack(0), _physicalDefense(0), _magicalAttack(0), _magicalDefense(0), _speed(0) : _health(0), _physicalAttack(0), _physicalDefense(0), _magicalAttack(0), _magicalDefense(0), _speed(0) {}
{}
inline T GetHealth() const{ return _health; } inline T GetHealth() const { return _health; }
inline T GetPhysicalAttack() const{ return _physicalAttack; } inline T GetPhysicalAttack() const { return _physicalAttack; }
inline T GetPhysicalDefense() const{ return _physicalDefense; } inline T GetPhysicalDefense() const { return _physicalDefense; }
inline T GetMagicalAttack() const{ return _magicalAttack; } inline T GetMagicalAttack() const { return _magicalAttack; }
inline T GetMagicalDefense() const{ return _magicalDefense; } inline T GetMagicalDefense() const { return _magicalDefense; }
inline T GetSpeed() const{ return _speed; } inline T GetSpeed() const { return _speed; }
[[nodiscard]] inline T GetStat(Statistic stat) const {
[[nodiscard]] inline T GetStat(Statistic stat) const{ switch (stat) {
switch (stat){
case Health: return _health; case Health: return _health;
case PhysicalAttack: return _physicalAttack; case PhysicalAttack: return _physicalAttack;
case PhysicalDefense: return _physicalDefense; case PhysicalDefense: return _physicalDefense;
@ -45,8 +43,8 @@ namespace CreatureLib::Core{
throw NotReachableException(); throw NotReachableException();
} }
inline void SetStat(Statistic stat, T value){ inline void SetStat(Statistic stat, T value) {
switch (stat){ switch (stat) {
case Health: _health = value; case Health: _health = value;
case PhysicalAttack: _physicalAttack = value; case PhysicalAttack: _physicalAttack = value;
case PhysicalDefense: _physicalDefense = value; case PhysicalDefense: _physicalDefense = value;
@ -57,8 +55,8 @@ namespace CreatureLib::Core{
throw NotReachableException(); throw NotReachableException();
} }
inline void IncreaseStatBy(Statistic stat, T amount){ inline void IncreaseStatBy(Statistic stat, T amount) {
switch (stat){ switch (stat) {
case Health: _health += amount; case Health: _health += amount;
case PhysicalAttack: _physicalAttack += amount; case PhysicalAttack: _physicalAttack += amount;
case PhysicalDefense: _physicalDefense += amount; case PhysicalDefense: _physicalDefense += amount;
@ -68,8 +66,8 @@ namespace CreatureLib::Core{
} }
throw NotReachableException(); throw NotReachableException();
} }
inline void DecreaseStatBy(Statistic stat, T amount){ inline void DecreaseStatBy(Statistic stat, T amount) {
switch (stat){ switch (stat) {
case Health: _health -= amount; case Health: _health -= amount;
case PhysicalAttack: _physicalAttack -= amount; case PhysicalAttack: _physicalAttack -= amount;
case PhysicalDefense: _physicalDefense -= amount; case PhysicalDefense: _physicalDefense -= amount;
@ -82,5 +80,4 @@ namespace CreatureLib::Core{
}; };
} }
#endif //CREATURELIB_STATISTICSET_HPP #endif //CREATURELIB_STATISTICSET_HPP

View File

@ -2,15 +2,22 @@
\brief GetProperty creates a simple wrapper for a field, creating a private field, and a public getter method. \brief GetProperty creates a simple wrapper for a field, creating a private field, and a public getter method.
*/ */
#define GetProperty(type, name) \ #define GetProperty(type, name) \
private: type __##name; \ private: \
public: [[nodiscard]] inline type Get##name() const{ return __##name; }; type __##name; \
\
public: \
[[nodiscard]] inline type Get##name() const { return __##name; };
/*! /*!
\brief GetProperty creates a simple wrapper for a field, creating a private field, a public getter method, and a public \brief GetProperty creates a simple wrapper for a field, creating a private field, a public getter method, and a public
setter method. setter method.
*/ */
#define GetSetProperty(type, name) \ #define GetSetProperty(type, name) \
private: type __##name; \ private: \
public: [[nodiscard]] inline type Get##name() const{ return __##name; }; \ type __##name; \
public: inline void Set##name(type value) { __##name = value; }; \
public: \
[[nodiscard]] inline type Get##name() const { return __##name; }; \
\
public: \
inline void Set##name(type value) { __##name = value; };

View File

@ -1,20 +1,16 @@
#include "AttackLibrary.hpp" #include "AttackLibrary.hpp"
const CreatureLib::Library::AttackData *CreatureLib::Library::AttackLibrary::GetAttack(const std::string &name) const { const CreatureLib::Library::AttackData* CreatureLib::Library::AttackLibrary::GetAttack(const std::string& name) const {
return this->_attacks.at(name); return this->_attacks.at(name);
} }
const CreatureLib::Library::AttackData *CreatureLib::Library::AttackLibrary::operator[](const std::string &name) const { const CreatureLib::Library::AttackData* CreatureLib::Library::AttackLibrary::operator[](const std::string& name) const {
return GetAttack(name); return GetAttack(name);
} }
void CreatureLib::Library::AttackLibrary::LoadAttack(const std::string &name, void CreatureLib::Library::AttackLibrary::LoadAttack(const std::string& name,
const CreatureLib::Library::AttackData* attack) { const CreatureLib::Library::AttackData* attack) {
this->_attacks.insert({name, attack}); this->_attacks.insert({name, attack});
} }
void CreatureLib::Library::AttackLibrary::DeleteAttack(const std::string &name) { void CreatureLib::Library::AttackLibrary::DeleteAttack(const std::string& name) { this->_attacks.erase(name); }
this->_attacks.erase(name);
}

View File

@ -9,22 +9,23 @@ namespace CreatureLib::Library {
class AttackLibrary { class AttackLibrary {
private: private:
std::unordered_map<std::string, const AttackData*> _attacks; std::unordered_map<std::string, const AttackData*> _attacks;
public: public:
AttackLibrary() = default; AttackLibrary() = default;
~AttackLibrary(){ ~AttackLibrary() {
for (auto attack: _attacks){ for (auto attack : _attacks) {
delete attack.second; delete attack.second;
} }
_attacks.clear(); _attacks.clear();
} }
[[nodiscard]] const AttackData* GetAttack(const std::string& name) const; [[nodiscard]] const AttackData* GetAttack(const std::string& name) const;
[[nodiscard]] const AttackData* operator[] (const std::string& name) const; [[nodiscard]] const AttackData* operator[](const std::string& name) const;
void LoadAttack(const std::string& name, const AttackData* attack); void LoadAttack(const std::string& name, const AttackData* attack);
void DeleteAttack(const std::string& name); void DeleteAttack(const std::string& name);
}; };
} }
#endif //CREATURELIB_ATTACKLIBRARY_HPP #endif // CREATURELIB_ATTACKLIBRARY_HPP

View File

@ -4,11 +4,7 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library { namespace CreatureLib::Library {
enum class AttackCategory : uint8_t { enum class AttackCategory : uint8_t { Physical, Magical, Status };
Physical,
Magical,
Status
};
} }
#endif //CREATURELIB_ATTACKCATEGORY_HPP #endif // CREATURELIB_ATTACKCATEGORY_HPP

View File

@ -1,5 +1,4 @@
#include "AttackData.hpp" #include "AttackData.hpp"
#include <utility> #include <utility>
CreatureLib::Library::AttackData::AttackData(std::string name, std::string type, CreatureLib::Library::AttackData::AttackData(std::string name, std::string type,
@ -7,19 +6,9 @@ CreatureLib::Library::AttackData::AttackData(std::string name, std::string type,
uint8_t accuracy, uint8_t baseUsage, uint8_t accuracy, uint8_t baseUsage,
CreatureLib::Library::AttackTarget target, uint8_t priority, CreatureLib::Library::AttackTarget target, uint8_t priority,
std::unordered_set<std::string> flags) std::unordered_set<std::string> flags)
: : __Name(std::move(name)), __Type(std::move(type)), __Category(category), __BasePower(power), __Accuracy(accuracy),
__Name(std::move(name)), __BaseUsages(baseUsage), __Target(target), __Priority(priority), _flags(std::move(flags)) {}
__Type(std::move(type)),
__Category(category),
__BasePower(power),
__Accuracy(accuracy),
__BaseUsages(baseUsage),
__Target(target),
__Priority(priority),
_flags(std::move(flags))
{}
bool CreatureLib::Library::AttackData::HasFlag(const std::string& key) const{ bool CreatureLib::Library::AttackData::HasFlag(const std::string& key) const {
return this->_flags.find(key) != this->_flags.end(); return this->_flags.find(key) != this->_flags.end();
} }

View File

@ -3,23 +3,24 @@
#include <string> #include <string>
#include <unordered_set> #include <unordered_set>
#include "../../GenericTemplates.cpp"
#include "AttackCategory.hpp" #include "AttackCategory.hpp"
#include "AttackTarget.hpp" #include "AttackTarget.hpp"
#include "../../GenericTemplates.cpp"
namespace CreatureLib::Library { namespace CreatureLib::Library {
class AttackData { class AttackData {
GetProperty(std::string, Name); GetProperty(std::string, Name);
GetProperty(std::string, Type); GetProperty(std::string, Type);
GetProperty(AttackCategory , Category); GetProperty(AttackCategory, Category);
GetProperty(uint8_t , BasePower); GetProperty(uint8_t, BasePower);
GetProperty(uint8_t , Accuracy); GetProperty(uint8_t, Accuracy);
GetProperty(uint8_t , BaseUsages); GetProperty(uint8_t, BaseUsages);
GetProperty(AttackTarget, Target); GetProperty(AttackTarget, Target);
GetProperty(uint8_t , Priority); GetProperty(uint8_t, Priority);
private: private:
std::unordered_set<std::string> _flags; std::unordered_set<std::string> _flags;
public: public:
AttackData(std::string name, std::string type, AttackCategory category, uint8_t power, uint8_t accuracy, AttackData(std::string name, std::string type, AttackCategory category, uint8_t power, uint8_t accuracy,
uint8_t baseUsage, AttackTarget target, uint8_t priority, std::unordered_set<std::string> flags); uint8_t baseUsage, AttackTarget target, uint8_t priority, std::unordered_set<std::string> flags);
@ -28,5 +29,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif // CREATURELIB_ATTACKDATA_HPP
#endif //CREATURELIB_ATTACKDATA_HPP

View File

@ -4,7 +4,7 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library { namespace CreatureLib::Library {
enum class AttackTarget : uint8_t{ enum class AttackTarget : uint8_t {
Adjacent, Adjacent,
AdjacentAlly, AdjacentAlly,
AdjacentAllySelf, AdjacentAllySelf,
@ -23,4 +23,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif //CREATURELIB_ATTACKTARGET_HPP #endif // CREATURELIB_ATTACKTARGET_HPP

View File

@ -1,16 +1,8 @@
#include "CreatureMoves.hpp" #include "CreatureMoves.hpp"
#include <utility> #include <utility>
CreatureLib::Library::LevelMove::LevelMove(uint8_t level, std::string name) CreatureLib::Library::LevelMove::LevelMove(uint8_t level, std::string name) : _level(level), _name(std::move(name)) {}
:_level(level),
_name(std::move(name))
{}
uint8_t CreatureLib::Library::LevelMove::GetLevel() const { uint8_t CreatureLib::Library::LevelMove::GetLevel() const { return this->_level; }
return this->_level;
}
std::string CreatureLib::Library::LevelMove::GetName() const {
return this->_name;
}
std::string CreatureLib::Library::LevelMove::GetName() const { return this->_name; }

View File

@ -5,11 +5,12 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace CreatureLib::Library{ namespace CreatureLib::Library {
class LevelMove{ class LevelMove {
private: private:
uint8_t _level; uint8_t _level;
std::string _name; std::string _name;
public: public:
LevelMove(uint8_t level, std::string name); LevelMove(uint8_t level, std::string name);
[[nodiscard]] inline uint8_t GetLevel() const; [[nodiscard]] inline uint8_t GetLevel() const;
@ -23,10 +24,10 @@ namespace CreatureLib::Library{
std::vector<std::string> _machineMoves; std::vector<std::string> _machineMoves;
std::vector<std::string> _tutorMoves; std::vector<std::string> _tutorMoves;
std::vector<std::string> _variantDependentMoves; std::vector<std::string> _variantDependentMoves;
public: public:
//TODO: Public API funcs // TODO: Public API funcs
}; };
} }
#endif // CREATURELIB_CREATUREMOVES_HPP
#endif //CREATURELIB_CREATUREMOVES_HPP

View File

@ -2,30 +2,19 @@
using namespace CreatureLib::Library; using namespace CreatureLib::Library;
CreatureSpecies::CreatureSpecies(uint16_t id, std::string name, const SpeciesVariant* defaultVariant, CreatureSpecies::CreatureSpecies(uint16_t id, std::string name, const SpeciesVariant* defaultVariant, float genderRatio,
float genderRatio, std::string growthRate, uint8_t captureRate, uint8_t baseHappiness) std::string growthRate, uint8_t captureRate, uint8_t baseHappiness)
: : __Id(id), __GenderRate(genderRatio), __GrowthRate(std::move(growthRate)), __CaptureRate(captureRate),
__Id(id), __BaseHappiness(baseHappiness), _variants({{"default", defaultVariant}}), _name(std::move(name)) {}
__GenderRate(genderRatio),
__GrowthRate(std::move(growthRate)),
__CaptureRate(captureRate),
__BaseHappiness(baseHappiness),
_variants({{"default", defaultVariant}}),
_name(std::move(name))
{}
const SpeciesVariant *CreatureSpecies::GetVariant(const std::string& key) const { const SpeciesVariant* CreatureSpecies::GetVariant(const std::string& key) const { return _variants.at(key); }
return _variants.at(key);
}
Gender CreatureSpecies::GetRandomGender(CreatureLib::Core::Random &rand) const { Gender CreatureSpecies::GetRandomGender(CreatureLib::Core::Random& rand) const {
// TODO: Genderless creatures // TODO: Genderless creatures
auto val = rand.GetDouble(); auto val = rand.GetDouble();
if (val >= this->__GenderRate) return Gender ::Female; if (val >= this->__GenderRate)
return Gender ::Female;
return Gender ::Male; return Gender ::Male;
} }
const std::string &CreatureSpecies::GetName() const { const std::string& CreatureSpecies::GetName() const { return _name; }
return _name;
}

View File

@ -3,12 +3,13 @@
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include "SpeciesVariant.hpp"
#include "../Gender.hpp" #include "../Gender.hpp"
#include "SpeciesVariant.hpp"
namespace CreatureLib::Library { namespace CreatureLib::Library {
/*! /*!
\brief This holds the data required for a species of a creature, so the general data we can describe different creatures with. \brief This holds the data required for a species of a creature, so the general data we can describe different
creatures with.
*/ */
class CreatureSpecies { class CreatureSpecies {
GetProperty(uint16_t, Id); GetProperty(uint16_t, Id);
@ -16,15 +17,17 @@ namespace CreatureLib::Library {
GetProperty(std::string, GrowthRate); GetProperty(std::string, GrowthRate);
GetProperty(uint8_t, CaptureRate); GetProperty(uint8_t, CaptureRate);
GetProperty(uint8_t, BaseHappiness); GetProperty(uint8_t, BaseHappiness);
private: private:
std::unordered_map<std::string, const SpeciesVariant*> _variants; std::unordered_map<std::string, const SpeciesVariant*> _variants;
std::string _name; std::string _name;
public:
CreatureSpecies(uint16_t id, std::string name, const SpeciesVariant* defaultVariant,
float genderRatio, std::string growthRate, uint8_t captureRate, uint8_t baseHappiness);
~CreatureSpecies(){ public:
for (auto v: _variants) CreatureSpecies(uint16_t id, std::string name, const SpeciesVariant* defaultVariant, float genderRatio,
std::string growthRate, uint8_t captureRate, uint8_t baseHappiness);
~CreatureSpecies() {
for (auto v : _variants)
delete v.second; delete v.second;
_variants.clear(); _variants.clear();
} }
@ -35,4 +38,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif //CREATURELIB_CREATURESPECIES_HPP #endif // CREATURELIB_CREATURESPECIES_HPP

View File

@ -2,10 +2,8 @@
using namespace CreatureLib::Library; using namespace CreatureLib::Library;
void LearnableAttacks::AddLevelMove(uint8_t level, AttackData *attack) { void LearnableAttacks::AddLevelMove(uint8_t level, AttackData* attack) { _learnedByLevel[level].push_back(attack); }
_learnedByLevel[level].push_back(attack);
}
const std::vector<const AttackData *> &LearnableAttacks::GetMovesForLevel(uint8_t level) const { const std::vector<const AttackData*>& LearnableAttacks::GetMovesForLevel(uint8_t level) const {
return _learnedByLevel[level]; return _learnedByLevel[level];
} }

View File

@ -7,9 +7,9 @@
namespace CreatureLib::Library { namespace CreatureLib::Library {
class LearnableAttacks { class LearnableAttacks {
std::vector<std::vector<const AttackData*>> _learnedByLevel; std::vector<std::vector<const AttackData*>> _learnedByLevel;
public: public:
LearnableAttacks(uint8_t maxLevel) LearnableAttacks(uint8_t maxLevel) : _learnedByLevel(std::vector<std::vector<const AttackData*>>(maxLevel)) {}
:_learnedByLevel(std::vector<std::vector<const AttackData*>>(maxLevel)){}
void AddLevelMove(uint8_t level, AttackData* attack); void AddLevelMove(uint8_t level, AttackData* attack);
@ -17,5 +17,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif // CREATURELIB_LEARNABLEATTACKS_HPP
#endif //CREATURELIB_LEARNABLEATTACKS_HPP

View File

@ -2,24 +2,18 @@
#include <algorithm> #include <algorithm>
#include <utility> #include <utility>
const std::vector<uint8_t>& CreatureLib::Library::SpeciesVariant::GetTypes() const { const std::vector<uint8_t>& CreatureLib::Library::SpeciesVariant::GetTypes() const { return _types; }
return _types;
}
size_t CreatureLib::Library::SpeciesVariant::GetTypeCount() const { size_t CreatureLib::Library::SpeciesVariant::GetTypeCount() const { return _types.size(); }
return _types.size();
}
uint8_t CreatureLib::Library::SpeciesVariant::GetType(size_t index) const { uint8_t CreatureLib::Library::SpeciesVariant::GetType(size_t index) const { return _types[index]; }
return _types[index];
}
uint32_t CreatureLib::Library::SpeciesVariant::GetStatistic(CreatureLib::Core::Statistic stat) const { uint32_t CreatureLib::Library::SpeciesVariant::GetStatistic(CreatureLib::Core::Statistic stat) const {
return _baseStatistics.GetStat(stat); return _baseStatistics.GetStat(stat);
} }
const std::string& CreatureLib::Library::SpeciesVariant::GetTalent(int32_t index) const { const std::string& CreatureLib::Library::SpeciesVariant::GetTalent(int32_t index) const {
if (index < 0){ if (index < 0) {
index = -index - 1; index = -index - 1;
return _secretTalents[index]; return _secretTalents[index];
} }
@ -30,42 +24,34 @@ const std::string& CreatureLib::Library::SpeciesVariant::GetTalent(int32_t index
return &_moves; return &_moves;
}*/ }*/
int8_t CreatureLib::Library::SpeciesVariant::GetTalentIndex(const std::string& talent) const{ int8_t CreatureLib::Library::SpeciesVariant::GetTalentIndex(const std::string& talent) const {
auto i = std::find(_talents.begin(), _talents.end(), talent); auto i = std::find(_talents.begin(), _talents.end(), talent);
if (i != _talents.end()){ if (i != _talents.end()) {
return std::distance(_talents.begin(), i); return std::distance(_talents.begin(), i);
} }
i = std::find(_secretTalents.begin(), _secretTalents.end(), talent); i = std::find(_secretTalents.begin(), _secretTalents.end(), talent);
if (i != _secretTalents.end()){ if (i != _secretTalents.end()) {
return std::distance(_secretTalents.begin(), i); return std::distance(_secretTalents.begin(), i);
} }
throw CreatureException("The given talent is not a valid talent for this creature."); throw CreatureException("The given talent is not a valid talent for this creature.");
} }
int8_t CreatureLib::Library::SpeciesVariant::GetRandomTalent(CreatureLib::Core::Random *rand) const { int8_t CreatureLib::Library::SpeciesVariant::GetRandomTalent(CreatureLib::Core::Random* rand) const {
return rand->Get(_talents.size()); return rand->Get(_talents.size());
} }
const CreatureLib::Library::LearnableAttacks *CreatureLib::Library::SpeciesVariant::GetLearnableAttacks() const { const CreatureLib::Library::LearnableAttacks* CreatureLib::Library::SpeciesVariant::GetLearnableAttacks() const {
return _attacks; return _attacks;
} }
CreatureLib::Library::SpeciesVariant::SpeciesVariant(std::string name, float height, float weight, CreatureLib::Library::SpeciesVariant::SpeciesVariant(std::string name, float height, float weight,
uint32_t baseExperience, std::vector<uint8_t> types, uint32_t baseExperience, std::vector<uint8_t> types,
CreatureLib::Core::StatisticSet<uint16_t > baseStats, CreatureLib::Core::StatisticSet<uint16_t> baseStats,
std::vector<std::string> talents, std::vector<std::string> talents,
std::vector<std::string> secretTalents, const LearnableAttacks* attacks) std::vector<std::string> secretTalents,
: __Name(std::move(name)), const LearnableAttacks* attacks)
__Height(height), : __Name(std::move(name)), __Height(height), __Weight(weight), __BaseExperience(baseExperience),
__Weight(weight), _types(std::move(types)), _baseStatistics(baseStats), _talents(std::move(talents)),
__BaseExperience(baseExperience), _secretTalents(std::move(secretTalents)), _attacks(attacks) {}
_types(std::move(types)),
_baseStatistics(baseStats),
_talents(std::move(talents)),
_secretTalents(std::move(secretTalents)),
_attacks(attacks)
{}
CreatureLib::Library::SpeciesVariant::~SpeciesVariant() { CreatureLib::Library::SpeciesVariant::~SpeciesVariant() { delete _attacks; }
delete _attacks;
}

View File

@ -3,37 +3,40 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "CreatureMoves.hpp" #include "../../Core/Random.hpp"
#include "../../Core/StatisticSet.hpp" #include "../../Core/StatisticSet.hpp"
#include "../../GenericTemplates.cpp" #include "../../GenericTemplates.cpp"
#include "../../Core/Random.hpp" #include "CreatureMoves.hpp"
#include "LearnableAttacks.hpp" #include "LearnableAttacks.hpp"
namespace CreatureLib::Library { namespace CreatureLib::Library {
/*! /*!
\brief A single species can have more than one variant. This class holds the data for those variants. \brief A single species can have more than one variant. This class holds the data for those variants.
*/ */
class SpeciesVariant { class SpeciesVariant {
GetProperty(std::string, Name); GetProperty(std::string, Name);
GetProperty(float, Height); GetProperty(float, Height);
GetProperty(float, Weight); GetProperty(float, Weight);
GetProperty(uint32_t, BaseExperience); GetProperty(uint32_t, BaseExperience);
private: private:
std::vector<uint8_t > _types; std::vector<uint8_t> _types;
const Core::StatisticSet<uint16_t > _baseStatistics; const Core::StatisticSet<uint16_t> _baseStatistics;
std::vector<std::string> _talents; std::vector<std::string> _talents;
std::vector<std::string> _secretTalents; std::vector<std::string> _secretTalents;
const LearnableAttacks* _attacks; const LearnableAttacks* _attacks;
public: public:
SpeciesVariant(std::string name, float height, float weight, uint32_t baseExperience, SpeciesVariant(std::string name, float height, float weight, uint32_t baseExperience,
std::vector<uint8_t> types, Core::StatisticSet<uint16_t > baseStats, std::vector<std::string> talents, std::vector<uint8_t> types, Core::StatisticSet<uint16_t> baseStats,
std::vector<std::string> secretTalents, const LearnableAttacks* attacks); std::vector<std::string> talents, std::vector<std::string> secretTalents,
const LearnableAttacks* attacks);
~SpeciesVariant(); ~SpeciesVariant();
[[nodiscard]] size_t GetTypeCount() const; [[nodiscard]] size_t GetTypeCount() const;
[[nodiscard]] uint8_t GetType(size_t index) const; [[nodiscard]] uint8_t GetType(size_t index) const;
[[nodiscard]] const std::vector<uint8_t >& GetTypes() const; [[nodiscard]] const std::vector<uint8_t>& GetTypes() const;
[[nodiscard]] uint32_t GetStatistic(Core::Statistic stat) const; [[nodiscard]] uint32_t GetStatistic(Core::Statistic stat) const;
[[nodiscard]] const std::string& GetTalent(int32_t index) const; [[nodiscard]] const std::string& GetTalent(int32_t index) const;
[[nodiscard]] const LearnableAttacks* GetLearnableAttacks() const; [[nodiscard]] const LearnableAttacks* GetLearnableAttacks() const;
@ -42,4 +45,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif //CREATURELIB_SPECIESVARIANT_HPP #endif // CREATURELIB_SPECIESVARIANT_HPP

View File

@ -1,39 +1,31 @@
#include "DataLibrary.hpp" #include "DataLibrary.hpp"
CreatureLib::Library::DataLibrary::DataLibrary(LibrarySettings settings, CreatureLib::Library::DataLibrary::DataLibrary(LibrarySettings settings, CreatureLib::Library::SpeciesLibrary* species,
CreatureLib::Library::SpeciesLibrary *species, CreatureLib::Library::AttackLibrary* attacks,
CreatureLib::Library::AttackLibrary *attacks, CreatureLib::Library::ItemLibrary* items,
CreatureLib::Library::ItemLibrary *items, CreatureLib::Library::GrowthRateLibrary* growthRates,
CreatureLib::Library::GrowthRateLibrary *growthRates,
TypeLibrary* typeLibrary) TypeLibrary* typeLibrary)
: _settings(settings), _species(species), _attacks(attacks), _items(items), : _settings(settings), _species(species), _attacks(attacks), _items(items), _growthRates(growthRates),
_growthRates(growthRates), _typeLibrary(typeLibrary){ _typeLibrary(typeLibrary) {}
} const CreatureLib::Library::LibrarySettings& CreatureLib::Library::DataLibrary::GetSettings() const {
const CreatureLib::Library::LibrarySettings &CreatureLib::Library::DataLibrary::GetSettings() const {
return _settings; return _settings;
} }
const CreatureLib::Library::SpeciesLibrary *CreatureLib::Library::DataLibrary::GetSpeciesLibrary() const { const CreatureLib::Library::SpeciesLibrary* CreatureLib::Library::DataLibrary::GetSpeciesLibrary() const {
return _species; return _species;
} }
const CreatureLib::Library::AttackLibrary *CreatureLib::Library::DataLibrary::GetAttackLibrary() const { const CreatureLib::Library::AttackLibrary* CreatureLib::Library::DataLibrary::GetAttackLibrary() const {
return _attacks; return _attacks;
} }
const CreatureLib::Library::ItemLibrary *CreatureLib::Library::DataLibrary::GetItemLibrary() const { const CreatureLib::Library::ItemLibrary* CreatureLib::Library::DataLibrary::GetItemLibrary() const { return _items; }
return _items;
}
const CreatureLib::Library::GrowthRateLibrary *CreatureLib::Library::DataLibrary::GetGrowthRates() const { const CreatureLib::Library::GrowthRateLibrary* CreatureLib::Library::DataLibrary::GetGrowthRates() const {
return _growthRates; return _growthRates;
} }
const CreatureLib::Library::TypeLibrary *CreatureLib::Library::DataLibrary::GetTypeLibrary() const { const CreatureLib::Library::TypeLibrary* CreatureLib::Library::DataLibrary::GetTypeLibrary() const {
return _typeLibrary; return _typeLibrary;
} }

View File

@ -1,15 +1,15 @@
#ifndef CREATURELIB_DATALIBRARY_HPP #ifndef CREATURELIB_DATALIBRARY_HPP
#define CREATURELIB_DATALIBRARY_HPP #define CREATURELIB_DATALIBRARY_HPP
#include "SpeciesLibrary.hpp"
#include "AttackLibrary.hpp" #include "AttackLibrary.hpp"
#include "ItemLibrary.hpp"
#include "GrowthRates/GrowthRateLibrary.hpp" #include "GrowthRates/GrowthRateLibrary.hpp"
#include "ItemLibrary.hpp"
#include "LibrarySettings.hpp" #include "LibrarySettings.hpp"
#include "SpeciesLibrary.hpp"
#include "TypeLibrary.hpp" #include "TypeLibrary.hpp"
namespace CreatureLib::Library { namespace CreatureLib::Library {
/*! /*!
\brief The core library. This library holds all static data for a creature set. \brief The core library. This library holds all static data for a creature set.
*/ */
class DataLibrary { class DataLibrary {
@ -20,16 +20,13 @@ namespace CreatureLib::Library {
const ItemLibrary* _items; const ItemLibrary* _items;
const GrowthRateLibrary* _growthRates; const GrowthRateLibrary* _growthRates;
const TypeLibrary* _typeLibrary; const TypeLibrary* _typeLibrary;
public:
DataLibrary(LibrarySettings settings,
CreatureLib::Library::SpeciesLibrary *species,
CreatureLib::Library::AttackLibrary *attacks,
CreatureLib::Library::ItemLibrary *items,
CreatureLib::Library::GrowthRateLibrary *growthRates,
TypeLibrary* typeLibrary
);
~DataLibrary(){ public:
DataLibrary(LibrarySettings settings, CreatureLib::Library::SpeciesLibrary* species,
CreatureLib::Library::AttackLibrary* attacks, CreatureLib::Library::ItemLibrary* items,
CreatureLib::Library::GrowthRateLibrary* growthRates, TypeLibrary* typeLibrary);
~DataLibrary() {
delete _species; delete _species;
delete _attacks; delete _attacks;
delete _items; delete _items;
@ -46,5 +43,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif // CREATURELIB_DATALIBRARY_HPP
#endif //CREATURELIB_DATALIBRARY_HPP

View File

@ -3,16 +3,12 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library{ namespace CreatureLib::Library {
/*! /*!
\brief Might be somewhat controversial nowadays, but as many creature battling games only have two genders, we'll \brief Might be somewhat controversial nowadays, but as many creature battling games only have two genders, we'll
hardcode those. hardcode those.
*/ */
enum class Gender : uint8_t { enum class Gender : uint8_t { Male, Female, Genderless };
Male,
Female,
Genderless
};
} }
#endif //CREATURELIB_GENDER_HPP #endif // CREATURELIB_GENDER_HPP

View File

@ -11,4 +11,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif //CREATURELIB_GROWTHRATE_HPP #endif // CREATURELIB_GROWTHRATE_HPP

View File

@ -1,9 +1,11 @@
#include "GrowthRateLibrary.hpp" #include "GrowthRateLibrary.hpp"
uint8_t CreatureLib::Library::GrowthRateLibrary::CalculateLevel(const std::string &growthRate, uint32_t experience) const { uint8_t CreatureLib::Library::GrowthRateLibrary::CalculateLevel(const std::string& growthRate,
uint32_t experience) const {
return _growthRates.at(growthRate)->CalculateLevel(experience); return _growthRates.at(growthRate)->CalculateLevel(experience);
} }
uint32_t CreatureLib::Library::GrowthRateLibrary::CalculateExperience(const std::string &growthRate, uint8_t level) const { uint32_t CreatureLib::Library::GrowthRateLibrary::CalculateExperience(const std::string& growthRate,
uint8_t level) const {
return _growthRates.at(growthRate)->CalculateExperience(level); return _growthRates.at(growthRate)->CalculateExperience(level);
} }

View File

@ -6,14 +6,15 @@
#include <unordered_map> #include <unordered_map>
#include "GrowthRate.hpp" #include "GrowthRate.hpp"
namespace CreatureLib::Library{ namespace CreatureLib::Library {
class GrowthRateLibrary { class GrowthRateLibrary {
private: private:
std::unordered_map<std::string, GrowthRate*> _growthRates; std::unordered_map<std::string, GrowthRate*> _growthRates;
public: public:
[[nodiscard]] uint8_t CalculateLevel(const std::string& growthRate, uint32_t experience) const; [[nodiscard]] uint8_t CalculateLevel(const std::string& growthRate, uint32_t experience) const;
[[nodiscard]] uint32_t CalculateExperience(const std::string& growthRate, uint8_t level) const; [[nodiscard]] uint32_t CalculateExperience(const std::string& growthRate, uint8_t level) const;
}; };
} }
#endif //CREATURELIB_GROWTHRATELIBRARY_HPP #endif // CREATURELIB_GROWTHRATELIBRARY_HPP

View File

@ -1,17 +1,15 @@
#include "ItemLibrary.hpp" #include "ItemLibrary.hpp"
const CreatureLib::Library::Item *CreatureLib::Library::ItemLibrary::GetItem(const std::string &name) const { const CreatureLib::Library::Item* CreatureLib::Library::ItemLibrary::GetItem(const std::string& name) const {
return this->_items.at(name); return this->_items.at(name);
} }
const CreatureLib::Library::Item *CreatureLib::Library::ItemLibrary::operator[](const std::string &name) const { const CreatureLib::Library::Item* CreatureLib::Library::ItemLibrary::operator[](const std::string& name) const {
return this->GetItem(name); return this->GetItem(name);
} }
void CreatureLib::Library::ItemLibrary::LoadItem(const std::string &name, const CreatureLib::Library::Item *item) { void CreatureLib::Library::ItemLibrary::LoadItem(const std::string& name, const CreatureLib::Library::Item* item) {
this->_items.insert({name, item}); this->_items.insert({name, item});
} }
void CreatureLib::Library::ItemLibrary::DeleteItem(const std::string &name) { void CreatureLib::Library::ItemLibrary::DeleteItem(const std::string& name) { this->_items.erase(name); }
this->_items.erase(name);
}

View File

@ -8,21 +8,18 @@
namespace CreatureLib::Library { namespace CreatureLib::Library {
class ItemLibrary { class ItemLibrary {
private: private:
std::unordered_map<std::string, const Item *> _items; std::unordered_map<std::string, const Item*> _items;
public: public:
ItemLibrary() = default; ItemLibrary() = default;
~ItemLibrary(){ ~ItemLibrary() { _items.clear(); }
_items.clear();
}
[[nodiscard]] const Item* GetItem(const std::string& name) const; [[nodiscard]] const Item* GetItem(const std::string& name) const;
[[nodiscard]] const Item* operator[] (const std::string& name) const; [[nodiscard]] const Item* operator[](const std::string& name) const;
void LoadItem(const std::string& name, const Item* item); void LoadItem(const std::string& name, const Item* item);
void DeleteItem(const std::string& name); void DeleteItem(const std::string& name);
}; };
} }
#endif // CREATURELIB_ITEMLIBRARY_HPP
#endif //CREATURELIB_ITEMLIBRARY_HPP

View File

@ -4,13 +4,7 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library { namespace CreatureLib::Library {
enum class BattleItemCategory : uint8_t { enum class BattleItemCategory : uint8_t { None, Healing, StatusHealing, CaptureDevice, MiscBattleItem };
None,
Healing,
StatusHealing,
CaptureDevice,
MiscBattleItem
};
} }
#endif //CREATURELIB_BATTLEITEMCATEGORY_HPP #endif // CREATURELIB_BATTLEITEMCATEGORY_HPP

View File

@ -3,18 +3,20 @@
#include <string> #include <string>
#include <unordered_set> #include <unordered_set>
#include "ItemCategory.hpp"
#include "BattleItemCategory.hpp"
#include "../../GenericTemplates.cpp" #include "../../GenericTemplates.cpp"
#include "BattleItemCategory.hpp"
#include "ItemCategory.hpp"
namespace CreatureLib::Library { namespace CreatureLib::Library {
class Item { class Item {
GetProperty(std::string, Name); GetProperty(std::string, Name);
GetProperty(ItemCategory, Category); GetProperty(ItemCategory, Category);
GetProperty(BattleItemCategory, BattleCategory); GetProperty(BattleItemCategory, BattleCategory);
GetProperty(int32_t , Price); GetProperty(int32_t, Price);
private: private:
std::unordered_set<std::string> _flags; std::unordered_set<std::string> _flags;
public: public:
Item(std::string name, ItemCategory category, BattleItemCategory battleCategory, int32_t price, Item(std::string name, ItemCategory category, BattleItemCategory battleCategory, int32_t price,
std::unordered_set<std::string> flags); std::unordered_set<std::string> flags);
@ -23,4 +25,4 @@ namespace CreatureLib::Library {
}; };
} }
#endif //CREATURELIB_ITEM_HPP #endif // CREATURELIB_ITEM_HPP

View File

@ -3,7 +3,7 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library{ namespace CreatureLib::Library {
enum class ItemCategory : uint8_t { enum class ItemCategory : uint8_t {
MiscItem, MiscItem,
CaptureDevice, CaptureDevice,
@ -16,4 +16,4 @@ namespace CreatureLib::Library{
}; };
} }
#endif //CREATURELIB_ITEMCATEGORY_HPP #endif // CREATURELIB_ITEMCATEGORY_HPP

View File

@ -4,21 +4,18 @@
#include <cstdint> #include <cstdint>
namespace CreatureLib::Library { namespace CreatureLib::Library {
class LibrarySettings{ class LibrarySettings {
uint8_t _maximalLevel; uint8_t _maximalLevel;
uint8_t _maximalMoves; uint8_t _maximalMoves;
public: public:
LibrarySettings(uint8_t maximalLevel, uint8_t maximalMoves) LibrarySettings(uint8_t maximalLevel, uint8_t maximalMoves)
: _maximalLevel(maximalLevel), _maximalMoves(maximalMoves){} : _maximalLevel(maximalLevel), _maximalMoves(maximalMoves) {}
inline uint8_t GetMaximalLevel() const{ inline uint8_t GetMaximalLevel() const { return _maximalLevel; }
return _maximalLevel;
}
inline uint8_t GetMaximalMoves() const{ inline uint8_t GetMaximalMoves() const { return _maximalMoves; }
return _maximalMoves;
}
}; };
} }
#endif //CREATURELIB_LIBRARYSETTINGS_HPP #endif // CREATURELIB_LIBRARYSETTINGS_HPP

View File

@ -1,19 +1,18 @@
#include "SpeciesLibrary.hpp" #include "SpeciesLibrary.hpp"
const CreatureLib::Library::CreatureSpecies *CreatureLib::Library::SpeciesLibrary::GetSpecies(const std::string& name) const{ const CreatureLib::Library::CreatureSpecies*
CreatureLib::Library::SpeciesLibrary::GetSpecies(const std::string& name) const {
return _species.at(name); return _species.at(name);
} }
const CreatureLib::Library::CreatureSpecies* CreatureLib::Library::SpeciesLibrary::operator[](const std::string &name) const{ const CreatureLib::Library::CreatureSpecies*
CreatureLib::Library::SpeciesLibrary::operator[](const std::string& name) const {
return GetSpecies(name); return GetSpecies(name);
} }
void CreatureLib::Library::SpeciesLibrary::LoadSpecies(const std::string &name, void CreatureLib::Library::SpeciesLibrary::LoadSpecies(const std::string& name,
const CreatureLib::Library::CreatureSpecies* species) { const CreatureLib::Library::CreatureSpecies* species) {
_species.insert({name, species}); _species.insert({name, species});
} }
void CreatureLib::Library::SpeciesLibrary::DeleteSpecies(const std::string &name) { void CreatureLib::Library::SpeciesLibrary::DeleteSpecies(const std::string& name) { _species.erase(name); }
_species.erase(name);
}

View File

@ -9,22 +9,22 @@ namespace CreatureLib::Library {
class SpeciesLibrary { class SpeciesLibrary {
private: private:
std::unordered_map<std::string, const CreatureSpecies*> _species; std::unordered_map<std::string, const CreatureSpecies*> _species;
public: public:
SpeciesLibrary() = default; SpeciesLibrary() = default;
~SpeciesLibrary(){ ~SpeciesLibrary() {
for (auto s: _species) for (auto s : _species)
delete s.second; delete s.second;
_species.clear(); _species.clear();
} }
[[nodiscard]] const CreatureSpecies* GetSpecies(const std::string& name) const; [[nodiscard]] const CreatureSpecies* GetSpecies(const std::string& name) const;
[[nodiscard]] const CreatureSpecies* operator[] (const std::string& name) const; [[nodiscard]] const CreatureSpecies* operator[](const std::string& name) const;
void LoadSpecies(const std::string& name, const CreatureSpecies* species); void LoadSpecies(const std::string& name, const CreatureSpecies* species);
void DeleteSpecies(const std::string& name); void DeleteSpecies(const std::string& name);
}; };
} }
#endif // CREATURELIB_SPECIESLIBRARY_HPP
#endif //CREATURELIB_SPECIESLIBRARY_HPP

View File

@ -2,9 +2,9 @@
using namespace CreatureLib::Library; using namespace CreatureLib::Library;
float TypeLibrary::GetEffectiveness(uint8_t attacking, const std::vector<uint8_t> &defensive) const { float TypeLibrary::GetEffectiveness(uint8_t attacking, const std::vector<uint8_t>& defensive) const {
auto eff = 1; auto eff = 1;
for (auto def: defensive){ for (auto def : defensive) {
eff *= GetSingleEffectiveness(attacking, def); eff *= GetSingleEffectiveness(attacking, def);
} }
return eff; return eff;
@ -14,14 +14,12 @@ float TypeLibrary::GetSingleEffectiveness(uint8_t attacking, uint8_t defensive)
return _effectiveness[attacking][defensive]; return _effectiveness[attacking][defensive];
} }
uint8_t TypeLibrary::GetTypeId(const std::string &s) const { uint8_t TypeLibrary::GetTypeId(const std::string& s) const { return _types.at(s); }
return _types.at(s);
}
uint8_t TypeLibrary::RegisterType(const std::string& typeName) { uint8_t TypeLibrary::RegisterType(const std::string& typeName) {
_types.insert({typeName, _types.size()}); _types.insert({typeName, _types.size()});
_effectiveness.resize(_types.size()); _effectiveness.resize(_types.size());
for (auto & eff : _effectiveness){ for (auto& eff : _effectiveness) {
eff.resize(_types.size(), 1); eff.resize(_types.size(), 1);
} }
return _types.size() - 1; return _types.size() - 1;

View File

@ -4,10 +4,11 @@
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
namespace CreatureLib::Library{ namespace CreatureLib::Library {
class TypeLibrary { class TypeLibrary {
std::unordered_map<std::string, uint8_t > _types; std::unordered_map<std::string, uint8_t> _types;
std::vector<std::vector<float>> _effectiveness; std::vector<std::vector<float>> _effectiveness;
public: public:
uint8_t GetTypeId(const std::string& s) const; uint8_t GetTypeId(const std::string& s) const;
float GetSingleEffectiveness(uint8_t attacking, uint8_t defensive) const; float GetSingleEffectiveness(uint8_t attacking, uint8_t defensive) const;
@ -18,5 +19,4 @@ namespace CreatureLib::Library{
}; };
} }
#endif // CREATURELIB_TYPELIBRARY_HPP
#endif //CREATURELIB_TYPELIBRARY_HPP

View File

@ -1,13 +1,13 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include "../TestLibrary/TestLibrary.cpp"
#include "../../src/Battling/Models/BattleSide.hpp" #include "../../src/Battling/Models/BattleSide.hpp"
#include "../../src/Battling/Models/CreateCreature.hpp" #include "../../src/Battling/Models/CreateCreature.hpp"
#include "../../src/Battling/TurnChoices/PassTurnChoice.hpp" #include "../../src/Battling/TurnChoices/PassTurnChoice.hpp"
#include "../TestLibrary/TestLibrary.cpp"
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
TEST_CASE( "Set Choice one-sized side", "[Battling]" ) { TEST_CASE("Set Choice one-sized side", "[Battling]") {
auto side = BattleSide(nullptr, 1); auto side = BattleSide(nullptr, 1);
auto c = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
side.SetCreature(c, 0); side.SetCreature(c, 0);
@ -17,7 +17,7 @@ TEST_CASE( "Set Choice one-sized side", "[Battling]" ) {
delete c; delete c;
} }
TEST_CASE( "Set Choice one-sized side, validate all choices set", "[Battling]" ) { TEST_CASE("Set Choice one-sized side, validate all choices set", "[Battling]") {
auto side = BattleSide(nullptr, 1); auto side = BattleSide(nullptr, 1);
auto c = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
side.SetCreature(c, 0); side.SetCreature(c, 0);
@ -29,7 +29,7 @@ TEST_CASE( "Set Choice one-sized side, validate all choices set", "[Battling]" )
delete c; delete c;
} }
TEST_CASE( "Set Choice two-sized side", "[Battling]" ) { TEST_CASE("Set Choice two-sized side", "[Battling]") {
auto side = BattleSide(nullptr, 2); auto side = BattleSide(nullptr, 2);
auto c1 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c1 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
auto c2 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c2 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
@ -45,7 +45,7 @@ TEST_CASE( "Set Choice two-sized side", "[Battling]" ) {
delete c2; delete c2;
} }
TEST_CASE( "Set Choice two-sized side, validate all choices set", "[Battling]" ) { TEST_CASE("Set Choice two-sized side, validate all choices set", "[Battling]") {
auto side = BattleSide(nullptr, 2); auto side = BattleSide(nullptr, 2);
auto c1 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c1 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
auto c2 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create(); auto c2 = CreateCreature(GetLibrary(), "testSpecies1", 5).Create();
@ -64,5 +64,4 @@ TEST_CASE( "Set Choice two-sized side, validate all choices set", "[Battling]" )
delete c2; delete c2;
} }
#endif #endif

View File

@ -1,31 +1,25 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include <utility> #include <utility>
#include "../../../extern/catch.hpp" #include "../../../extern/catch.hpp"
#include "../../../src/Battling/ScriptHandling/ScriptAggregator.hpp" #include "../../../src/Battling/ScriptHandling/ScriptAggregator.hpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
class TestScript : public Script{ class TestScript : public Script {
public: public:
explicit TestScript(std::string name) : Script(std::move(name)){}; explicit TestScript(std::string name) : Script(std::move(name)){};
void TestMethod(int& runCount) { void TestMethod(int& runCount) { runCount++; }
runCount++;
}
}; };
TEST_CASE( "Script Aggregator properly iterates containing script.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates containing script.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
auto ran = 0; auto ran = 0;
auto vec = std::vector<ScriptWrapper>{&script}; auto vec = std::vector<ScriptWrapper>{&script};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -34,14 +28,14 @@ TEST_CASE( "Script Aggregator properly iterates containing script.", "[Battling,
delete script; delete script;
} }
TEST_CASE( "Script Aggregator properly iterates multiple scripts.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates multiple scripts.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
Script* script2 = new TestScript("test2"); Script* script2 = new TestScript("test2");
Script* script3 = new TestScript("test3"); Script* script3 = new TestScript("test3");
auto ran = 0; auto ran = 0;
auto vec = std::vector<ScriptWrapper>{&script, &script2, &script3}; auto vec = std::vector<ScriptWrapper>{&script, &script2, &script3};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -52,7 +46,7 @@ TEST_CASE( "Script Aggregator properly iterates multiple scripts.", "[Battling,
delete script3; delete script3;
} }
TEST_CASE( "Script Aggregator properly iterates Script Set.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates Script Set.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
Script* script2 = new TestScript("test2"); Script* script2 = new TestScript("test2");
Script* script3 = new TestScript("test3"); Script* script3 = new TestScript("test3");
@ -63,7 +57,7 @@ TEST_CASE( "Script Aggregator properly iterates Script Set.", "[Battling, Script
set.Add(script3); set.Add(script3);
auto vec = std::vector<ScriptWrapper>{&set}; auto vec = std::vector<ScriptWrapper>{&set};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -74,7 +68,7 @@ TEST_CASE( "Script Aggregator properly iterates Script Set.", "[Battling, Script
delete script3; delete script3;
} }
TEST_CASE( "Script Aggregator properly iterates data of Script Set and Script.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates data of Script Set and Script.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
Script* script2 = new TestScript("test2"); Script* script2 = new TestScript("test2");
Script* script3 = new TestScript("test3"); Script* script3 = new TestScript("test3");
@ -84,7 +78,7 @@ TEST_CASE( "Script Aggregator properly iterates data of Script Set and Script.",
set.Add(script3); set.Add(script3);
auto vec = std::vector<ScriptWrapper>{&set, &script}; auto vec = std::vector<ScriptWrapper>{&set, &script};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -95,7 +89,7 @@ TEST_CASE( "Script Aggregator properly iterates data of Script Set and Script.",
delete script3; delete script3;
} }
TEST_CASE( "Script Aggregator properly iterates data of Script and Script Set.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates data of Script and Script Set.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
Script* script2 = new TestScript("test2"); Script* script2 = new TestScript("test2");
Script* script3 = new TestScript("test3"); Script* script3 = new TestScript("test3");
@ -105,7 +99,7 @@ TEST_CASE( "Script Aggregator properly iterates data of Script and Script Set.",
set.Add(script3); set.Add(script3);
auto vec = std::vector<ScriptWrapper>{&script, &set}; auto vec = std::vector<ScriptWrapper>{&script, &set};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -116,7 +110,7 @@ TEST_CASE( "Script Aggregator properly iterates data of Script and Script Set.",
delete script3; delete script3;
} }
TEST_CASE( "Script Aggregator properly iterates data of Script, Script Set and Script.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates data of Script, Script Set and Script.", "[Battling, Scripting]") {
Script* script = new TestScript("test"); Script* script = new TestScript("test");
Script* script2 = new TestScript("test2"); Script* script2 = new TestScript("test2");
Script* script3 = new TestScript("test3"); Script* script3 = new TestScript("test3");
@ -127,7 +121,7 @@ TEST_CASE( "Script Aggregator properly iterates data of Script, Script Set and S
set.Add(script3); set.Add(script3);
auto vec = std::vector<ScriptWrapper>{&script, &set, &script4}; auto vec = std::vector<ScriptWrapper>{&script, &set, &script4};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next != nullptr); REQUIRE(next != nullptr);
dynamic_cast<TestScript*>(next)->TestMethod(ran); dynamic_cast<TestScript*>(next)->TestMethod(ran);
@ -139,22 +133,22 @@ TEST_CASE( "Script Aggregator properly iterates data of Script, Script Set and S
delete script4; delete script4;
} }
TEST_CASE( "Script Aggregator properly iterates when empty.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates when empty.", "[Battling, Scripting]") {
auto ran = 0; auto ran = 0;
auto vec = std::vector<ScriptWrapper>{}; auto vec = std::vector<ScriptWrapper>{};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
throw CreatureException("Aggregator returned a script, but should have been empty."); throw CreatureException("Aggregator returned a script, but should have been empty.");
} }
CHECK(ran == 0); CHECK(ran == 0);
} }
TEST_CASE( "Script Aggregator properly iterates empty Script Set.", "[Battling, Scripting]" ) { TEST_CASE("Script Aggregator properly iterates empty Script Set.", "[Battling, Scripting]") {
auto ran = 0; auto ran = 0;
auto set = ScriptSet(); auto set = ScriptSet();
auto vec = std::vector<ScriptWrapper>{&set}; auto vec = std::vector<ScriptWrapper>{&set};
auto aggr = ScriptAggregator(vec); auto aggr = ScriptAggregator(vec);
while (aggr.HasNext()){ while (aggr.HasNext()) {
auto next = aggr.GetNext(); auto next = aggr.GetNext();
REQUIRE(next == nullptr); REQUIRE(next == nullptr);
ran++; ran++;
@ -162,8 +156,4 @@ TEST_CASE( "Script Aggregator properly iterates empty Script Set.", "[Battling,
CHECK(ran == 1); CHECK(ran == 1);
} }
#endif #endif

View File

@ -1,20 +1,18 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include <utility> #include <utility>
#include "../../../extern/catch.hpp" #include "../../../extern/catch.hpp"
#include "../../../src/Battling/ScriptHandling/ScriptSet.hpp" #include "../../../src/Battling/ScriptHandling/ScriptSet.hpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
TEST_CASE("Empty script set count == 0", "[Battling, Scripting]") {
TEST_CASE( "Empty script set count == 0", "[Battling, Scripting]" ) {
auto set = ScriptSet(); auto set = ScriptSet();
REQUIRE(set.Count() == 0); REQUIRE(set.Count() == 0);
} }
TEST_CASE( "Add script to script set", "[Battling, Scripting]" ) { TEST_CASE("Add script to script set", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
set.Add(s); set.Add(s);
@ -22,7 +20,7 @@ TEST_CASE( "Add script to script set", "[Battling, Scripting]" ) {
delete s; delete s;
} }
TEST_CASE( "Add script to script set, then retrieve it", "[Battling, Scripting]" ) { TEST_CASE("Add script to script set, then retrieve it", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
set.Add(s); set.Add(s);
@ -32,7 +30,7 @@ TEST_CASE( "Add script to script set, then retrieve it", "[Battling, Scripting]"
delete s; delete s;
} }
TEST_CASE( "Add two scripts to script set", "[Battling, Scripting]" ) { TEST_CASE("Add two scripts to script set", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
auto s2 = new Script("foobar2"); auto s2 = new Script("foobar2");
@ -43,7 +41,7 @@ TEST_CASE( "Add two scripts to script set", "[Battling, Scripting]" ) {
delete s2; delete s2;
} }
TEST_CASE( "Add two scripts to script set, then retrieve them", "[Battling, Scripting]" ) { TEST_CASE("Add two scripts to script set, then retrieve them", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
auto s2 = new Script("foobar2"); auto s2 = new Script("foobar2");
@ -58,7 +56,7 @@ TEST_CASE( "Add two scripts to script set, then retrieve them", "[Battling, Scri
delete s2; delete s2;
} }
TEST_CASE( "Add script to script set, then remove it", "[Battling, Scripting]" ) { TEST_CASE("Add script to script set, then remove it", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
set.Add(s); set.Add(s);
@ -70,7 +68,7 @@ TEST_CASE( "Add script to script set, then remove it", "[Battling, Scripting]" )
delete s; delete s;
} }
TEST_CASE( "Add two scripts to script set, then remove them", "[Battling, Scripting]" ) { TEST_CASE("Add two scripts to script set, then remove them", "[Battling, Scripting]") {
auto set = ScriptSet(); auto set = ScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
auto s2 = new Script("foobar2"); auto s2 = new Script("foobar2");
@ -85,9 +83,4 @@ TEST_CASE( "Add two scripts to script set, then remove them", "[Battling, Script
delete s2; delete s2;
} }
#endif #endif

View File

@ -1,50 +1,44 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include <utility>
#include "../../../extern/catch.hpp"
#include "../../../src/Battling/ScriptHandling/ScriptSource.hpp" #include "../../../src/Battling/ScriptHandling/ScriptSource.hpp"
#include <utility>
#include "../../../extern/catch.hpp"
#include "../../../src/Battling/ScriptHandling/ScriptAggregator.hpp" #include "../../../src/Battling/ScriptHandling/ScriptAggregator.hpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
class TestScript : public Script{ class TestScript : public Script {
public: public:
explicit TestScript(std::string name) : Script(std::move(name)){}; explicit TestScript(std::string name) : Script(std::move(name)){};
void TestMethod(int& runCount) { void TestMethod(int& runCount) { runCount++; }
runCount++;
}
}; };
class ScriptSourceWithScriptPtr : public ScriptSource{ class ScriptSourceWithScriptPtr : public ScriptSource {
public: public:
Script* ScriptPtr = nullptr; Script* ScriptPtr = nullptr;
protected: protected:
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override { void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override { scripts.emplace_back(&ScriptPtr); }
scripts.emplace_back(&ScriptPtr);
}
}; };
class ScriptSourceWithScriptSet : public ScriptSource{ class ScriptSourceWithScriptSet : public ScriptSource {
public: public:
ScriptSet Set; ScriptSet Set;
protected: protected:
void GetActiveScripts(std::vector<ScriptWrapper> &scripts) override { void GetActiveScripts(std::vector<ScriptWrapper>& scripts) override { scripts.emplace_back(&Set); }
scripts.emplace_back(&Set);
}
}; };
TEST_CASE("Script source with unset script ptr.", "[Battling, Scripting]") {
TEST_CASE( "Script source with unset script ptr.", "[Battling, Scripting]" ) {
auto source = ScriptSourceWithScriptPtr(); auto source = ScriptSourceWithScriptPtr();
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
auto first = scripts.GetNext(); auto first = scripts.GetNext();
CHECK(first == nullptr); CHECK(first == nullptr);
} }
TEST_CASE( "Script source with script ptr being set.", "[Battling, Scripting]" ) { TEST_CASE("Script source with script ptr being set.", "[Battling, Scripting]") {
auto source = ScriptSourceWithScriptPtr(); auto source = ScriptSourceWithScriptPtr();
source.ScriptPtr = new Script("foobar"); source.ScriptPtr = new Script("foobar");
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
@ -53,7 +47,7 @@ TEST_CASE( "Script source with script ptr being set.", "[Battling, Scripting]" )
delete source.ScriptPtr; delete source.ScriptPtr;
} }
TEST_CASE( "Script source with script ptr being set after first iteration.", "[Battling, Scripting]" ) { TEST_CASE("Script source with script ptr being set after first iteration.", "[Battling, Scripting]") {
auto source = ScriptSourceWithScriptPtr(); auto source = ScriptSourceWithScriptPtr();
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
auto first = scripts.GetNext(); auto first = scripts.GetNext();
@ -65,25 +59,25 @@ TEST_CASE( "Script source with script ptr being set after first iteration.", "[B
delete source.ScriptPtr; delete source.ScriptPtr;
} }
TEST_CASE( "Script source with empty script set.", "[Battling, Scripting]" ) { TEST_CASE("Script source with empty script set.", "[Battling, Scripting]") {
auto source = ScriptSourceWithScriptSet(); auto source = ScriptSourceWithScriptSet();
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
auto first = scripts.GetNext(); auto first = scripts.GetNext();
CHECK(first == nullptr); CHECK(first == nullptr);
} }
TEST_CASE( "Script source with single item script set.", "[Battling, Scripting]" ) { TEST_CASE("Script source with single item script set.", "[Battling, Scripting]") {
auto source = ScriptSourceWithScriptSet(); auto source = ScriptSourceWithScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
source.Set.Add(s); source.Set.Add(s);
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
auto first = scripts.GetNext(); auto first = scripts.GetNext();
CHECK(first != nullptr); CHECK(first != nullptr);
CHECK (first->GetName() == "foobar"); CHECK(first->GetName() == "foobar");
delete s; delete s;
} }
TEST_CASE( "Script source with multiple item script set.", "[Battling, Scripting]" ) { TEST_CASE("Script source with multiple item script set.", "[Battling, Scripting]") {
auto source = ScriptSourceWithScriptSet(); auto source = ScriptSourceWithScriptSet();
auto s = new Script("foobar"); auto s = new Script("foobar");
auto s2 = new Script("foobar2"); auto s2 = new Script("foobar2");
@ -92,14 +86,12 @@ TEST_CASE( "Script source with multiple item script set.", "[Battling, Scripting
auto scripts = source.GetScriptIterator(); auto scripts = source.GetScriptIterator();
auto first = scripts.GetNext(); auto first = scripts.GetNext();
CHECK(first != nullptr); CHECK(first != nullptr);
CHECK (first->GetName() == "foobar"); CHECK(first->GetName() == "foobar");
auto second = scripts.GetNext(); auto second = scripts.GetNext();
CHECK(second != nullptr); CHECK(second != nullptr);
CHECK (second->GetName() == "foobar2"); CHECK(second->GetName() == "foobar2");
delete s; delete s;
delete s2; delete s2;
} }
#endif #endif

View File

@ -1,23 +1,23 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include "../TestLibrary/TestLibrary.cpp"
#include "../../src/Battling/TurnChoices/PassTurnChoice.hpp"
#include "../../src/Battling/TurnChoices/AttackTurnChoice.hpp"
#include "../../src/Battling/Flow/TurnOrdering.hpp" #include "../../src/Battling/Flow/TurnOrdering.hpp"
#include "../../src/Battling/TurnChoices/AttackTurnChoice.hpp"
#include "../../src/Battling/TurnChoices/PassTurnChoice.hpp"
#include "../TestLibrary/TestLibrary.cpp"
using namespace CreatureLib; using namespace CreatureLib;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
TEST_CASE( "Turn ordering: Attack before pass", "[Battling]" ) { TEST_CASE("Turn ordering: Attack before pass", "[Battling]") {
auto choice1 = new PassTurnChoice(nullptr); auto choice1 = new PassTurnChoice(nullptr);
auto choice2 = new AttackTurnChoice(nullptr, nullptr, Target(0,0)); auto choice2 = new AttackTurnChoice(nullptr, nullptr, Target(0, 0));
auto vec = std::vector<BaseTurnChoice*>{choice1, choice2}; auto vec = std::vector<BaseTurnChoice*>{choice1, choice2};
auto rand = Core::Random(); auto rand = Core::Random();
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
vec = std::vector<BaseTurnChoice*>{choice2, choice1}; vec = std::vector<BaseTurnChoice*>{choice2, choice1};
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
@ -25,19 +25,19 @@ TEST_CASE( "Turn ordering: Attack before pass", "[Battling]" ) {
delete choice2; delete choice2;
} }
TEST_CASE( "Turn ordering: High priority goes before no priority", "[Battling]" ) { TEST_CASE("Turn ordering: High priority goes before no priority", "[Battling]") {
auto l = GetLibrary()->GetAttackLibrary(); auto l = GetLibrary()->GetAttackLibrary();
auto a1 = new LearnedAttack(l->GetAttack("standard"), AttackLearnMethod::Unknown); auto a1 = new LearnedAttack(l->GetAttack("standard"), AttackLearnMethod::Unknown);
auto a2 = new LearnedAttack(l->GetAttack("highPriority"), AttackLearnMethod::Unknown); auto a2 = new LearnedAttack(l->GetAttack("highPriority"), AttackLearnMethod::Unknown);
auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0,0)); auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0, 0));
auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0,0)); auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0, 0));
auto vec = std::vector<BaseTurnChoice*>{choice1, choice2}; auto vec = std::vector<BaseTurnChoice*>{choice1, choice2};
auto rand = Core::Random(); auto rand = Core::Random();
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
vec = std::vector<BaseTurnChoice*>{choice2, choice1}; vec = std::vector<BaseTurnChoice*>{choice2, choice1};
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
@ -47,19 +47,19 @@ TEST_CASE( "Turn ordering: High priority goes before no priority", "[Battling]"
delete a2; delete a2;
} }
TEST_CASE( "Turn ordering: Higher priority goes before high priority", "[Battling]" ) { TEST_CASE("Turn ordering: Higher priority goes before high priority", "[Battling]") {
auto l = GetLibrary()->GetAttackLibrary(); auto l = GetLibrary()->GetAttackLibrary();
auto a1 = new LearnedAttack(l->GetAttack("highPriority"), AttackLearnMethod::Unknown); auto a1 = new LearnedAttack(l->GetAttack("highPriority"), AttackLearnMethod::Unknown);
auto a2 = new LearnedAttack(l->GetAttack("higherPriority"), AttackLearnMethod::Unknown); auto a2 = new LearnedAttack(l->GetAttack("higherPriority"), AttackLearnMethod::Unknown);
auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0,0)); auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0, 0));
auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0,0)); auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0, 0));
auto vec = std::vector<BaseTurnChoice*>{choice1, choice2}; auto vec = std::vector<BaseTurnChoice*>{choice1, choice2};
auto rand = Core::Random(); auto rand = Core::Random();
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
vec = std::vector<BaseTurnChoice*>{choice2, choice1}; vec = std::vector<BaseTurnChoice*>{choice2, choice1};
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
@ -69,19 +69,19 @@ TEST_CASE( "Turn ordering: Higher priority goes before high priority", "[Battlin
delete a2; delete a2;
} }
TEST_CASE( "Turn ordering: High priority goes before low priority", "[Battling]" ) { TEST_CASE("Turn ordering: High priority goes before low priority", "[Battling]") {
auto l = GetLibrary()->GetAttackLibrary(); auto l = GetLibrary()->GetAttackLibrary();
auto a1 = new LearnedAttack(l->GetAttack("lowPriority"), AttackLearnMethod::Unknown); auto a1 = new LearnedAttack(l->GetAttack("lowPriority"), AttackLearnMethod::Unknown);
auto a2 = new LearnedAttack(l->GetAttack("higherPriority"), AttackLearnMethod::Unknown); auto a2 = new LearnedAttack(l->GetAttack("higherPriority"), AttackLearnMethod::Unknown);
auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0,0)); auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0, 0));
auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0,0)); auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0, 0));
auto vec = std::vector<BaseTurnChoice*>{choice1, choice2}; auto vec = std::vector<BaseTurnChoice*>{choice1, choice2};
auto rand = Core::Random(); auto rand = Core::Random();
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
vec = std::vector<BaseTurnChoice*>{choice2, choice1}; vec = std::vector<BaseTurnChoice*>{choice2, choice1};
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
@ -91,19 +91,19 @@ TEST_CASE( "Turn ordering: High priority goes before low priority", "[Battling]"
delete a2; delete a2;
} }
TEST_CASE( "Turn ordering: No priority goes before low priority", "[Battling]" ) { TEST_CASE("Turn ordering: No priority goes before low priority", "[Battling]") {
auto l = GetLibrary()->GetAttackLibrary(); auto l = GetLibrary()->GetAttackLibrary();
auto a1 = new LearnedAttack(l->GetAttack("lowPriority"), AttackLearnMethod::Unknown); auto a1 = new LearnedAttack(l->GetAttack("lowPriority"), AttackLearnMethod::Unknown);
auto a2 = new LearnedAttack(l->GetAttack("standard"), AttackLearnMethod::Unknown); auto a2 = new LearnedAttack(l->GetAttack("standard"), AttackLearnMethod::Unknown);
auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0,0)); auto choice1 = new AttackTurnChoice(nullptr, a1, Target(0, 0));
auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0,0)); auto choice2 = new AttackTurnChoice(nullptr, a2, Target(0, 0));
auto vec = std::vector<BaseTurnChoice*>{choice1, choice2}; auto vec = std::vector<BaseTurnChoice*>{choice1, choice2};
auto rand = Core::Random(); auto rand = Core::Random();
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
vec = std::vector<BaseTurnChoice*>{choice2, choice1}; vec = std::vector<BaseTurnChoice*>{choice2, choice1};
TurnOrdering::OrderChoices(vec,rand); TurnOrdering::OrderChoices(vec, rand);
CHECK(vec[0] == choice2); CHECK(vec[0] == choice2);
CHECK(vec[1] == choice1); CHECK(vec[1] == choice1);
@ -113,6 +113,4 @@ TEST_CASE( "Turn ordering: No priority goes before low priority", "[Battling]" )
delete a2; delete a2;
} }
#endif #endif

View File

@ -3,41 +3,41 @@
#include "../TestLibrary/TestLibrary.cpp" #include "../TestLibrary/TestLibrary.cpp"
using namespace CreatureLib::Library; using namespace CreatureLib::Library;
TEST_CASE( "Create basic creature", "[Library]" ) { TEST_CASE("Create basic creature", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
delete creature; delete creature;
} }
TEST_CASE( "Get creature species", "[Library]" ) { TEST_CASE("Get creature species", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
REQUIRE(creature->GetSpecies()->GetName() == "testSpecies1"); REQUIRE(creature->GetSpecies()->GetName() == "testSpecies1");
delete creature; delete creature;
} }
TEST_CASE( "Get creature level", "[Library]" ) { TEST_CASE("Get creature level", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
REQUIRE(creature->GetLevel() == 1); REQUIRE(creature->GetLevel() == 1);
delete creature; delete creature;
} }
TEST_CASE( "Get creature variant when unset", "[Library]" ) { TEST_CASE("Get creature variant when unset", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
REQUIRE(creature->GetVariant()->GetName() == "default"); REQUIRE(creature->GetVariant()->GetName() == "default");
delete creature; delete creature;
} }
TEST_CASE( "Get creature nickname when unset", "[Library]" ) { TEST_CASE("Get creature nickname when unset", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
REQUIRE(creature->GetNickname() == "testSpecies1"); REQUIRE(creature->GetNickname() == "testSpecies1");
delete creature; delete creature;
} }
TEST_CASE( "Get creature stat potentials when unset", "[Library]" ) { TEST_CASE("Get creature stat potentials when unset", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
auto potentials = creature->GetStatPotential(); auto potentials = creature->GetStatPotential();
@ -50,7 +50,7 @@ TEST_CASE( "Get creature stat potentials when unset", "[Library]" ) {
delete creature; delete creature;
} }
TEST_CASE( "Get creature stat experience when unset", "[Library]" ) { TEST_CASE("Get creature stat experience when unset", "[Library]") {
auto library = GetLibrary(); auto library = GetLibrary();
auto creature = CreateCreature(library, "testSpecies1", 1).Create(); auto creature = CreateCreature(library, "testSpecies1", 1).Create();
auto experiences = creature->GetStatExperience(); auto experiences = creature->GetStatExperience();

View File

@ -4,34 +4,34 @@
#include "../../extern/catch.hpp" #include "../../extern/catch.hpp"
#include "../TestLibrary/TestLibrary.cpp" #include "../TestLibrary/TestLibrary.cpp"
TEST_CASE( "Can Create Species Library", "[Library]" ) { TEST_CASE("Can Create Species Library", "[Library]") {
auto l = BuildSpeciesLibrary(); auto l = BuildSpeciesLibrary();
REQUIRE(l != nullptr); REQUIRE(l != nullptr);
delete l; delete l;
} }
TEST_CASE( "Can Create Attack Library", "[Library]" ) { TEST_CASE("Can Create Attack Library", "[Library]") {
auto l = BuildAttackLibrary(); auto l = BuildAttackLibrary();
REQUIRE(l != nullptr); REQUIRE(l != nullptr);
delete l; delete l;
} }
TEST_CASE( "Can Create Item Library", "[Library]" ) { TEST_CASE("Can Create Item Library", "[Library]") {
auto l = BuildItemLibrary(); auto l = BuildItemLibrary();
REQUIRE(l != nullptr); REQUIRE(l != nullptr);
delete l; delete l;
} }
TEST_CASE( "Can Create Growthrate Library", "[Library]" ) { TEST_CASE("Can Create Growthrate Library", "[Library]") {
auto l = BuildGrowthRateLibrary(); auto l = BuildGrowthRateLibrary();
REQUIRE(l != nullptr); REQUIRE(l != nullptr);
delete l; delete l;
} }
TEST_CASE( "Can Create Data Library", "[Library]" ) { TEST_CASE("Can Create Data Library", "[Library]") {
auto l = BuildLibrary(); auto l = BuildLibrary();
REQUIRE(l != nullptr); REQUIRE(l != nullptr);
delete l; delete l;
} }
#endif #endif

View File

@ -1,9 +1,9 @@
#ifdef TESTS_BUILD #ifdef TESTS_BUILD
#include "../extern/catch.hpp" #include "../extern/catch.hpp"
#include "../src/Core/Random.hpp"
#include "../src/Core/Exceptions/CreatureException.hpp" #include "../src/Core/Exceptions/CreatureException.hpp"
#include "../src/Core/Random.hpp"
TEST_CASE( "Random ints", "[Utilities]" ) { TEST_CASE("Random ints", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
CHECK(rand.Get() == 1656398469); CHECK(rand.Get() == 1656398469);
CHECK(rand.Get() == 641584702); CHECK(rand.Get() == 641584702);
@ -17,7 +17,7 @@ TEST_CASE( "Random ints", "[Utilities]" ) {
CHECK(rand.Get() == 1252673902); CHECK(rand.Get() == 1252673902);
} }
TEST_CASE( "Random ints with limit", "[Utilities]" ) { TEST_CASE("Random ints with limit", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
CHECK(rand.Get(10) == 7); CHECK(rand.Get(10) == 7);
CHECK(rand.Get(10) == 2); CHECK(rand.Get(10) == 2);
@ -39,10 +39,9 @@ TEST_CASE( "Random ints with limit", "[Utilities]" ) {
CHECK(rand.Get(2) == 0); CHECK(rand.Get(2) == 0);
CHECK(rand.Get(2) == 0); CHECK(rand.Get(2) == 0);
CHECK(rand.Get(2) == 0); CHECK(rand.Get(2) == 0);
} }
TEST_CASE( "Random ints with upper and bottom", "[Utilities]" ) { TEST_CASE("Random ints with upper and bottom", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
CHECK(rand.Get(10, 30) == 25); CHECK(rand.Get(10, 30) == 25);
CHECK(rand.Get(10, 30) == 15); CHECK(rand.Get(10, 30) == 15);
@ -56,55 +55,60 @@ TEST_CASE( "Random ints with upper and bottom", "[Utilities]" ) {
CHECK(rand.Get(10, 30) == 21); CHECK(rand.Get(10, 30) == 21);
} }
TEST_CASE( "Random distribution (max 0, min 1)", "[Utilities]" ) { TEST_CASE("Random distribution (max 0, min 1)", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
const int size = 100000; const int size = 100000;
int arr[size]; int arr[size];
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
arr[i] = rand.Get(0, 1); arr[i] = rand.Get(0, 1);
} }
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
if (arr[i] != 0) if (arr[i] != 0)
throw CreatureException("We expected a value of 0 here, but got a " + std::to_string(arr[i])); throw CreatureException("We expected a value of 0 here, but got a " + std::to_string(arr[i]));
} }
} }
TEST_CASE( "Random distribution (max 0, min 2)", "[Utilities]" ) { TEST_CASE("Random distribution (max 0, min 2)", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
const int size = 100000; const int size = 100000;
int arr[size]; int arr[size];
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
arr[i] = rand.Get(0, 2); arr[i] = rand.Get(0, 2);
} }
auto numZeros = 0; auto numZeros = 0;
auto numOnes = 0; auto numOnes = 0;
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
if (arr[i] != 0 && arr[i] != 1) if (arr[i] != 0 && arr[i] != 1)
throw CreatureException("We expected a value of 0 or 1 here, but got a " + std::to_string(arr[i])); throw CreatureException("We expected a value of 0 or 1 here, but got a " + std::to_string(arr[i]));
if (arr[i] == 0) numZeros++; if (arr[i] == 0)
else numOnes++; numZeros++;
else
numOnes++;
} }
auto div = static_cast<float>(numZeros) / static_cast<float>(numOnes); auto div = static_cast<float>(numZeros) / static_cast<float>(numOnes);
INFO("Distribution: " << numZeros << "/" << numOnes); INFO("Distribution: " << numZeros << "/" << numOnes);
CHECK(Approx(div).margin(0.01) == 1); CHECK(Approx(div).margin(0.01) == 1);
} }
TEST_CASE( "Random distribution (max 0, min 3)", "[Utilities]" ) { TEST_CASE("Random distribution (max 0, min 3)", "[Utilities]") {
auto rand = CreatureLib::Core::Random(10); auto rand = CreatureLib::Core::Random(10);
const int size = 100000; const int size = 100000;
int arr[size]; int arr[size];
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
arr[i] = rand.Get(0, 3); arr[i] = rand.Get(0, 3);
} }
auto numZeros = 0; auto numZeros = 0;
auto numOnes = 0; auto numOnes = 0;
auto numTwos = 0; auto numTwos = 0;
for (size_t i = 0; i < size; i++){ for (size_t i = 0; i < size; i++) {
if (arr[i] != 0 && arr[i] != 1 && arr[i] != 2) if (arr[i] != 0 && arr[i] != 1 && arr[i] != 2)
throw CreatureException("We expected a value between 0 and 2 here, but got a " + std::to_string(arr[i])); throw CreatureException("We expected a value between 0 and 2 here, but got a " + std::to_string(arr[i]));
if (arr[i] == 0) numZeros++; if (arr[i] == 0)
else if (arr[i] == 1) numOnes++; numZeros++;
else numTwos++; else if (arr[i] == 1)
numOnes++;
else
numTwos++;
} }
INFO("Distribution: " << numZeros << "/" << numOnes << "/" << numTwos); INFO("Distribution: " << numZeros << "/" << numOnes << "/" << numTwos);
CHECK(Approx(static_cast<float>(numZeros) / static_cast<float>(numOnes)).margin(0.01) == 1); CHECK(Approx(static_cast<float>(numZeros) / static_cast<float>(numOnes)).margin(0.01) == 1);
@ -112,6 +116,4 @@ TEST_CASE( "Random distribution (max 0, min 3)", "[Utilities]" ) {
CHECK(Approx(static_cast<float>(numOnes) / static_cast<float>(numTwos)).margin(0.01) == 1); CHECK(Approx(static_cast<float>(numOnes) / static_cast<float>(numTwos)).margin(0.01) == 1);
} }
#endif #endif

View File

@ -7,41 +7,41 @@ using namespace CreatureLib::Library;
using namespace CreatureLib::Battling; using namespace CreatureLib::Battling;
static BattleLibrary* __library = nullptr; static BattleLibrary* __library = nullptr;
static SpeciesLibrary* BuildSpeciesLibrary(){ static SpeciesLibrary* BuildSpeciesLibrary() {
auto l = new SpeciesLibrary(); auto l = new SpeciesLibrary();
l->LoadSpecies("testSpecies1", new CreatureSpecies(0, "testSpecies1", l->LoadSpecies("testSpecies1",
new SpeciesVariant("default", 1,1, 10, {0, 1}, new CreatureSpecies(
StatisticSet<uint16_t >(10,10,10,10,10,10), 0, "testSpecies1",
{"testTalent"}, {"testSecretTalent"}, new SpeciesVariant("default", 1, 1, 10, {0, 1}, StatisticSet<uint16_t>(10, 10, 10, 10, 10, 10),
new LearnableAttacks(100)), {"testTalent"}, {"testSecretTalent"}, new LearnableAttacks(100)),
0.5f, "testGrowthRate", 5, 100)); 0.5f, "testGrowthRate", 5, 100));
return l; return l;
} }
static AttackLibrary* BuildAttackLibrary(){ static AttackLibrary* BuildAttackLibrary() {
auto l = new AttackLibrary(); auto l = new AttackLibrary();
l->LoadAttack("standard", new AttackData("standard", "normal", AttackCategory::Physical, l->LoadAttack("standard", new AttackData("standard", "normal", AttackCategory::Physical, 20, 100, 30,
20, 100, 30, AttackTarget::AdjacentOpponent,0, {})); AttackTarget::AdjacentOpponent, 0, {}));
l->LoadAttack("highPriority", new AttackData("highPriority", "normal", AttackCategory::Physical, l->LoadAttack("highPriority", new AttackData("highPriority", "normal", AttackCategory::Physical, 20, 100, 30,
20, 100, 30, AttackTarget::AdjacentOpponent,1, {})); AttackTarget::AdjacentOpponent, 1, {}));
l->LoadAttack("higherPriority", new AttackData("higherPriority", "normal", AttackCategory::Physical, l->LoadAttack("higherPriority", new AttackData("higherPriority", "normal", AttackCategory::Physical, 20, 100, 30,
20, 100, 30, AttackTarget::AdjacentOpponent,2, {})); AttackTarget::AdjacentOpponent, 2, {}));
l->LoadAttack("lowPriority", new AttackData("lowPriority", "normal", AttackCategory::Physical, l->LoadAttack("lowPriority", new AttackData("lowPriority", "normal", AttackCategory::Physical, 20, 100, 30,
20, 100, 30, AttackTarget::AdjacentOpponent,-1, {})); AttackTarget::AdjacentOpponent, -1, {}));
return l; return l;
} }
static ItemLibrary* BuildItemLibrary(){ static ItemLibrary* BuildItemLibrary() {
auto l = new ItemLibrary(); auto l = new ItemLibrary();
return l; return l;
} }
static GrowthRateLibrary* BuildGrowthRateLibrary(){ static GrowthRateLibrary* BuildGrowthRateLibrary() {
auto l = new GrowthRateLibrary(); auto l = new GrowthRateLibrary();
return l; return l;
} }
static TypeLibrary* BuildTypeLibrary(){ static TypeLibrary* BuildTypeLibrary() {
auto l = new TypeLibrary(); auto l = new TypeLibrary();
l->RegisterType("testType1"); l->RegisterType("testType1");
l->RegisterType("testType2"); l->RegisterType("testType2");
@ -49,17 +49,16 @@ static TypeLibrary* BuildTypeLibrary(){
return l; return l;
} }
static BattleLibrary* BuildLibrary(){ static BattleLibrary* BuildLibrary() {
auto l = new DataLibrary(LibrarySettings(100, 4), BuildSpeciesLibrary(), BuildAttackLibrary(), auto l = new DataLibrary(LibrarySettings(100, 4), BuildSpeciesLibrary(), BuildAttackLibrary(), BuildItemLibrary(),
BuildItemLibrary(), BuildGrowthRateLibrary(), BuildTypeLibrary()); BuildGrowthRateLibrary(), BuildTypeLibrary());
auto battleLib = new BattleLibrary(l, new BattleStatCalculator(), new DamageLibrary(), auto battleLib = new BattleLibrary(l, new BattleStatCalculator(), new DamageLibrary(), new CriticalLibrary(),
new CriticalLibrary(), new ScriptResolver()); new ScriptResolver());
return battleLib; return battleLib;
} }
[[maybe_unused]] [[maybe_unused]] static BattleLibrary* GetLibrary() {
static BattleLibrary* GetLibrary(){ if (__library == nullptr) {
if (__library == nullptr){
__library = BuildLibrary(); __library = BuildLibrary();
} }
return __library; return __library;