forked from densom/TicTacToe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AlphaBetaMinimaxPlayer.cs
52 lines (45 loc) · 1.35 KB
/
AlphaBetaMinimaxPlayer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TicTacToe
{
class AlphaBetaMinimaxPlayer : IPlayer
{
int miniMaxCount = 0;
public Grid MakeMove(Grid g)
{
GridCells move;
miniMaxCount = 0;
Minimax(g, out move, float.MinValue, float.MaxValue);
Console.WriteLine("Minimax method calls: {0}", miniMaxCount);
return g.MakeMove(move);
}
public float Minimax(Grid g, out GridCells best, float alpha, float beta, int depth = 1)
{
miniMaxCount++;
best = GridCells.None;
var bestResult = -10f;
GridCells garbage;
if (g.IsDraw)
return 0f;
if (g.CurrentIsWinner)
return 1f / depth;
if (g.CurrentIsLoser)
return -1f / depth;
foreach (var move in g.GetMoves())
{
var other = g.MakeMove(move);
alpha = -Minimax(other, out garbage, -beta, -alpha, depth + 1);
if (beta <= alpha)
return alpha;
if (alpha > bestResult)
{
best = move;
bestResult = alpha;
}
}
return bestResult;
}
}
}