Код: Выделить всё
private class Player
{
public bool IsSquareTaken { get => GetsSquareAndVerifies(); }
public char Symbol { get; set; }
public int Row { get; set; }
public int Column { get; set; }
// creates a player and gives them a symbol
public Player(char symbol)
{
Symbol = symbol;
}
public Player()
{
}
public bool GetsSquareAndVerifies()
{
TicTacToeGame game = new TicTacToeGame();
while (true)
{
Console.WriteLine($"It is {Symbol}'s turn.\nWhich square would you like to play in? (1-9)");
if ((!int.TryParse(Console.ReadLine(), out int userInput) || userInput < 1 || userInput > 9))
{
Console.WriteLine("Please enter a valid number!");
return true;
}
Row = (userInput - 1) / 3;
Column = (userInput - 1) % 3;
if (game.Board[Row, Column] != '\0')
{
Console.WriteLine("Halt! That square is taken.");
return true;
} else if (game.Board[Row, Column] == '\0')
{
game.Board[Row, Column] = Symbol;
return false;
}
}
}
}
}
Код: Выделить всё
private class TicTacToeGame()
{
private char[,] board = new char[3, 3];
Player player = new('X');
Player player2 = new('O');
public char[,] Board { get => board; set => board = value; }
public void InitializeBoard()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Board[i, j] = '\0';
}
}
for (int r = 0; r < 3; r++)
{
Console.WriteLine(" {0} | {1} | {2} ", Board[r, 0], Board[r, 1], Board[r, 2]);
if (r < 2)
{
Console.WriteLine("----+----+-----");
}
}
}
public void DisplayPlacedSymbol()
{
while (true)
{
if (player.IsSquareTaken == false)
{
for (int r = 0; r < 3; r++)
{
Console.WriteLine(" {0} | {1} | {2} ", board[r, 0], board[r, 1], board[r, 2]);
if (r < 2)
{
Console.WriteLine("----+----+-----");
}
}
Console.WriteLine($"Symbol {player.Symbol} is placed at {player.Row}, {player.Column}");
}
if (player2.IsSquareTaken == false)
{
for (int r = 0; r < 3; r++)
{
Console.WriteLine(" {0} | {1} | {2} ", board[r, 0], board[r, 1], board[r, 2]);
if (r < 2)
{
Console.WriteLine("----+----+-----");
}
}
Console.WriteLine($"Symbol {player.Symbol} is placed at {player.Row}, {player.Column}");
}
}
}
}
Код: Выделить всё
internal partial class Program
{
static void Main(string[] args)
{
TicTacToeGame game = new TicTacToeGame();
game.InitializeBoard();
game.DisplayPlacedSymbol();
}
}
Код: Выделить всё
Row = (userInput - 1) / 3;
Column = (userInput - 1) % 3;
Подробнее здесь: https://stackoverflow.com/questions/787 ... -game-in-c