Completed
Push — master ( fe9b11...feae1a )
by Jakub
02:34
created

CombatBase::logResults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace HeroesofAbenez\Combat;
5
6
use Nexendrie\Utils\Numbers,
7
    Nexendrie\Utils\Constants;
8
9
/**
10
 * Handles combat
11
 * 
12
 * @author Jakub Konečný
13
 * @property-read CombatLogger $log Log from the combat
14
 * @property-read int $winner Team which won the combat/0 if there is no winner yet
15
 * @property-read int $round Number of current round
16
 * @property-read int $roundLimit
17
 * @property-read Team $team1
18
 * @property-read Team $team2
19
 * @property-read int $team1Damage
20
 * @property-read int $team2Damage
21
 * @property ISuccessCalculator $successCalculator
22
 * @property callable $victoryCondition To evaluate the winner of combat. Gets combat as parameter, should return winning team (1/2) or 0 if there is not winner (yet)
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 166 characters
Loading history...
23
 * @property callable $healers To determine characters that are supposed to heal their team. Gets team1 and team2 as parameters, should return Team
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 147 characters
Loading history...
24
 * @method void onCombatStart(CombatBase $combat)
25
 * @method void onCombatEnd(CombatBase $combat)
26
 * @method void onRoundStart(CombatBase $combat)
27
 * @method void onRound(CombatBase $combat)
28
 * @method void onRoundEnd(CombatBase $combat)
29
 * @method void onAttack(Character $attacker, Character $defender)
30
 * @method void onSkillAttack(Character $attacker, Character $defender, CharacterAttackSkill $skill)
31
 * @method void onSkillSpecial(Character $character1, Character $target, CharacterSpecialSkill $skill)
32
 * @method void onHeal(Character $healer, Character $patient)
33
 */
34 1
class CombatBase {
35 1
  use \Nette\SmartObject;
36
  
37
  protected const LOWEST_HP_THRESHOLD = 0.5;
38
  
39
  /** @var Team First team */
40
  protected $team1;
41
  /** @var Team Second team */
42
  protected $team2;
43
  /** @var CombatLogger */
44
  protected $log;
45
  /** @var int Number of current round */
46
  protected $round = 0;
47
  /** @var int Round limit */
48
  protected $roundLimit = 30;
49
  /** @var array Dealt damage by team */
50
  protected $damage = [1 => 0, 2 => 0];
51
  /** @var callable[] */
52
  public $onCombatStart = [];
53
  /** @var callable[] */
54
  public $onCombatEnd = [];
55
  /** @var callable[] */
56
  public $onRoundStart = [];
57
  /** @var callable[] */
58
  public $onRound = [];
59
  /** @var callable[] */
60
  public $onRoundEnd = [];
61
  /** @var callable[] */
62
  public $onAttack = [];
63
  /** @var callable[] */
64
  public $onSkillAttack = [];
65
  /** @var callable[] */
66
  public $onSkillSpecial = [];
67
  /** @var callable[] */
68
  public $onHeal = [];
69
  /** @var callable */
70
  protected $victoryCondition;
71
  /** @var callable */
72
  protected $healers;
73
  /** @var ISuccessCalculator */
74
  protected $successCalculator;
75
  
76
  public function __construct(CombatLogger $logger, ?ISuccessCalculator $successCalculator = NULL) {
77 1
    $this->log = $logger;
78 1
    $this->onCombatStart[] = [$this, "applyEffectProviders"];
79 1
    $this->onCombatStart[] = [$this, "setSkillsCooldowns"];
80 1
    $this->onCombatStart[] = [$this, "assignPositions"];
81 1
    $this->onCombatEnd[] = [$this, "removeCombatEffects"];
82 1
    $this->onCombatEnd[] = [$this, "logCombatResult"];
83 1
    $this->onCombatEnd[] = [$this, "resetInitiative"];
84 1
    $this->onRoundStart[] = [$this ,"recalculateStats"];
85 1
    $this->onRoundStart[] = [$this, "logRoundNumber"];
86 1
    $this->onRoundStart[] = [$this, "applyPoison"];
87 1
    $this->onRound[] = [$this, "mainStage"];
88 1
    $this->onRoundEnd[] = [$this, "decreaseSkillsCooldowns"];
89 1
    $this->onRoundEnd[] = [$this, "resetInitiative"];
90 1
    $this->onAttack[] = [$this, "attackHarm"];
91 1
    $this->onSkillAttack[] = [$this, "useAttackSkill"];
92 1
    $this->onSkillSpecial[] = [$this, "useSpecialSkill"];
93 1
    $this->onHeal[] = [$this, "heal"];
94 1
    $this->victoryCondition = [VictoryConditions::class, "moreDamage"];
95 1
    $this->successCalculator = $successCalculator ?? new RandomSuccessCalculator();
96 1
    $this->healers = function(): Team {
97
      return new Team("healers");
98
    };
99 1
  }
100
  
101
  public function getRound(): int {
102 1
    return $this->round;
103
  }
104
  
105
  public function getRoundLimit(): int {
106 1
    return $this->roundLimit;
107
  }
108
  
109
  /**
110
   * Set teams
111
   */
112
  public function setTeams(Team $team1, Team $team2): void {
113 1
    if(isset($this->team1)) {
114 1
      throw new ImmutableException("Teams has already been set.");
115
    }
116 1
    $this->team1 = & $team1;
117 1
    $this->team2 = & $team2;
118 1
    $this->log->setTeams($team1, $team2);
119 1
  }
120
  
121
  /**
122
   * Set participants for duel
123
   * Creates teams named after the member
124
   */
125
  public function setDuelParticipants(Character $player, Character $opponent): void {
126 1
    $team1 = new Team($player->name);
127 1
    $team1[] = $player;
128 1
    $team2 = new Team($opponent->name);
129 1
    $team2[] = $opponent;
130 1
    $this->setTeams($team1, $team2);
131 1
  }
132
  
133
  public function getTeam1(): Team {
134 1
    return $this->team1;
135
  }
136
  
137
  public function getTeam2(): Team {
138 1
    return $this->team2;
139
  }
140
  
141
  public function getVictoryCondition(): callable {
142 1
    return $this->victoryCondition;
143
  }
144
  
145
  public function setVictoryCondition(callable $victoryCondition) {
146 1
    $this->victoryCondition = $victoryCondition;
147 1
  }
148
  
149
  public function getHealers(): callable {
150
    return $this->healers;
151
  }
152
  
153
  public function setHealers(callable $healers) {
154 1
    $this->healers = $healers;
155 1
  }
156
  
157
  public function getTeam1Damage(): int {
158 1
    return $this->damage[1];
159
  }
160
  
161
  public function getTeam2Damage(): int {
162 1
    return $this->damage[2];
163
  }
164
  
165
  public function getSuccessCalculator(): ISuccessCalculator {
166 1
    return $this->successCalculator;
167
  }
168
  
169
  public function setSuccessCalculator(ISuccessCalculator $successCalculator): void {
170 1
    $this->successCalculator = $successCalculator;
171 1
  }
172
  
173
  /**
174
   * Get winner of combat
175
   * 
176
   * @staticvar int $result
177
   * @return int Winning team/0
178
   */
179
  public function getWinner(): int {
180 1
    static $result = 0;
181 1
    if($result === 0) {
182 1
      $result = call_user_func($this->victoryCondition, $this);
183 1
      $result = Numbers::range($result, 0, 2);
184
    }
185 1
    return $result;
186
  }
187
  
188
  protected function getTeam(Character $character): Team {
189 1
    return $this->team1->hasMembers(["id" => $character->id]) ? $this->team1 : $this->team2;
190
  }
191
  
192
  protected function getEnemyTeam(Character $character): Team {
193 1
    return $this->team1->hasMembers(["id" => $character->id]) ? $this->team2 : $this->team1;
194
  }
195
  
196
  public function applyEffectProviders(self $combat): void {
197
    /** @var Character[] $characters */
198 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
199 1
    foreach($characters as $character) {
200 1
      foreach($character->effectProviders as $item) {
201 1
        $effect = $item->toCombatEffect();
202 1
        if(is_null($effect)) {
203
          continue;
204
        }
205 1
        $character->addEffect($effect);
206
      }
207
    }
208 1
  }
209
  
210
  /**
211
   * Set skills' cooldowns
212
   */
213
  public function setSkillsCooldowns(self $combat): void {
214
    /** @var Character[] $characters */
215 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
216 1
    foreach($characters as $character) {
217 1
      foreach($character->skills as $skill) {
218 1
        $skill->resetCooldown();
219
      }
220
    }
221 1
  }
222
  
223
  public function assignPositions(self $combat): void {
224 1
    $assignPositions = function(Team $team) {
225 1
      $row = 1;
226 1
      $column = 0;
227
      /** @var Character $character */
228 1
      foreach($team as $character) {
229
        try {
230 1
          $column++;
231 1
          if($character->positionRow > 0 AND $character->positionColumn > 0) {
232 1
            continue;
233
          }
234
          setPosition:
0 ignored issues
show
introduced by
Use of the GOTO language construct is discouraged
Loading history...
235 1
          $team->setCharacterPosition($character->id, $row, $column);
236 1
        } catch(InvalidCharacterPositionException $e) {
237 1
          if($e->getCode() === InvalidCharacterPositionException::ROW_FULL) {
238 1
            $row++;
239 1
            $column = 1;
240
          } elseif($e->getCode() === InvalidCharacterPositionException::POSITION_OCCUPIED) {
241
            $column++;
242
          } else {
243
            throw $e;
244
          }
245 1
          goto setPosition;
0 ignored issues
show
introduced by
Use of the GOTO language construct is discouraged
Loading history...
246
        }
247
      }
248 1
    };
249 1
    $assignPositions($combat->team1);
250 1
    $assignPositions($combat->team2);
251 1
  }
252
  
253
  /**
254
   * Decrease skills' cooldowns
255
   */
256
  public function decreaseSkillsCooldowns(self $combat): void {
257
    /** @var Character[] $characters */
258 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
259 1
    foreach($characters as $character) {
260 1
      foreach($character->skills as $skill) {
261 1
        $skill->decreaseCooldown();
262
      }
263
    }
264 1
  }
265
  
266
  /**
267
   * Remove combat effects from character at the end of the combat
268
   */
269
  public function removeCombatEffects(CombatBase $combat): void {
270
    /** @var Character[] $characters */
271 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
272 1
    foreach($characters as $character) {
273 1
      foreach($character->effects as $effect) {
274 1
        if($effect->duration === CharacterEffect::DURATION_COMBAT OR is_int($effect->duration)) {
275 1
          $character->removeEffect($effect->id);
276
        }
277
      }
278
    }
279 1
  }
280
  
281
  /**
282
   * Add winner to the log
283
   */
284
  public function logCombatResult(self $combat): void {
285 1
    $combat->log->round = 5000;
286
    $params = [
287 1
      "team1name" => $combat->team1->name, "team1damage" => $combat->damage[1],
288 1
      "team2name" => $combat->team2->name, "team2damage" => $combat->damage[2],
289
    ];
290 1
    if($combat->winner === 1) {
291
      $params["winner"] = $combat->team1->name;
292
    } else {
293 1
      $params["winner"] = $combat->team2->name;
294
    }
295 1
    $combat->log->logText("combat.log.combatEnd", $params);
296 1
  }
297
  
298
  /**
299
   * Log start of a round
300
   */
301
  public function logRoundNumber(self $combat): void {
302 1
    $combat->log->round = ++$this->round;
303 1
  }
304
  
305
  /**
306
   * Decrease duration of effects and recalculate stats
307
   */
308
  public function recalculateStats(self $combat): void {
309
    /** @var Character[] $characters */
310 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
311 1
    foreach($characters as $character) {
312 1
      $character->recalculateStats();
313
    }
314 1
  }
315
  
316
  /**
317
   * Reset characters' initiative
318
   */
319
  public function resetInitiative(self $combat): void {
320
    /** @var Character[] $characters */
321 1
    $characters = array_merge($combat->team1->toArray(), $combat->team2->toArray());
322 1
    foreach($characters as $character) {
323 1
      $character->resetInitiative();
324
    }
325 1
  }
326
  
327
  /**
328
   * Select random character from the team
329
   */
330
  protected function selectRandomCharacter(Team $team): ?Character {
331 1
    if(count($team->aliveMembers) === 0) {
332
      return NULL;
333 1
    } elseif(count($team) === 1) {
334 1
      return $team[0];
335
    }
336
    $roll = rand(0, count($team->aliveMembers) - 1);
337
    return $team->aliveMembers[$roll];
338
  }
339
  
340
  /**
341
   * Select target for attack
342
   */
343
  protected function selectAttackTarget(Character $attacker): ?Character {
344 1
    $enemyTeam = $this->getEnemyTeam($attacker);
345 1
    $target = $this->findLowestHpCharacter($enemyTeam);
346 1
    if(!is_null($target)) {
347 1
      return $target;
348
    }
349 1
    return $this->selectRandomCharacter($enemyTeam);
350
  }
351
  
352
  /**
353
   * Find character with lowest hp in the team
354
   */
355
  protected function findLowestHpCharacter(Team $team, int $threshold = NULL): ?Character {
356 1
    $lowestHp = PHP_INT_MAX;
357 1
    $lowestIndex = PHP_INT_MIN;
358 1
    if(is_null($threshold)) {
359 1
      $threshold = static::LOWEST_HP_THRESHOLD;
360
    }
361 1
    foreach($team->aliveMembers as $index => $member) {
362 1
      if($member->hitpoints <= $member->maxHitpoints * $threshold AND $member->hitpoints < $lowestHp) {
363 1
        $lowestHp = $member->hitpoints;
364 1
        $lowestIndex = $index;
365
      }
366
    }
367 1
    if($lowestIndex === PHP_INT_MIN) {
368 1
      return NULL;
369
    }
370 1
    return $team->aliveMembers[$lowestIndex];
371
  }
372
  
373
  /**
374
   * Select target for healing
375
   */
376
  protected function selectHealingTarget(Character $healer): ?Character {
377 1
    return $this->findLowestHpCharacter($this->getTeam($healer));
378
  }
379
  
380
  protected function findHealers(): Team {
381 1
    $healers = call_user_func($this->healers, $this->team1, $this->team2);
382 1
    if($healers instanceof Team) {
383 1
      return $healers;
384
    }
385
    return new Team("healers");
386
  }
387
  
388
  protected function doAttackSkill(Character $character, CharacterAttackSkill $skill): void {
389 1
    $targets = [];
390 1
    switch($skill->skill->target) {
391 1
      case SkillAttack::TARGET_SINGLE:
392 1
        $targets[] = $this->selectAttackTarget($character);
393 1
        break;
394
      case SkillAttack::TARGET_ROW:
395
        /** @var Character $primaryTarget */
396
        $primaryTarget = $this->selectAttackTarget($character);
397
        $targets = $this->getTeam($primaryTarget)->getMembers(["positionRow" => $primaryTarget->positionRow]);
398
        break;
399
      case SkillAttack::TARGET_COLUMN:
400
        /** @var Character $primaryTarget */
401
        $primaryTarget = $this->selectAttackTarget($character);
402
        $targets = $this->getTeam($primaryTarget)->getMembers(["positionColumn" => $primaryTarget->positionColumn]);
403
        break;
404
      default:
405
        throw new NotImplementedException("Target $skill->skill->target for attack skills is not implemented.");
406
    }
407 1
    foreach($targets as $target) {
408 1
      for($i = 1; $i <= $skill->skill->strikes; $i++) {
409 1
        $this->onSkillAttack($character, $target, $skill);
410
      }
411
    }
412 1
  }
413
  
414
  protected function doSpecialSkill(Character $character, CharacterSpecialSkill $skill): void {
415 1
    $targets = [];
416 1
    switch($skill->skill->target) {
417 1
      case SkillSpecial::TARGET_ENEMY:
418
        $targets[] = $this->selectAttackTarget($character);
419
        break;
420 1
      case SkillSpecial::TARGET_SELF:
421 1
        $targets[] = $character;
422 1
        break;
423
      case SkillSpecial::TARGET_PARTY:
424
        $targets = $this->getTeam($character)->toArray();
425
        break;
426
      case SkillSpecial::TARGET_ENEMY_PARTY:
427
        $targets = $this->getEnemyTeam($character)->toArray();
428
        break;
429
      default:
430
        throw new NotImplementedException("Target $skill->skill->target for special skills is not implemented.");
431
    }
432 1
    foreach($targets as $target) {
433 1
      $this->onSkillSpecial($character, $target, $skill);
434
    }
435 1
  }
436
  
437
  protected function chooseAction(CombatBase $combat, Character $character): ?string {
438 1
    if($character->hitpoints < 1) {
439
      return NULL;
440 1
    } elseif(in_array($character, $combat->findHealers()->toArray(), true) AND !is_null($combat->selectHealingTarget($character))) {
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 132 characters
Loading history...
441 1
      return CombatAction::ACTION_HEALING;
442
    }
443 1
    $attackTarget = $combat->selectAttackTarget($character);
444 1
    if(is_null($attackTarget)) {
445
      return NULL;
446
    }
447 1
    if(count($character->usableSkills) > 0) {
448 1
      $skill = $character->usableSkills[0];
449 1
      if($skill instanceof CharacterAttackSkill) {
450 1
        return CombatAction::ACTION_SKILL_ATTACK;
451 1
      } elseif($skill instanceof  CharacterSpecialSkill) {
452 1
        return CombatAction::ACTION_SKILL_SPECIAL;
453
      }
454
    }
455 1
    return CombatAction::ACTION_ATTACK;
456
  }
457
  
458
  protected function getAllowedActions(): array {
459 1
    $allowedActions = Constants::getConstantsValues(CombatAction::class, "ACTION_");
460 1
    return array_values(array_filter($allowedActions, function(string $value) {
461 1
      return ($value !== CombatAction::ACTION_POISON);
462 1
    }));
463
  }
464
  
465
  /**
466
   * Main stage of a round
467
   */
468
  public function mainStage(self $combat): void {
469
    /** @var Character[] $characters */
470 1
    $characters = array_merge($combat->team1->usableMembers, $combat->team2->usableMembers);
471 1
    usort($characters, function(Character $a, Character $b) {
472 1
      return -1 * strcmp((string) $a->initiative, (string) $b->initiative);
473 1
    });
474 1
    foreach($characters as $character) {
475 1
      $action = $combat->chooseAction($combat, $character);
476 1
      if(!in_array($action, $this->getAllowedActions(), true)) {
477
        continue;
478
      }
479
      switch($action) {
480 1
        case CombatAction::ACTION_ATTACK:
481 1
          $combat->onAttack($character, $combat->selectAttackTarget($character));
482 1
          break;
483 1
        case CombatAction::ACTION_SKILL_ATTACK:
484
          /** @var CharacterAttackSkill $skill */
485 1
          $skill = $character->usableSkills[0];
486 1
          $combat->doAttackSkill($character, $skill);
487 1
          break;
488 1
        case CombatAction::ACTION_SKILL_SPECIAL:
489
          /** @var CharacterSpecialSkill $skill */
490 1
          $skill = $character->usableSkills[0];
491 1
          $combat->doSpecialSkill($character, $skill);
492 1
          break;
493 1
        case CombatAction::ACTION_HEALING:
494 1
          $combat->onHeal($character, $combat->selectHealingTarget($character));
495 1
          break;
496
      }
497
    }
498 1
  }
499
  
500
  /**
501
   * Start next round
502
   * 
503
   * @return int Winning team/0
504
   */
505
  protected function startRound(): int {
506 1
    $this->onRoundStart($this);
507 1
    return $this->getWinner();
508
  }
509
  
510
  /**
511
   * Do a round
512
   */
513
  protected function doRound(): void {
514 1
    $this->onRound($this);
515 1
  }
516
  
517
  /**
518
   * End round
519
   * 
520
   * @return int Winning team/0
521
   */
522
  protected function endRound(): int {
523 1
    $this->onRoundEnd($this);
524 1
    return $this->getWinner();
525
  }
526
  
527
  /**
528
   * Executes the combat
529
   * 
530
   * @return int Winning team
531
   */
532
  public function execute(): int {
533 1
    if(!isset($this->team1)) {
534 1
      throw new InvalidStateException("Teams are not set.");
535
    }
536 1
    $this->onCombatStart($this);
537 1
    while($this->round <= $this->roundLimit) {
538 1
      if($this->startRound() > 0) {
539 1
        break;
540
      }
541 1
      $this->doRound();
542 1
      if($this->endRound() > 0) {
543
        break;
544
      }
545
    }
546 1
    $this->onCombatEnd($this);
547 1
    return $this->getWinner();
548
  }
549
  
550
  /**
551
   * Calculate hit chance for attack/skill attack
552
   */
553
  protected function calculateHitChance(Character $character1, Character $character2, CharacterAttackSkill $skill = NULL): int {
0 ignored issues
show
introduced by
Line exceeds 120 characters; contains 128 characters
Loading history...
554 1
    $hitChance = $this->successCalculator->calculateHitChance($character1, $character2, $skill);
555 1
    return Numbers::range($hitChance, ISuccessCalculator::MIN_HIT_CHANCE, ISuccessCalculator::MAX_HIT_CHANCE);
556
  }
557
  
558
  /**
559
   * Check whether action succeeded
560
   */
561
  protected function hasHit(int $hitChance): bool {
562 1
    return $this->successCalculator->hasHit($hitChance);
563
  }
564
  
565
  /**
566
   * Do an attack
567
   * Hit chance = Attacker's hit - Defender's dodge, but at least 15%
568
   * Damage = Attacker's damage - defender's defense
569
   */
570
  public function attackHarm(Character $attacker, Character $defender): void {
571 1
    $result = [];
572 1
    $hitChance = $this->calculateHitChance($attacker, $defender);
573 1
    $result["result"] = $this->hasHit($hitChance);
574 1
    $result["amount"] = 0;
575 1
    if($result["result"]) {
576 1
      $amount = $attacker->damage - $defender->defense;
577 1
      $result["amount"] = Numbers::range($amount, 0, $defender->hitpoints);
578
    }
579 1
    if($result["amount"] > 0) {
580 1
      $defender->harm($result["amount"]);
581
    }
582 1
    $result["action"] = CombatAction::ACTION_ATTACK;
583 1
    $result["name"] = "";
584 1
    $result["character1"] = $attacker;
585 1
    $result["character2"] = $defender;
586 1
    $this->logDamage($attacker, $result["amount"]);
587 1
    $this->log->log($result);
588 1
  }
589
  
590
  /**
591
   * Use an attack skill
592
   */
593
  public function useAttackSkill(Character $attacker, Character $defender, CharacterAttackSkill $skill): void {
594 1
    $result = [];
595 1
    $hitChance = $this->calculateHitChance($attacker, $defender, $skill);
596 1
    $result["result"] = $this->hasHit($hitChance);
597 1
    $result["amount"] = 0;
598 1
    if($result["result"]) {
599 1
      $amount = (int) ($attacker->damage - $defender->defense / 100 * $skill->damage);
600 1
      $result["amount"] = Numbers::range($amount, 0, $defender->hitpoints);
601
    }
602 1
    if($result["amount"]) {
603 1
      $defender->harm($result["amount"]);
604
    }
605 1
    $result["action"] = CombatAction::ACTION_SKILL_ATTACK;
606 1
    $result["name"] = $skill->skill->name;
607 1
    $result["character1"] = $attacker;
608 1
    $result["character2"] = $defender;
609 1
    $this->logDamage($attacker, $result["amount"]);
610 1
    $this->log->log($result);
611 1
    $skill->resetCooldown();
612 1
  }
613
  
614
  /**
615
   * Use a special skill
616
   */
617
  public function useSpecialSkill(Character $character1, Character $target, CharacterSpecialSkill $skill): void {
618
    $result = [
619 1
      "result" => true, "amount" => 0, "action" => CombatAction::ACTION_SKILL_SPECIAL, "name" => $skill->skill->name,
620 1
      "character1" => $character1, "character2" => $target,
621
    ];
622 1
    $effect = new CharacterEffect([
623 1
      "id" => "skill{$skill->skill->id}Effect",
624 1
      "type" => $skill->skill->type,
625 1
      "stat" => ((in_array($skill->skill->type, SkillSpecial::NO_STAT_TYPES, true)) ? NULL : $skill->skill->stat),
626 1
      "value" => $skill->value,
627 1
      "source" => CharacterEffect::SOURCE_SKILL,
628 1
      "duration" => $skill->skill->duration,
629
    ]);
630 1
    $target->addEffect($effect);
631 1
    $this->log->log($result);
632 1
    $skill->resetCooldown();
633 1
  }
634
  
635
  /**
636
   * Heal a character
637
   */
638
  public function heal(Character $healer, Character $patient): void {
639 1
    $result = [];
640 1
    $hitChance = $this->successCalculator->calculateHealingSuccessChance($healer);
641 1
    $hitChance = Numbers::range($hitChance, 0, 100);
642 1
    $result["result"] = $this->successCalculator->hasHit($hitChance);
643 1
    $amount = ($result["result"]) ? (int) ($healer->intelligence / 2) : 0;
644 1
    $result["amount"] = Numbers::range($amount, 0, $patient->maxHitpoints - $patient->hitpoints);
645 1
    if($result["amount"]) {
646 1
      $patient->heal($result["amount"]);
647
    }
648 1
    $result["action"] = CombatAction::ACTION_HEALING;
649 1
    $result["name"] = "";
650 1
    $result["character1"] = $healer;
651 1
    $result["character2"] = $patient;
652 1
    $this->log->log($result);
653 1
  }
654
  
655
  /**
656
   * Harm poisoned characters at start of round
657
   */
658
  public function applyPoison(self $combat): void {
659
    /** @var Character[] $characters */
660 1
    $characters = array_merge($combat->team1->aliveMembers, $combat->team2->aliveMembers);
661 1
    foreach($characters as $character) {
662 1
      foreach($character->effects as $effect) {
663 1
        if($effect->type === SkillSpecial::TYPE_POISON) {
664
          $character->harm($effect->value);
665
          $action = [
666
            "action" => CombatAction::ACTION_POISON, "result" => true, "amount" => $effect->value,
667
            "character1" => $character, "character2" => $character,
668
          ];
669 1
          $combat->log->log($action);
670
        }
671
      }
672
    }
673 1
  }
674
  
675
  /**
676
   * Log dealt damage
677
   */
678
  public function logDamage(Character $attacker, int $amount): void {
679 1
    $team = $this->team1->hasMembers(["id" => $attacker->id]) ? 1 : 2;
680 1
    $this->damage[$team] += $amount;
681 1
  }
682
  
683
  public function getLog(): CombatLogger {
684 1
    return $this->log;
685
  }
686
}
687
?>