Completed
Pull Request — master (#7)
by Thijs
02:24
created

EvaluationResult::isBetterThan()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace lucidtaz\minimax\engine;
4
5
use Closure;
6
7
/**
8
 * Value object containing the result of a decision tree node evaluation
9
 * These two concepts are used together so often that it warrants a separate
10
 * class to be able to carry them around easily.
11
 */
12
class EvaluationResult
13
{
14
    const EPSILON = 0.00001;
15
16
    /**
17
     * @var float Score that results from applying the decision
18
     */
19
    public $score;
20
21
    /**
22
     * @var integer How deep in the execution tree this result was found. Higher
23
     * means earlier. This is to prefer earlier solutions to later solutions
24
     * with the same score, which will make the AI not delay a win without
25
     * reason.
26
     */
27
    public $age;
28
29 11
    public function isBetterThan(EvaluationResult $other): bool
30
    {
31 11
        if (abs($this->score - $other->score) < self::EPSILON) {
32
            // Scores are considered the same, prefer earliest decision. (Shallowest node)
33 11
            return $this->age > $other->age;
34
        }
35 9
        return $this->score > $other->score;
36
    }
37
38 11
    public static function getBestComparator(): Closure
39
    {
40
        return function (EvaluationResult $a, EvaluationResult $b) {
41 11
            return $a->isBetterThan($b) ? 1 : -1;
42 11
        };
43
    }
44
45
    public static function getWorstComparator(): Closure
46
    {
47 11
        return function (EvaluationResult $a, EvaluationResult $b) {
48 11
            return $b->isBetterThan($a) ? 1 : -1;
49 11
        };
50
    }
51
}
52