I wrote a basic command prompt Tic Tac Toe Game. I want to know what can be improved in terms of modeling and what mistakes I've made (if any).
void Main()
{
TicTacToeBoard board = new TicTacToeBoard();
while(!board.GameOver())
{
var i = int.Parse(Console.ReadLine());
board.MakeMove(i);
Console.WriteLine(board.DrawBoard());
}
}
class TicTacToeBoard
{
SquareType[] board = new SquareType[9];
SquareType currentType = SquareType.X;
public void MakeMove(int i)
{
if(board[i] != SquareType.Empty) return;
board[i] = currentType;
currentType = OppositeType(currentType);
}
SquareType OppositeType(SquareType squareType) =>
squareType == SquareType.X ? SquareType.O : SquareType.X;
public bool GameOver()
{
return WeHaveWinner() || WeHaveDraw();
}
bool WeHaveWinner()
{
var winningIndecies = new[]
{
new[]{1,2,3},
new[]{4,5,6},
new[]{7,8,9},
new[]{1,5,9},
new[]{3,5,7}
};
foreach(var indecies in winningIndecies)
{
var squares = indecies.Select(i => board[i - 1]);
if(squares.Any(x => x == SquareType.Empty)) continue;
else if(squares.Distinct().Count() == 1) return true;
}
return false;
}
bool WeHaveDraw() => !WeHaveWinner() && board.All(x => x != SquareType.Empty);
public string DrawBoard()
=> $@"|{board[0]},{board[1]},{board[2]}|
|{board[3]},{board[4]},{board[5]}|
|{board[6]},{board[7]},{board[8]}|".Replace("Empty"," ");
}
enum SquareType { Empty, X, O }