public static PlacePosition DetermineMove(int[,] board, int playerId)
{
// If the player has two in a row, they can place a third to get three in a row.
foreach (var rps in RowPositions)
{
var x = 0;
PlacePosition emptyPosition = null;
foreach (var pos in rps)
{
var v = board[pos.X, pos.Y];
if (v == 0)
emptyPosition = pos;
else if (v == playerId)
x += 1;
}
if (x == Rule.BoardSize - 1 && emptyPosition != null)
return emptyPosition;
}
// If the opponent has two in a row, the player must play the third themselves to block the opponent.
foreach (var rps in RowPositions)
{
var x = 0;
PlacePosition emptyPosition = null;
foreach (var pos in rps)
{
var v = board[pos.X, pos.Y];
if (v == 0)
emptyPosition = pos;
else if (v != playerId)
x += 1;
}
if (x == Rule.BoardSize - 1 && emptyPosition != null)
return emptyPosition;
}
// Random pick
var positions = new List<PlacePosition>();
for (int x = 0; x < Rule.BoardSize; x++)
{
for (int y = 0; y < Rule.BoardSize; y++)
{
if (board[x, y] == 0)
positions.Add(new PlacePosition(x, y));
}
}
if (positions.Count > 0)
return positions[new Random().Next(positions.Count)];
return null;
}