92 lines
1.9 KiB
C#
92 lines
1.9 KiB
C#
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
|
|
namespace ProjectGrid.Models
|
|
{
|
|
/// <summary>
|
|
/// Holds data for a TicTacTocBoard
|
|
/// 0: empty field, > 0 players
|
|
/// </summary>
|
|
public class TicTacTocBoard
|
|
{
|
|
private List<int> _field;
|
|
public List<int> Field => _field;
|
|
|
|
private int _lastSetValue;
|
|
public int LastSetValue => _lastSetValue;
|
|
|
|
private int PosToIdx(int x, int y)
|
|
{
|
|
Debug.Assert(x >= 0 && x <= 3
|
|
&& y >= 0 && y <= 3,
|
|
$"{x}:{y} outside of playarea!");
|
|
return x + y * 3;
|
|
}
|
|
|
|
private int GetField(int x, int y) => _field[PosToIdx(x, y)];
|
|
private void SetField(int value, int x, int y)
|
|
{
|
|
_field[PosToIdx(x, y)] = value;
|
|
_lastSetValue = value;
|
|
}
|
|
|
|
// 0 1 2
|
|
// 3 4 5
|
|
// 6 7 8
|
|
private static readonly int[,] _winning = new int[,] {
|
|
{ 0, 1, 2 },
|
|
{ 3, 4, 5 },
|
|
{ 6, 7 ,8 },
|
|
{ 0, 3 ,6 },
|
|
{ 1, 4 ,7 },
|
|
{ 2, 5 ,8 },
|
|
{ 0, 4 ,8 },
|
|
{ 2, 4 ,6 },
|
|
};
|
|
|
|
public TicTacTocBoard()
|
|
{
|
|
_field = new List<int>(new int[9] {
|
|
0, 0, 0,
|
|
0, 0, 0,
|
|
0, 0, 0,
|
|
});
|
|
|
|
_lastSetValue = 0;
|
|
}
|
|
|
|
public bool SetFieldValue(int value, int x, int y, bool force = false)
|
|
{
|
|
int field = GetField(x, y);
|
|
if (0 == field || force)
|
|
{
|
|
SetField(value, x, y);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public bool ValueWon(int value)
|
|
{
|
|
Debug.Assert(value > 0, "ValueWon called for Empty field 0");
|
|
|
|
for (int x = 0; x < _winning.GetLength(0); x++)
|
|
{
|
|
bool won = true;
|
|
for (int y = 0; y < _winning.GetLength(1); y++)
|
|
{
|
|
if (_field[_winning[x, y]] != value)
|
|
{
|
|
won = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (won)
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
} |