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

Engine   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%
Metric Value
wmc 4
lcom 1
cbo 4
dl 0
loc 33
ccs 15
cts 15
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A decide() 0 17 3
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