我知道你已经不再寻找这个问题的答案了。但是,也许有人还在寻找。
使用@fran-casadome的answer和@chakrit的answer,我会像这样做。硬编码的可能性似乎是合适的。Linq让我们用流畅的步骤包装逻辑。非常好的使用方法。
private bool IsWinner(char player) => new[]
{
new[] { 0, 1, 2 },
new[] { 3, 4, 5 },
new[] { 6, 7, 8 },
new[] { 0, 3, 6 },
new[] { 1, 4, 7 },
new[] { 2, 5, 8 },
new[] { 0, 4, 8 },
new[] { 2, 4, 6 }
}.Any(indexes => indexes.All(index => _data[index] == player));
这是剩余的部分,为了上下文。
private readonly char[] _data =
new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public bool GameOver { get; private set; } = false;
public char? WinningPlayer { get; private set; } = null;
public char CurrentPlayer { get; private set; } = 'x';
public void Play(int position)
{
var index = Array.IndexOf(_data, position);
if (GameOver || index == -1)
{
return;
}
if (GameOver = IsWinner(_data[index] = CurrentPlayer))
{
WinningPlayer = CurrentPlayer;
}
else
{
CurrentPlayer = CurrentPlayer == 'x' ? 'o' : 'x';
}
}