-
Notifications
You must be signed in to change notification settings - Fork 2
/
Connect4State.cs
107 lines (87 loc) · 2.87 KB
/
Connect4State.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
using System.Text;
using MinMaxSearch;
namespace Connect4Tests
{
public class Connect4State : IDeterministicState
{
public const int BoardSize = 6;
public Connect4State(Player[,] board, Player turn)
{
Board = board;
Turn = turn;
}
public Player[,] Board { get; }
public Player Turn { get; }
public IEnumerable<IState> GetNeighbors()
{
if (BoardEvaluator.IsWin(Board, Turn.GetReversePlayer()))
return new List<IDeterministicState>();
var result = new List<Connect4State>();
for (int i = 0; i < BoardSize; i++)
{
var newState = AddPieceTo(i);
if (newState != null)
result.Add(newState);
}
return result;
}
public double Evaluate(int depth, List<IState> passedThroughStates) =>
BoardEvaluator.Evaluate(Board);
public Connect4State AddPieceTo(int i)
{
var newBoard = (Player[,]) Board.Clone();
for (int j = 0; j < BoardSize; j ++)
if (newBoard[j, i] == Player.Empty)
{
newBoard[j, i] = Turn;
return new Connect4State(newBoard, Turn.GetReversePlayer());
}
return null;
}
public override bool Equals(object obj)
{
if (!(obj is Connect4State connect4State))
return false;
if (Turn != connect4State.Turn)
return false;
for (var i = 0; i < BoardSize; i++)
for (var j = 0; j < BoardSize; j++)
if (Board[i, j] != connect4State.Board[i, j])
return false;
return true;
}
public override int GetHashCode()
{
int sum = 0;
for (var i = 0; i < BoardSize; i++)
for (var j = 0; j < BoardSize; j++)
sum += GetValue(Board[i, j]) * (int)Math.Pow(3, i + j);
return sum + (int) Turn * (int) Math.Pow(3, BoardSize * BoardSize);
}
private int GetValue(Player player)
{
switch (player)
{
case Player.Min:
return 1;
case Player.Max:
return 2;
default:
return 0;
}
}
public override string ToString()
{
var builder = new StringBuilder();
for (int i = 0; i < BoardSize; i++)
{
for (int j = 0; j < BoardSize; j++)
builder.Append(GetValue(Board[i,j]) + " ");
builder.Append("#" + Environment.NewLine);
}
return builder.ToString();
}
}
}