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

DecisionNode::getChildResult()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 1
nop 1
crap 2
1
<?php
2
3
namespace lucidtaz\minimax\engine;
4
5
use lucidtaz\minimax\game\GameState;
6
use lucidtaz\minimax\game\Player;
7
8
/**
9
 * Node in the decision search tree
10
 * An object of this class can be queried for its ideal decision (and according
11
 * score) by calling the decide() method. It will recursively construct child
12
 * nodes and evaluate them using that method as well.
13
 */
14
class DecisionNode
15
{
16
    /**
17
     * @var Player The player to optimize for.
18
     */
19
    private $objectivePlayer;
20
21
    /**
22
     * @var GameState The current GameState to base future decisions on.
23
     */
24
    private $state;
25
26
    /**
27
     * @var int Limit on how deep we can continue to search, recursion limiter.
28
     */
29
    private $depthLeft;
30
31
    /**
32
     * @var NodeType Whether we are a min-node or a max-node. This enables the
33
     * caller to select either the most favorable or the least favorable
34
     * outcome.
35
     */
36
    private $type;
37
38
    /**
39
     * @param Player $objectivePlayer The Player to optimize for
40
     * @param GameState $state Current GameState to base decisions on
41
     * @param int $depthLeft Recursion limiter
42
     * @param NodeType $type Signifies whether to minimize or maximize the score
43
     */
44 12
    public function __construct(Player $objectivePlayer, GameState $state, int $depthLeft, NodeType $type)
45
    {
46 12
        $this->objectivePlayer = $objectivePlayer;
47 12
        $this->state = $state;
48 12
        $this->depthLeft = $depthLeft;
49 12
        $this->type = $type;
50 12
    }
51
52
    /**
53
     * Determine the ideal move for this node
54
     * This means either the best or the worst possible outcome for the
55
     * objective player, based on who is actually playing. (If the objective
56
     * player is currently playing, we take the best outcome, otherwise we take
57
     * the worst. This reflects that the opponent also plays optimally.)
58
     */
59 12
    public function traverseGameTree(): TraversalResult
60
    {
61 12
        if ($this->depthLeft == 0) {
62 11
            return TraversalResult::onlyEvaluation($this->makeLeafResult());
63
        }
64
65
        /* @var $possibleMoves GameState[] */
66 12
        $possibleMoves = $this->state->getPossibleMoves();
67 12
        if (empty($possibleMoves)) {
68 9
            return TraversalResult::onlyEvaluation($this->makeLeafResult());
69
        }
70
71 12
        $idealResult = null;
72 12
        $idealMove = null;
73 12
        foreach ($possibleMoves as $move) {
74 12
            $moveResult = $this->getChildResult($move);
75
76 12
            if ($idealResult === null || $this->isIdealOver($moveResult, $idealResult)) {
77 12
                $idealResult = $moveResult;
78 12
                $idealMove = $move;
79
            }
80
        }
81
82 12
        return TraversalResult::create($idealMove, $idealResult);
0 ignored issues
show
Bug introduced by
It seems like $idealMove defined by null on line 72 can be null; however, lucidtaz\minimax\engine\TraversalResult::create() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $idealResult defined by null on line 71 can be null; however, lucidtaz\minimax\engine\TraversalResult::create() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
83
    }
84
85
    /**
86
     * Formulate the evaluation result, this node being a leaf node
87
     */
88 12
    private function makeLeafResult(): EvaluationResult
89
    {
90 12
        $result = new EvaluationResult();
91 12
        $result->age = $this->depthLeft;
92 12
        $result->score = $this->state->evaluateScore($this->objectivePlayer);
93 12
        return $result;
94
    }
95
96
    /**
97
     * Recursively evaluate a child decision
98
     * Apply a move and evaluate the outcome
99
     * @param GameState $stateAfterMove The GameState that was created as a
100
     * result of a possible move.
101
     */
102 12
    private function getChildResult(GameState $stateAfterMove): EvaluationResult
103
    {
104 12
        $nextPlayerIsFriendly = $stateAfterMove->getNextPlayer()->isFriendsWith($this->objectivePlayer);
105 12
        $nextDecisionPoint = new static(
106 12
            $this->objectivePlayer,
107
            $stateAfterMove,
108 12
            $this->depthLeft - 1,
109 12
            $nextPlayerIsFriendly ? $this->type : $this->type->alternate()
110
        );
111 12
        return $nextDecisionPoint->traverseGameTree()->evaluation;
112
    }
113
114
    /**
115
     * Compare two evaluation results
116
     * The meaning of "best" is decided by the "ideal" member variable
117
     * comparator
118
     */
119 11
    private function isIdealOver(EvaluationResult $a, EvaluationResult $b): bool
120
    {
121 11
        $ideal = $this->type == NodeType::MIN()
122 11
            ? EvaluationResult::getWorstComparator()
123 11
            : EvaluationResult::getBestComparator();
124 11
        $idealEvaluationResult = $ideal($a, $b);
125 11
        return $idealEvaluationResult > 0;
126
    }
127
}
128