oecs-sharp/examples/TicTacToe/Systems/RenderSystem.cs

70 lines
2.2 KiB
C#
Raw Normal View History

using OECS;
namespace TicTacToe;
/// <summary>
/// Prints the board to the console.
/// </summary>
public class RenderSystem : ISystem
{
public QueryDescriptor Query { get; }
public RenderSystem(World world)
{
Query = world.Query().With<Cell>().Build();
}
public void Run(World world)
{
var state = world.ReadSingleton<GameState>();
// Build a 3×3 grid.
var grid = new char[3, 3];
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
grid[r, c] = '.';
// Fill in placed marks using the iterator API.
var markQuery = world.Query().With<Cell>().With<Mark>().Build();
using var markIter = world.Select<Cell, Mark>(markQuery);
while (markIter.MoveNext())
{
grid[markIter.Current1.Row, markIter.Current1.Col] =
markIter.Current2.Player == Player.X ? 'X' : 'O';
}
Console.WriteLine();
Console.WriteLine(" Tic-Tac-Toe");
Console.WriteLine(" ═══════════");
Console.WriteLine();
Console.WriteLine(" 0 1 2");
Console.WriteLine(" ┌───┬───┬───┐");
for (int r = 0; r < 3; r++)
{
Console.Write($"{r} │");
for (int c = 0; c < 3; c++)
{
Console.Write($" {grid[r, c]} ");
if (c < 2) Console.Write("│");
}
Console.WriteLine("│");
if (r < 2) Console.WriteLine(" ├───┼───┼───┤");
}
Console.WriteLine(" └───┴───┴───┘");
Console.WriteLine();
// Status line.
var statusText = state.Status switch
{
GameStatus.Playing => $"{(state.CurrentPlayer == Player.X ? 'X' : 'O')}'s turn (move {state.MoveCount + 1})",
GameStatus.XWon => "X wins!",
GameStatus.OWon => "O wins!",
GameStatus.Draw => "It's a draw!",
_ => ""
};
Console.WriteLine($" {statusText}");
Console.WriteLine();
Console.Write(" Enter row col (e.g. \"1 2\"): ");
}
}