Files
Shogi/Shogi.UI/Pages/Home/GameBoard/SeatedGameBoard.razor

93 lines
2.7 KiB
Plaintext

@using Shogi.Contracts.Api;
@using Shogi.Contracts.Types;
@using System.Text.RegularExpressions;
@using System.Net;
@inject PromotePrompt PromotePrompt;
@inject IShogiApi ShogiApi;
<GameBoardPresentation Session="Session"
Perspective="Perspective"
OnClickHand="OnClickHand"
OnClickTile="OnClickTile"
OnClickJoinGame="OnClickJoinGame" />
@code {
[Parameter, EditorRequired]
public WhichPlayer Perspective { get; set; }
[Parameter, EditorRequired]
public Session Session { get; set; }
[Parameter] public Func<Task>? OnRefetchSession { get; set; }
private bool IsMyTurn => Session?.BoardState.WhoseTurn == Perspective;
private string? selectedBoardPosition;
private WhichPiece? selectedPieceFromHand;
bool ShouldPromptForPromotion(string position)
{
if (Perspective == WhichPlayer.Player1 && Regex.IsMatch(position, ".[7-9]"))
{
return true;
}
if (Perspective == WhichPlayer.Player2 && Regex.IsMatch(position, ".[1-3]"))
{
return true;
}
return false;
}
async Task OnClickTile(Piece? piece, string position)
{
if (!IsMyTurn) return;
if (selectedBoardPosition == null || piece?.Owner == Perspective)
{
// Select a position.
selectedBoardPosition = position;
return;
}
if (selectedBoardPosition == position)
{
// Deselect the selected position.
selectedBoardPosition = null;
return;
}
if (piece == null)
{
if (ShouldPromptForPromotion(position) || ShouldPromptForPromotion(selectedBoardPosition))
{
PromotePrompt.Show(Session.SessionName, new MovePieceCommand
{
From = selectedBoardPosition,
To = position
});
}
else
{
await ShogiApi.Move(Session.SessionName, new MovePieceCommand
{
From = selectedBoardPosition,
IsPromotion = false,
To = position
});
}
}
}
async Task OnClickHand(Piece piece)
{
selectedPieceFromHand = piece.WhichPiece;
await Task.CompletedTask;
}
async Task OnClickJoinGame()
{
if (Session != null && OnRefetchSession != null)
{
var status = await ShogiApi.PatchJoinGame(Session.SessionName);
if (status == HttpStatusCode.OK)
{
await OnRefetchSession.Invoke();
}
}
}
}