Passed
Push — master ( d0ce80...210dba )
by Jakub
06:27
created

Character.php$3 ➔ getIntelligenceBase()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 2
ccs 0
cts 1
cp 0
rs 10
c 0
b 0
f 0
cc 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace HeroesofAbenez\Combat;
5
6
use Nexendrie\Utils\Numbers;
7
use Symfony\Component\OptionsResolver\OptionsResolver;
8
9
/**
10
 * Structure for single character
11
 *
12
 * @author Jakub Konečný
13
 * @property-read int|string $id
14
 * @property-read string $name
15
 * @property-read string $gender
16
 * @property-read string $race
17
 * @property-read string $occupation
18
 * @property-read string $specialization
19
 * @property-read int $level
20
 * @property-read int $strength
21
 * @property-read int $strengthBase
22
 * @property-read int $dexterity
23
 * @property-read int $dexterityBase
24
 * @property-read int $constitution
25
 * @property-read int $constitutionBase
26
 * @property-read int $intelligence
27
 * @property-read int $intelligenceBase
28
 * @property-read int $charisma
29
 * @property-read int $charismaBase
30
 * @property-read int $maxHitpoints
31
 * @property-read int $maxHitpointsBase
32
 * @property-read int $hitpoints
33
 * @property-read int $damage
34
 * @property-read int $damageBase
35
 * @property-read int $hit
36
 * @property-read int $hitBase
37
 * @property-read int $dodge
38
 * @property-read int $dodgeBase
39
 * @property-read int $initiative
40
 * @property-read int $initiativeBase
41
 * @property-read string $initiativeFormula
42
 * @property-read int $defense
43
 * @property-read int $defenseBase
44
 * @property-read int|null $activePet
45
 * @property-read bool $stunned
46
 * @property-read bool $poisoned
47
 * @property-read bool $hidden
48
 * @property-read BaseCharacterSkill[] $usableSkills
49
 * @property IInitiativeFormulaParser $initiativeFormulaParser
50
 * @property int $positionRow
51
 * @property int $positionColumn
52
 */
53 1
class Character {
54
  use \Nette\SmartObject;
55
  
56
  public const HITPOINTS_PER_CONSTITUTION = 5;
57
  public const STAT_STRENGTH = "strength";
58
  public const STAT_DEXTERITY = "dexterity";
59
  public const STAT_CONSTITUTION = "constitution";
60
  public const STAT_INTELLIGENCE = "intelligence";
61
  public const STAT_CHARISMA = "charisma";
62
  public const STAT_MAX_HITPOINTS = "maxHitpoints";
63
  public const STAT_DAMAGE = "damage";
64
  public const STAT_DEFENSE = "defense";
65
  public const STAT_HIT = "hit";
66
  public const STAT_DODGE = "dodge";
67
  public const STAT_INITIATIVE = "initiative";
68
  public const BASE_STATS = [
69
    self::STAT_STRENGTH, self::STAT_DEXTERITY, self::STAT_CONSTITUTION, self::STAT_INTELLIGENCE, self::STAT_CHARISMA,
70
  ];
71
  public const SECONDARY_STATS = [
72
    self::STAT_MAX_HITPOINTS, self::STAT_DAMAGE, self::STAT_DEFENSE, self::STAT_HIT, self::STAT_DODGE, self::STAT_INITIATIVE,
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 125 characters
Loading history...
73
  ];
74
  public const STATUS_STUNNED = "stunned";
75
  public const STATUS_POISONED = "poisoned";
76
  public const STATUS_HIDDEN = "hidden";
77
  
78
  /** @var int|string */
79
  protected $id;
80
  protected string $name;
81
  protected string $gender = "male";
82
  protected string $race;
83
  protected string $occupation;
84
  protected string $specialization;
85
  protected int $level;
86
  protected int $strength;
87
  protected int $strengthBase;
88
  protected int $dexterity;
89
  protected int $dexterityBase;
90
  protected int $constitution;
91
  protected int $constitutionBase;
92
  protected int $intelligence;
93
  protected int $intelligenceBase;
94
  protected int $charisma;
95
  protected int $charismaBase;
96
  protected int $maxHitpoints;
97
  protected int $maxHitpointsBase;
98
  protected int $hitpoints;
99
  protected int $damage = 0;
100
  protected int $damageBase = 0;
101
  protected int $hit = 0;
102
  protected int $hitBase = 0;
103
  protected int $dodge = 0;
104
  protected int $dodgeBase = 0;
105
  protected int $initiative = 0;
106
  protected int $initiativeBase = 0;
107
  protected string $initiativeFormula;
108
  protected IInitiativeFormulaParser $initiativeFormulaParser;
109
  protected float $defense = 0;
110
  protected float $defenseBase = 0;
111
  /** @var Equipment[]|EquipmentCollection Character's equipment */
112
  public EquipmentCollection $equipment;
113
  /** @var Pet[]|PetsCollection Character's pets */
114
  public PetsCollection $pets;
115
  /** @var BaseCharacterSkill[]|CharacterSkillsCollection Character's skills */
116
  public CharacterSkillsCollection $skills;
117
  protected ?int $activePet = null;
118
  /** @var CharacterEffect[]|CharacterEffectsCollection Active effects */
119
  public CharacterEffectsCollection $effects;
120
  /** @var ICharacterEffectsProvider[]|CharacterEffectsProvidersCollection */
121
  public CharacterEffectsProvidersCollection $effectProviders;
122
  protected int $positionRow = 0;
123
  protected int $positionColumn = 0;
124
  /** @var callable[] */
125
  protected array $statuses = [];
126
  
127
  /**
128
   *
129
   * @param array $stats Stats of the character
130
   * @param Equipment[] $equipment Equipment of the character
131
   * @param Pet[] $pets Pets owned by the character
132
   * @param BaseCharacterSkill[] $skills Skills acquired by the character
133
   */
134
  public function __construct(array $stats, array $equipment = [], array $pets = [], array $skills = [], IInitiativeFormulaParser $initiativeFormulaParser = null) {
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 164 characters
Loading history...
135 1
    $this->initiativeFormulaParser = $initiativeFormulaParser ?? new InitiativeFormulaParser();
136 1
    $this->equipment = EquipmentCollection::fromArray($equipment);
137 1
    $this->pets = PetsCollection::fromArray($pets);
138 1
    $this->effectProviders = CharacterEffectsProvidersCollection::fromArray(array_merge($equipment, $pets));
139 1
    $this->skills = CharacterSkillsCollection::fromArray($skills);
140 1
    $this->equipment->lock();
141 1
    $this->pets->lock();
142 1
    $this->skills->lock();
143 1
    $this->setStats($stats);
144 1
    $this->effects = new CharacterEffectsCollection($this);
145 1
    $this->registerDefaultStatuses();
146 1
  }
147
148
  protected function registerDefaultStatuses(): void {
149 1
    $this->registerStatus(static::STATUS_STUNNED, function(Character $character): bool {
150 1
      return $character->effects->hasItems(["type" => SkillSpecial::TYPE_STUN]);
151 1
    });
152 1
    $this->registerStatus(static::STATUS_POISONED, function(Character $character): int {
153 1
      $poisons = $character->effects->getItems(["type" => SkillSpecial::TYPE_POISON]);
154 1
      $poisonValue = 0;
155
      /** @var CharacterEffect $poison */
156 1
      foreach($poisons as $poison) {
157 1
        $poisonValue += $poison->value;
158
      }
159 1
      return $poisonValue;
160 1
    });
161 1
    $this->registerStatus(static::STATUS_HIDDEN, function(Character $character): bool {
162 1
      return $character->effects->hasItems(["type" => SkillSpecial::TYPE_HIDE]);
163 1
    });
164 1
  }
165
  
166
  protected function setStats(array $stats): void {
167 1
    $requiredStats = array_merge(["id", "name", "level", "initiativeFormula", ], static::BASE_STATS);
168 1
    $allStats = array_merge($requiredStats, ["occupation", "race", "specialization", "gender", ]);
169 1
    $numberStats = static::BASE_STATS;
170 1
    $textStats = ["name", "race", "occupation", "specialization", "initiativeFormula", ];
171 1
    $resolver = new OptionsResolver();
172 1
    $resolver->setDefined($allStats);
173 1
    $resolver->setAllowedTypes("id", ["integer", "string", ]);
174 1
    foreach($numberStats as $stat) {
175 1
      $resolver->setAllowedTypes($stat, ["integer", "float"]);
176 1
      $resolver->setNormalizer($stat, function(OptionsResolver $resolver, $value): int {
177 1
        return (int) $value;
178 1
      });
179
    }
180 1
    foreach($textStats as $stat) {
181 1
      $resolver->setNormalizer($stat, function(OptionsResolver $resolver, $value): string {
182 1
        return (string) $value;
183 1
      });
184
    }
185 1
    $resolver->setRequired($requiredStats);
186 1
    $stats = array_filter($stats, function($key) use($allStats): bool {
187 1
      return in_array($key, $allStats, true);
188 1
    }, ARRAY_FILTER_USE_KEY);
189 1
    $stats = $resolver->resolve($stats);
190 1
    foreach($stats as $key => $value) {
191 1
      if(in_array($key, $numberStats, true)) {
192 1
        $this->$key = $value;
193 1
        $this->{$key . "Base"} = $value;
194
      } else {
195 1
        $this->$key = $value;
196
      }
197
    }
198 1
    $this->hitpoints = $this->maxHitpoints = $this->maxHitpointsBase = $this->constitution * static::HITPOINTS_PER_CONSTITUTION;
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 128 characters
Loading history...
199 1
    $this->recalculateSecondaryStats();
200 1
    $this->hitBase = $this->hit;
201 1
    $this->dodgeBase = $this->dodge;
202 1
  }
203
  
204
  /**
205
   * @return int|string
206
   */
207
  protected function getId() {
208 1
    return $this->id;
209
  }
210
211
  protected function getName(): string {
212 1
    return $this->name;
213
  }
214
  
215
  protected function getGender(): string {
216
    return $this->gender;
217
  }
218
  
219
  protected function getRace(): string {
220
    return $this->race;
221
  }
222
  
223
  protected function getOccupation(): string {
224
    return $this->occupation;
225
  }
226
  
227
  protected function getLevel(): int {
228 1
    return $this->level;
229
  }
230
  
231
  protected function getStrength(): int {
232 1
    return $this->strength;
233
  }
234
  
235
  protected function getStrengthBase(): int {
236
    return $this->strengthBase;
237
  }
238
  
239
  protected function getDexterity(): int {
240 1
    return $this->dexterity;
241
  }
242
  
243
  protected function getDexterityBase(): int {
244
    return $this->dexterityBase;
245
  }
246
  
247
  protected function getConstitution(): int {
248 1
    return $this->constitution;
249
  }
250
  
251
  protected function getConstitutionBase(): int {
252
    return $this->constitutionBase;
253
  }
254
  
255
  protected function getCharisma(): int {
256 1
    return $this->charisma;
257
  }
258
  
259
  protected function getCharismaBase(): int {
260
    return $this->charismaBase;
261
  }
262
  
263
  protected function getMaxHitpoints(): int {
264 1
    return $this->maxHitpoints;
265
  }
266
  
267
  protected function getMaxHitpointsBase(): int {
268 1
    return $this->maxHitpointsBase;
269
  }
270
  
271
  protected function getHitpoints(): int {
272 1
    return $this->hitpoints;
273
  }
274
  
275
  protected function getDamage(): int {
276 1
    return $this->damage;
277
  }
278
  
279
  protected function getDamageBase(): int {
280
    return $this->damageBase;
281
  }
282
  
283
  protected function getHit(): int {
284 1
    return $this->hit;
285
  }
286
  
287
  protected function getHitBase(): int {
288
    return $this->hitBase;
289
  }
290
  
291
  protected function getDodge(): int {
292 1
    return $this->dodge;
293
  }
294
  
295
  protected function getDodgeBase(): int {
296
    return $this->dodgeBase;
297
  }
298
  
299
  protected function getInitiative(): int {
300 1
    return $this->initiative;
301
  }
302
  
303
  protected function getInitiativeBase(): int {
304 1
    return $this->initiativeBase;
305
  }
306
  
307
  protected function getInitiativeFormula(): string {
308 1
    return $this->initiativeFormula;
309
  }
310
  
311
  protected function getDefense(): int {
312 1
    return (int) $this->defense;
313
  }
314
  
315
  protected function getDefenseBase(): int {
316
    return (int) $this->defenseBase;
317
  }
318
319
  protected function getActivePet(): ?int {
320
    /** @var Pet|null $pet */
321 1
    $pet = $this->pets->getItem(["deployed" => true]);
322 1
    if($pet === null) {
323 1
      return null;
324
    }
325 1
    return $pet->id;
326
  }
327
  
328
  protected function isStunned(): bool {
329
    return $this->hasStatus(static::STATUS_STUNNED);
330
  }
331
332
  protected function isPoisoned(): bool {
333 1
    return $this->hasStatus(static::STATUS_POISONED);
334
  }
335
336
  protected function isHidden(): bool {
337 1
    return $this->hasStatus(static::STATUS_HIDDEN);
338
  }
339
  
340
  protected function getSpecialization(): string {
341
    return $this->specialization;
342
  }
343
  
344
  protected function getIntelligence(): int {
345 1
    return $this->intelligence;
346
  }
347
  
348
  protected function getIntelligenceBase(): int {
349
    return $this->intelligenceBase;
350
  }
351
  
352
  protected function getInitiativeFormulaParser(): IInitiativeFormulaParser {
353 1
    return $this->initiativeFormulaParser;
354
  }
355
  
356
  protected function setInitiativeFormulaParser(IInitiativeFormulaParser $initiativeFormulaParser): void {
357 1
    $oldParser = $this->initiativeFormulaParser;
358 1
    $this->initiativeFormulaParser = $initiativeFormulaParser;
359 1
    if($oldParser !== $initiativeFormulaParser) {
360 1
      $this->recalculateStats();
361
    }
362 1
  }
363
  
364
  protected function getPositionRow(): int {
365 1
    return $this->positionRow;
366
  }
367
  
368
  protected function setPositionRow(int $positionRow): void {
369 1
    $this->positionRow = Numbers::range($positionRow, 1, PHP_INT_MAX);
370 1
  }
371
  
372
  protected function getPositionColumn(): int {
373 1
    return $this->positionColumn;
374
  }
375
  
376
  protected function setPositionColumn(int $positionColumn): void {
377 1
    $this->positionColumn = Numbers::range($positionColumn, 1, PHP_INT_MAX);
378 1
  }
379
380
  /**
381
   * Register a new possible character status
382
   *
383
   * @param string $name
384
   * @param callable $callback Used to determine whether the status is active/what value does it have. Is called with Character instance as parameter
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 149 characters
Loading history...
385
   */
386
  public function registerStatus(string $name, callable $callback): void {
387 1
    $this->statuses[$name] = $callback;
388 1
  }
389
390
  /**
391
   * @return mixed
392
   */
393
  public function getStatus(string $name) {
394 1
    if(!array_key_exists($name, $this->statuses)) {
395 1
      return null;
396
    }
397 1
    return (call_user_func($this->statuses[$name], $this));
398
  }
399
400
  public function hasStatus(string $status): bool {
401 1
    if(!array_key_exists($status, $this->statuses)) {
402 1
      return false;
403
    }
404 1
    return (bool) (call_user_func($this->statuses[$status], $this));
405
  }
406
  
407
  /**
408
   * @internal
409
   */
410
  public function applyEffectProviders(): void {
411 1
    foreach($this->effectProviders as $item) {
412 1
      $effects = $item->getCombatEffects();
413 1
      array_walk($effects, function(CharacterEffect $effect): void {
414 1
        $this->effects->removeByFilter(["id" => $effect->id]);
415 1
        $this->effects[] = $effect;
416 1
      });
417
    }
418 1
  }
419
  
420
  /**
421
   * @return BaseCharacterSkill[]
422
   */
423
  protected function getUsableSkills(): array {
424 1
    return $this->skills->getItems(["usable" => true]);
425
  }
426
  
427
  /**
428
   * Harm the character
429
   */
430
  public function harm(int $amount): void {
431 1
    $this->hitpoints -= Numbers::range($amount, 0, $this->hitpoints);
432 1
  }
433
  
434
  /**
435
   * Heal the character
436
   */
437
  public function heal(int $amount): void {
438 1
    $this->hitpoints += Numbers::range($amount, 0, $this->maxHitpoints - $this->hitpoints);
439 1
  }
440
  
441
  /**
442
   * Determine which (primary) stat should be used to calculate damage
443
   */
444
  public function damageStat(): string {
445
    /** @var Weapon|null $item */
446 1
    $item = $this->equipment->getItem(["%class%" => Weapon::class, "worn" => true, ]);
447 1
    if($item === null) {
448 1
      return static::STAT_STRENGTH;
449
    }
450 1
    return $item->damageStat;
451
  }
452
  
453
  /**
454
   * Recalculate secondary stats from the the primary ones
455
   */
456
  public function recalculateSecondaryStats(): void {
457
    $stats = [
458 1
      static::STAT_DAMAGE => $this->damageStat(), static::STAT_HIT => static::STAT_DEXTERITY,
459 1
      static::STAT_DODGE => static::STAT_DEXTERITY, static::STAT_MAX_HITPOINTS => static::STAT_CONSTITUTION,
460 1
      static::STAT_INITIATIVE => "",
461
    ];
462 1
    foreach($stats as $secondary => $primary) {
463 1
      $gain = $this->$secondary - $this->{$secondary . "Base"};
464 1
      if($secondary === static::STAT_DAMAGE) {
465 1
        $base = (int) round($this->$primary / 2);
466 1
      } elseif($secondary === static::STAT_MAX_HITPOINTS) {
467 1
        $base = $this->$primary * static::HITPOINTS_PER_CONSTITUTION;
468 1
      } elseif($secondary === static::STAT_INITIATIVE) {
469 1
        $base = $this->initiativeFormulaParser->calculateInitiative($this);
470
      } else {
471 1
        $base = $this->$primary * 3;
472
      }
473 1
      $this->{$secondary . "Base"} = $base;
474 1
      $this->$secondary = $base + $gain;
475
    }
476 1
  }
477
  
478
  /**
479
   * Recalculates stats of the character (mostly used during combat)
480
   */
481
  public function recalculateStats(): void {
482 1
    $stats = array_merge(static::BASE_STATS, static::SECONDARY_STATS);
483 1
    $debuffs = [];
484 1
    foreach($stats as $stat) {
485 1
      $$stat = $this->{$stat . "Base"};
486 1
      $debuffs[$stat] = 0;
487
    }
488 1
    $this->effects->removeByFilter(["duration<" => 1]);
489 1
    foreach($this->effects as $effect) {
490 1
      $stat = $effect->stat;
491 1
      $type = $effect->type;
492 1
      $bonus_value = 0;
493 1
      if(!in_array($type, SkillSpecial::NO_STAT_TYPES, true)) {
494 1
        $bonus_value = ($effect->valueAbsolute) ? $effect->value : $$stat / 100 * $effect->value;
495
      }
496 1
      if($type == SkillSpecial::TYPE_BUFF) {
497 1
        $$stat += $bonus_value;
498 1
      } elseif($type == SkillSpecial::TYPE_DEBUFF) {
499 1
        $debuffs[$stat] += $bonus_value;
500
      }
501 1
      unset($stat, $type, $bonus_value);
502
    }
503 1
    foreach($debuffs as $stat => $value) {
504 1
      $value = min($value, 80);
505 1
      $bonus_value = $$stat / 100 * $value;
506 1
      $$stat -= $bonus_value;
507
    }
508 1
    foreach($stats as $stat) {
509 1
      $this->$stat = (int) round($$stat);
510
    }
511 1
    $this->recalculateSecondaryStats();
512 1
  }
513
  
514
  /**
515
   * Reset character's initiative
516
   */
517
  public function resetInitiative(): void {
518 1
    $this->initiative = $this->initiativeBase = 0;
519 1
  }
520
521
  public function canAct(): bool {
522 1
    if($this->hasStatus(static::STATUS_STUNNED)) {
523 1
      return false;
524 1
    } elseif($this->hitpoints < 1) {
525 1
      return false;
526
    }
527 1
    return true;
528
  }
529
530
  public function canDefend(): bool {
531 1
    if($this->hasStatus(static::STATUS_STUNNED)) {
532 1
      return false;
533
    }
534 1
    return true;
535
  }
536
}
537
?>