Completed
Push — master ( c94f97...665cde )
by Thijs
03:59
created

Engine::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace lucidtaz\minimax\engine;
4
5
use BadMethodCallException;
6
use lucidtaz\minimax\game\Decision;
7
use lucidtaz\minimax\game\GameState;
8
use lucidtaz\minimax\game\Player;
9
use RuntimeException;
10
11
class Engine
12
{
13
    private $objectivePlayer;
14
15
    private $maxDepth;
16
17 13
    public function __construct(Player $objectivePlayer, int $maxDepth = 3)
18
    {
19 13
        $this->objectivePlayer = $objectivePlayer;
20 13
        $this->maxDepth = $maxDepth;
21 13
    }
22
23
    /**
24
     * Evaluate possible decisions and take the best one
25
     */
26 13
    public function decide(GameState $state): Decision
27
    {
28 13
        if (!$state->getNextPlayer()->equals($this->objectivePlayer)) {
29 1
            throw new BadMethodCallException('It is not this players turn');
30
        }
31 12
        $topLevelNode = new DecisionPoint(
32 12
            $this->objectivePlayer,
33
            $state,
34 12
            $this->maxDepth,
35 12
            DecisionWithScore::getBestComparator()
36
        );
37 12
        $decisionWithScore = $topLevelNode->decide();
38 12
        if ($decisionWithScore->decision === null) {
39 1
            throw new RuntimeException('There are no possible moves');
40
        }
41 11
        return $decisionWithScore->decision;
42
    }
43
}
44