Test Failed
Pull Request — master (#7)
by Thijs
02:13
created

Evaluation::isBetterThan()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
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 Evaluation
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
    public function isBetterThan(Evaluation $other): bool
30
    {
31
        if (abs($this->score - $other->score) < self::EPSILON) {
32
            // Scores are considered the same, prefer earliest decision. (Shallowest node)
33
            return $this->age > $other->age;
34
        }
35
        return $this->score > $other->score;
36
    }
37
38
    public static function getBestComparator(): Closure
39
    {
40
        return function (Evaluation $a, Evaluation $b) {
41
            return $a->isBetterThan($b) ? 1 : -1;
42
        };
43
    }
44
45
    public static function getWorstComparator(): Closure
46
    {
47
        return function (Evaluation $a, Evaluation $b) {
48
            return $b->isBetterThan($a) ? 1 : -1;
49
        };
50
    }
51
}
52