Completed
Push — master ( 6c1e78...502e50 )
by Jakub
03:28
created

Character.php$3 ➔ hasStatus()   A

Complexity

Conditions 2

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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