TourIAm/TIAMSharedUI/Pages/TicTacToe.razor

118 lines
3.2 KiB
Plaintext

@page "/tictactoe"
@using Microsoft.AspNetCore.SignalR.Client
@using AyCode.Core.Loggers
@using AyCode.Services.Loggers
@using TIAM.Core.Loggers
@using TIAMWebApp.Shared.Application.Utility
@inject NavigationManager Navigation
@inject IEnumerable<IAcLogWriterClientBase> LogWriters
<h3>Tic Tac Toe</h3>
<div class="game-board">
@for (int i = 0; i < 3; i++)
{
<div class="board-row">
@for (int j = 0; j < 3; j++)
{
<button class="square" @onclick="() => MakeMove(i, j)">
@board[i, j]
</button>
}
</div>
}
</div>
<div class="status">
@if (!string.IsNullOrEmpty(winner))
{
<p>@winner wins!</p>
}
else if (board.Cast<string>().All(cell => cell != null))
{
<p>It's a draw!</p>
}
else
{
<p>Next player: @currentPlayer</p>
}
</div>
@code {
private string[,] board = new string[3, 3];
private string currentPlayer = "X";
private string winner;
private HubConnection hubConnection;
private string groupName = "tictactoe";
private LoggerClient<TicTacToe> _logger;
protected override async Task OnInitializedAsync()
{
_logger = new LoggerClient<TicTacToe>(LogWriters.ToArray());
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/gamehub"))
.Build();
hubConnection.On<int, int, string>("ReceiveMove", (row, col, player) =>
{
if (row >= 0 && row < 3 && col >= 0 && col < 3)
{
board[row, col] = player;
if (CheckWinner())
{
winner = player;
}
StateHasChanged();
}
});
await hubConnection.StartAsync();
await JoinGameGroup();
}
private async Task JoinGameGroup()
{
await hubConnection.SendAsync("JoinGame", groupName);
}
private async Task MakeMove(int row, int col)
{
_logger.DetailConditional($"row: {row}, col: {col}");
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row, col] == null && winner == null)
{
board[row, col] = currentPlayer;
if (CheckWinner())
{
winner = currentPlayer;
}
await hubConnection.SendAsync("MakeMove", groupName, row, col, currentPlayer);
currentPlayer = currentPlayer == "X" ? "O" : "X";
}
}
private bool CheckWinner()
{
// Check rows, columns and diagonals for a win
for (int i = 0; i < 3; i++)
{
if (board[i, 0] != null && board[i, 0] == board[i, 1] && board[i, 1] == board[i, 2])
{
return true;
}
if (board[0, i] != null && board[0, i] == board[1, i] && board[1, i] == board[2, i])
{
return true;
}
}
if (board[0, 0] != null && board[0, 0] == board[1, 1] && board[1, 1] == board[2, 2])
{
return true;
}
if (board[0, 2] != null && board[0, 2] == board[1, 1] && board[1, 1] == board[2, 0])
{
return true;
}
return false;
}
}