Evaluation::getBestComparator()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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