using System.Collections.Generic;
using System.Diagnostics;
namespace ProjectGrid.Models
{
///
/// Holds data for a TicTacTocBoard
/// 0: empty field, > 0 players
///
public class TicTacTocBoard
{
private List _field;
public List 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;
}
private void SetField(int value, int idx)
{
_field[idx] = 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(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)
public bool SetFieldValue(int value, int idx, bool force = false)
{
int field = _field[idx];
if (0 == field || force)
{
SetField(value, idx);
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;
}
}
}