Move from the hand.

This commit is contained in:
2023-02-01 22:49:28 -06:00
parent e2eff4f8b5
commit 3bf9aa3ee3
29 changed files with 248 additions and 133 deletions

View File

@@ -88,6 +88,9 @@ public class SessionsController : ControllerBase
var session = await sessionRepository.ReadSession(name); var session = await sessionRepository.ReadSession(name);
if (session == null) return this.NotFound(); if (session == null) return this.NotFound();
var players = await queryRespository.GetUsersForSession(session.Name);
if (players == null) return this.NotFound();
return new ReadSessionResponse return new ReadSessionResponse
{ {
Session = new Session Session = new Session
@@ -100,8 +103,8 @@ public class SessionsController : ControllerBase
PlayerInCheck = session.Board.BoardState.InCheck?.ToContract(), PlayerInCheck = session.Board.BoardState.InCheck?.ToContract(),
WhoseTurn = session.Board.BoardState.WhoseTurn.ToContract() WhoseTurn = session.Board.BoardState.WhoseTurn.ToContract()
}, },
Player1 = session.Player1, Player1 = players.Value.Player1,
Player2 = session.Player2, Player2 = players.Value.Player2,
SessionName = session.Name SessionName = session.Name
} }
}; };

View File

@@ -8,10 +8,10 @@ namespace Shogi.Api.Managers;
public interface ISocketConnectionManager public interface ISocketConnectionManager
{ {
Task BroadcastToAll(ISocketResponse response); Task BroadcastToAll(ISocketMessage response);
void Subscribe(WebSocket socket, string playerName); void Subscribe(WebSocket socket, string playerName);
void Unsubscribe(string playerName); void Unsubscribe(string playerName);
Task BroadcastToPlayers(ISocketResponse response, params string?[] playerNames); Task BroadcastToPlayers(ISocketMessage response, params string?[] playerNames);
} }
/// <summary> /// <summary>
@@ -45,7 +45,7 @@ public class SocketConnectionManager : ISocketConnectionManager
connections.TryRemove(playerName, out _); connections.TryRemove(playerName, out _);
} }
public async Task BroadcastToPlayers(ISocketResponse response, params string?[] playerNames) public async Task BroadcastToPlayers(ISocketMessage response, params string?[] playerNames)
{ {
var tasks = new List<Task>(playerNames.Length); var tasks = new List<Task>(playerNames.Length);
foreach (var name in playerNames) foreach (var name in playerNames)
@@ -59,7 +59,7 @@ public class SocketConnectionManager : ISocketConnectionManager
} }
await Task.WhenAll(tasks); await Task.WhenAll(tasks);
} }
public Task BroadcastToAll(ISocketResponse response) public Task BroadcastToAll(ISocketMessage response)
{ {
var message = Serialize(response); var message = Serialize(response);
logger.LogInformation("Broadcasting:\n{0}\nDone Broadcasting.", message); logger.LogInformation("Broadcasting:\n{0}\nDone Broadcasting.", message);

View File

@@ -1,6 +1,7 @@
using Dapper; using Dapper;
using Shogi.Contracts.Api; using Shogi.Contracts.Api;
using Shogi.Contracts.Types; using Shogi.Contracts.Types;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
namespace Shogi.Api.Repositories; namespace Shogi.Api.Repositories;
@@ -32,9 +33,33 @@ public class QueryRepository : IQueryRespository
AllOtherSessions = otherSessions.ToList() AllOtherSessions = otherSessions.ToList()
}; };
} }
/// <summary>
/// </summary>
/// <returns>A <see cref="ValueTuple"/> with Item1 as player 1 and Item2 as player 2.</returns>
public async Task<(User Player1, User? Player2)?> GetUsersForSession(string sessionName)
{
using var connection = new SqlConnection(connectionString);
var results = await connection.QueryAsync<(string Player1Name, string Player1DisplayName, string Player2Name, string Player2DisplayName)>(
"session.ReadUsersBySession",
new { SessionName = sessionName },
commandType: CommandType.StoredProcedure);
if (results.Any())
{
var (Player1Name, Player1DisplayName, Player2Name, Player2DisplayName) = results.First();
var p1 = new User(Player1Name, Player1DisplayName);
var p2 = Player2Name != null
? new User(Player2Name, Player2DisplayName)
: null;
return (p1, p2);
}
return null;
}
} }
public interface IQueryRespository public interface IQueryRespository
{ {
Task<(User Player1, User? Player2)?> GetUsersForSession(string sessionName);
Task<ReadSessionsPlayerCountResponse> ReadSessionPlayerCount(string playerName); Task<ReadSessionsPlayerCountResponse> ReadSessionPlayerCount(string playerName);
} }

View File

@@ -73,6 +73,15 @@ public class SessionRepository : ISessionRepository
public async Task CreateMove(string sessionName, MovePieceCommand command) public async Task CreateMove(string sessionName, MovePieceCommand command)
{ {
var yep = new
{
command.To,
command.From,
command.IsPromotion,
command.PieceFromHand,
SessionName = sessionName
};
using var connection = new SqlConnection(connectionString); using var connection = new SqlConnection(connectionString);
await connection.ExecuteAsync( await connection.ExecuteAsync(
"session.CreateMove", "session.CreateMove",
@@ -81,7 +90,7 @@ public class SessionRepository : ISessionRepository
command.To, command.To,
command.From, command.From,
command.IsPromotion, command.IsPromotion,
command.PieceFromHand, PieceFromHand = command.PieceFromHand.ToString(),
SessionName = sessionName SessionName = sessionName
}, },
commandType: CommandType.StoredProcedure); commandType: CommandType.StoredProcedure);

View File

@@ -59,7 +59,7 @@ namespace Shogi.Api.Services
var message = await socket.ReceiveTextAsync(); var message = await socket.ReceiveTextAsync();
if (string.IsNullOrWhiteSpace(message)) continue; if (string.IsNullOrWhiteSpace(message)) continue;
logger.LogInformation("Request \n{0}\n", message); logger.LogInformation("Request \n{0}\n", message);
var request = JsonSerializer.Deserialize<ISocketRequest>(message); var request = JsonSerializer.Deserialize<ISocketMessage>(message);
if (request == null || !Enum.IsDefined(typeof(SocketAction), request.Action)) if (request == null || !Enum.IsDefined(typeof(SocketAction), request.Action))
{ {
await socket.SendTextAsync("Error: Action not recognized."); await socket.SendTextAsync("Error: Action not recognized.");

View File

@@ -2,12 +2,12 @@
namespace Shogi.Contracts.Socket; namespace Shogi.Contracts.Socket;
public interface ISocketResponse public interface ISocketMessage
{ {
SocketAction Action { get; } SocketAction Action { get; }
} }
public class SocketResponse : ISocketResponse public class SocketResponse : ISocketMessage
{ {
public SocketAction Action { get; set; } public SocketAction Action { get; set; }
} }

View File

@@ -1,9 +0,0 @@
using Shogi.Contracts.Types;
namespace Shogi.Contracts.Socket
{
public interface ISocketRequest
{
SocketAction Action { get; }
}
}

View File

@@ -2,7 +2,7 @@
namespace Shogi.Contracts.Socket; namespace Shogi.Contracts.Socket;
public class PlayerHasMovedMessage : ISocketResponse public class PlayerHasMovedMessage : ISocketMessage
{ {
public SocketAction Action { get; } public SocketAction Action { get; }
public string SessionName { get; set; } public string SessionName { get; set; }

View File

@@ -2,7 +2,7 @@
namespace Shogi.Contracts.Socket; namespace Shogi.Contracts.Socket;
public class SessionCreatedSocketMessage : ISocketResponse public class SessionCreatedSocketMessage : ISocketMessage
{ {
public SocketAction Action => SocketAction.SessionCreated; public SocketAction Action => SocketAction.SessionCreated;
} }

View File

@@ -2,11 +2,11 @@
namespace Shogi.Contracts.Socket; namespace Shogi.Contracts.Socket;
public class SessionJoinedByPlayerSocketMessage : ISocketResponse public class SessionJoinedByPlayerSocketMessage : ISocketMessage
{ {
public SocketAction Action => SocketAction.SessionJoined; public SocketAction Action => SocketAction.SessionJoined;
public string SessionName { get; } public string SessionName { get; set; }
public SessionJoinedByPlayerSocketMessage(string sessionName) public SessionJoinedByPlayerSocketMessage(string sessionName)
{ {

View File

@@ -2,8 +2,8 @@
public class Session public class Session
{ {
public string Player1 { get; set; } public User Player1 { get; set; }
public string? Player2 { get; set; } public User? Player2 { get; set; }
public string SessionName { get; set; } public string SessionName { get; set; }
public BoardState BoardState { get; set; } public BoardState BoardState { get; set; }
} }

View File

@@ -1,9 +1,17 @@
namespace Shogi.Contracts.Types namespace Shogi.Contracts.Types;
public class User
{ {
public class User
{
public string Id { get; set; } = string.Empty; public string Id { get; set; } = string.Empty;
/// <summary>
/// A display name for the user.
/// </summary>
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public User(string id, string name)
{
Id = id;
Name = name;
} }
} }

View File

@@ -1,8 +1,8 @@
CREATE PROCEDURE [session].[CreateMove] CREATE PROCEDURE [session].[CreateMove]
@To VARCHAR(2), @To VARCHAR(2),
@From VARCHAR(2), @From VARCHAR(2) = NULL,
@IsPromotion BIT, @IsPromotion BIT = 0,
@PieceFromHand NVARCHAR(13), @PieceFromHand NVARCHAR(13) = NULL,
@SessionName [session].[SessionName] @SessionName [session].[SessionName]
AS AS
@@ -19,7 +19,7 @@ BEGIN
WHERE [Name] = @SessionName; WHERE [Name] = @SessionName;
DECLARE @PieceIdFromhand INT = NULL; DECLARE @PieceIdFromhand INT = NULL;
SELECT @PieceIdFromhand SELECT @PieceIdFromhand = Id
FROM [session].[Piece] FROM [session].[Piece]
WHERE [Name] = @PieceFromHand; WHERE [Name] = @PieceFromHand;

View File

@@ -0,0 +1,13 @@
CREATE PROCEDURE [session].[ReadUsersBySession]
@SessionName [session].[SessionName]
AS
SELECT
p1.[Name] as Player1Name,
p1.DisplayName as Player1DisplayName,
p2.[Name] as Player2Name,
p2.DisplayName as Player2Displayname
FROM [session].[Session] sess
INNER JOIN [user].[User] p1 ON sess.Player1Id = p1.Id
LEFT JOIN [user].[User] p2 on sess.Player2Id = p2.Id
WHERE sess.[Name] = @SessionName;

View File

@@ -4,12 +4,19 @@
[SessionId] BIGINT NOT NULL, [SessionId] BIGINT NOT NULL,
[To] VARCHAR(2) NOT NULL, [To] VARCHAR(2) NOT NULL,
[From] VARCHAR(2) NULL, [From] VARCHAR(2) NULL,
[IsPromotion] BIT NULL, [PieceIdFromHand] INT NULL,
[PieceIdFromHand] INT NULL [IsPromotion] BIT DEFAULT 0
CONSTRAINT [Cannot end where you start] CONSTRAINT [Cannot end where you start]
CHECK ([From] <> [To]), CHECK ([From] <> [To]),
CONSTRAINT [Move cannot start from two places]
CHECK (
( [From] IS NOT NULL AND [PieceIdFromHand] IS NULL )
OR
( [From] IS NULL AND [PieceIdFromhand] IS NOT NULL )
),
CONSTRAINT FK_Move_Session FOREIGN KEY (SessionId) REFERENCES [session].[Session] (Id) CONSTRAINT FK_Move_Session FOREIGN KEY (SessionId) REFERENCES [session].[Session] (Id)
ON DELETE CASCADE ON DELETE CASCADE
ON UPDATE CASCADE, ON UPDATE CASCADE,

View File

@@ -88,6 +88,7 @@
<Build Include="Session\Tables\Piece.sql" /> <Build Include="Session\Tables\Piece.sql" />
<Build Include="Session\Stored Procedures\DeleteSession.sql" /> <Build Include="Session\Stored Procedures\DeleteSession.sql" />
<Build Include="Session\Stored Procedures\CreateMove.sql" /> <Build Include="Session\Stored Procedures\CreateMove.sql" />
<Build Include="Session\Stored Procedures\ReadUsersBySession.sql" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PostDeploy Include="Post Deployment\Script.PostDeployment.sql" /> <PostDeploy Include="Post Deployment\Script.PostDeployment.sql" />

View File

@@ -1,6 +1,6 @@
CREATE TABLE [user].[User] CREATE TABLE [user].[User]
( (
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY, [Id] BIGINT NOT NULL PRIMARY KEY IDENTITY, -- TODO: Consider using user.UserName as the PK to avoid confusing "Id" in the database vs "Id" in the domain model.
[Name] [user].[UserName] NOT NULL UNIQUE, [Name] [user].[UserName] NOT NULL UNIQUE,
[DisplayName] NVARCHAR(100) NOT NULL, [DisplayName] NVARCHAR(100) NOT NULL,
[Platform] NVARCHAR(20) NOT NULL, [Platform] NVARCHAR(20) NOT NULL,

View File

@@ -15,7 +15,13 @@ public class Session
public string Name { get; } public string Name { get; }
public ShogiBoard Board { get; } public ShogiBoard Board { get; }
/// <summary>
/// The User.Id of the player which created the session.
/// </summary>
public string Player1 { get; } public string Player1 { get; }
/// <summary>
/// The User.Id of the second player.
/// </summary>
public string? Player2 { get; private set; } public string? Player2 { get; private set; }
public void AddPlayer2(string player2Name) public void AddPlayer2(string player2Name)

View File

@@ -59,9 +59,9 @@ else
{ {
var accountId = Account.User?.Id; var accountId = Account.User?.Id;
this.perspective = accountId == session.Player2 ? WhichPlayer.Player2 : WhichPlayer.Player1; this.perspective = accountId == session.Player1.Id ? WhichPlayer.Player1 : WhichPlayer.Player2;
this.isSpectating = !(accountId == this.session.Player1 || accountId == this.session.Player2); Console.WriteLine(new { this.perspective, accountId });
Console.WriteLine($"IsSpectating - {isSpectating}. AccountId - {accountId}. Player1 - {this.session.Player1}. Player2 - {this.session.Player2}"); this.isSpectating = !(accountId == this.session.Player1.Id || accountId == this.session.Player2?.Id);
} }
StateHasChanged(); StateHasChanged();

View File

@@ -1,4 +1,5 @@
@using Shogi.Contracts.Types; @using Shogi.Contracts.Types;
@using System.Text.Json;
@inject PromotePrompt PromotePrompt; @inject PromotePrompt PromotePrompt;
@inject AccountState AccountState; @inject AccountState AccountState;
@@ -70,7 +71,6 @@
<div class="hand"> <div class="hand">
@if (opponentHand.Any()) @if (opponentHand.Any())
{ {
@foreach (var piece in opponentHand) @foreach (var piece in opponentHand)
{ {
<div class="tile"> <div class="tile">
@@ -78,20 +78,29 @@
</div> </div>
} }
} }
else
{
<i class="place-self-center">Hand is empty.</i>
}
</div> </div>
<p class="text-center">Opponent Hand</p>
</div> </div>
<div class="spacer place-self-center"> <div class="spacer place-self-center text-center">
<p>@opponentName</p> <p>@opponentName</p>
<p title="It is @(IsMyTurn ? "your" : "their") turn.">
<svg width="32" height="32" fill="currentColor">
@if (IsMyTurn)
{
<use xlink:href="css/bootstrap/bootstrap-icons.svg#chevron-down" />
}
else
{
<use xlink:href="css/bootstrap/bootstrap-icons.svg#chevron-up" />
}
</svg>
</p>
<p>@userName</p> <p>@userName</p>
</div> </div>
<div class="player-area"> <div class="player-area">
@if (Session.Player2 == null && Session.Player1 != AccountState.User?.Id) @if (Session.Player2 == null && Session.Player1.Id != AccountState.User?.Id)
{ {
<div class="place-self-center"> <div class="place-self-center">
<p>Seat is Empty</p> <p>Seat is Empty</p>
@@ -100,20 +109,19 @@
} }
else else
{ {
<p class="text-center">Hand</p>
<div class="hand"> <div class="hand">
@if (userHand.Any()) @if (userHand.Any())
{ {
@foreach (var piece in userHand) @foreach (var piece in userHand)
{ {
<div class="title" @onclick="OnClickHandInternal(piece)"> <div @onclick="OnClickHandInternal(piece)"
class="tile"
data-selected="@(piece.WhichPiece == SelectedPieceFromHand)">
<GamePiece Piece="piece" Perspective="Perspective" /> <GamePiece Piece="piece" Perspective="Perspective" />
</div> </div>
} }
} }
else
{
<i class="place-self-center">Hand is empty.</i>
}
</div> </div>
} }
</div> </div>
@@ -132,10 +140,12 @@
[Parameter] public WhichPlayer Perspective { get; set; } [Parameter] public WhichPlayer Perspective { get; set; }
[Parameter] public Session? Session { get; set; } [Parameter] public Session? Session { get; set; }
[Parameter] public string? SelectedPosition { get; set; } [Parameter] public string? SelectedPosition { get; set; }
[Parameter] public WhichPiece? SelectedPieceFromHand { get; set; }
// TODO: Exchange these OnClick actions for events like "SelectionChangedEvent" and "MoveFromBoardEvent" and "MoveFromHandEvent". // TODO: Exchange these OnClick actions for events like "SelectionChangedEvent" and "MoveFromBoardEvent" and "MoveFromHandEvent".
[Parameter] public Func<Piece?, string, Task>? OnClickTile { get; set; } [Parameter] public Func<Piece?, string, Task>? OnClickTile { get; set; }
[Parameter] public Func<Piece, Task>? OnClickHand { get; set; } [Parameter] public Func<Piece, Task>? OnClickHand { get; set; }
[Parameter] public Func<Task>? OnClickJoinGame { get; set; } [Parameter] public Func<Task>? OnClickJoinGame { get; set; }
[Parameter] public bool IsMyTurn { get; set; }
private IReadOnlyCollection<Piece> opponentHand; private IReadOnlyCollection<Piece> opponentHand;
private IReadOnlyCollection<Piece> userHand; private IReadOnlyCollection<Piece> userHand;
@@ -152,7 +162,6 @@
protected override void OnParametersSet() protected override void OnParametersSet()
{ {
Console.WriteLine("Params changed. SelectedPosition = {0}", SelectedPosition);
base.OnParametersSet(); base.OnParametersSet();
if (Session == null) if (Session == null)
{ {
@@ -163,6 +172,7 @@
} }
else else
{ {
Console.WriteLine(JsonSerializer.Serialize(new { this.Session.Player1, this.Session.Player2, Perspective, this.Session.SessionName }));
opponentHand = Perspective == WhichPlayer.Player1 opponentHand = Perspective == WhichPlayer.Player1
? this.Session.BoardState.Player2Hand ? this.Session.BoardState.Player2Hand
: this.Session.BoardState.Player1Hand; : this.Session.BoardState.Player1Hand;
@@ -170,11 +180,11 @@
? this.Session.BoardState.Player1Hand ? this.Session.BoardState.Player1Hand
: this.Session.BoardState.Player2Hand; : this.Session.BoardState.Player2Hand;
userName = Perspective == WhichPlayer.Player1 userName = Perspective == WhichPlayer.Player1
? this.Session.Player1 ? this.Session.Player1.Name
: this.Session.Player2; : this.Session.Player2?.Name ?? "Empty Seat";
opponentName = Perspective == WhichPlayer.Player1 opponentName = Perspective == WhichPlayer.Player1
? this.Session.Player2 ? this.Session.Player2?.Name ?? "Empty Seat"
: this.Session.Player1; : this.Session.Player1.Name;
} }
} }

View File

@@ -1,7 +1,7 @@
.game-board { .game-board {
display: grid; display: grid;
grid-template-areas: "board side-board icons"; grid-template-areas: "board side-board icons";
grid-template-columns: 3fr minmax(10rem, 1fr) auto; grid-template-columns: max-content minmax(25rem, 1fr) 2fr;
gap: 0.5rem; gap: 0.5rem;
background-color: #444; background-color: #444;
position: relative; /* For absolute positioned children. */ position: relative; /* For absolute positioned children. */
@@ -58,17 +58,18 @@
} }
.tile { .tile {
background-color: beige;
display: grid; display: grid;
place-content: center; place-content: center;
padding: 0.25rem;
overflow: hidden; /* Because SVGs are shaped weird */
transition: filter linear 0.25s; transition: filter linear 0.25s;
} }
.tile[data-selected] { .board .tile {
background-color: beige;
}
.tile[data-selected] {
filter: invert(0.8); filter: invert(0.8);
} }
.ruler { .ruler {
color: beige; color: beige;
@@ -90,20 +91,30 @@
} }
.side-board { .side-board {
display: grid; display: flex;
grid-auto-rows: 1fr; flex-direction: column;
place-content: space-between;
padding: 1rem; padding: 1rem;
background-color: var(--contrast-color); background-color: var(--contrast-color);
} }
.side-board .player-area { .side-board .player-area {
display: grid; display: grid;
place-items: stretch;
} }
.side-board .hand { .side-board .hand {
display: grid; display: grid;
grid-auto-columns: 1fr;
border: 1px solid #ccc; border: 1px solid #ccc;
grid-template-columns: repeat(7, 1fr);
grid-template-rows: 4rem;
place-items: center start;
padding: 0.5rem;
}
.side-board .hand .tile {
max-height: 100%; /* I have no idea why I need to set this here to prevent a height blowout. */
background-color: var(--secondary-color);
} }
.promote-prompt { .promote-prompt {

View File

@@ -9,7 +9,9 @@
Perspective="Perspective" Perspective="Perspective"
OnClickHand="OnClickHand" OnClickHand="OnClickHand"
OnClickTile="OnClickTile" OnClickTile="OnClickTile"
SelectedPosition="@selectedBoardPosition" /> SelectedPosition="@selectedBoardPosition"
SelectedPieceFromHand="@selectedPieceFromHand"
IsMyTurn="IsMyTurn" />
@code { @code {
[Parameter, EditorRequired] [Parameter, EditorRequired]
@@ -23,6 +25,8 @@
protected override void OnParametersSet() protected override void OnParametersSet()
{ {
base.OnParametersSet(); base.OnParametersSet();
selectedBoardPosition = null;
selectedPieceFromHand = null;
if (Session == null) if (Session == null)
{ {
throw new ArgumentException($"{nameof(Session)} cannot be null.", nameof(Session)); throw new ArgumentException($"{nameof(Session)} cannot be null.", nameof(Session));
@@ -42,51 +46,77 @@
return false; return false;
} }
async Task OnClickTile(Piece? piece, string position) async Task OnClickTile(Piece? pieceAtPosition, string position)
{ {
Console.WriteLine("Is my turn?");
Console.WriteLine(true);
if (!IsMyTurn) return; if (!IsMyTurn) return;
if (selectedBoardPosition == null || piece?.Owner == Perspective)
{
// Select a position.
Console.WriteLine("Position {0}", position);
selectedBoardPosition = position;
StateHasChanged();
return;
}
if (selectedBoardPosition == position) if (selectedBoardPosition == position)
{ {
// Deselect the selected position. // Deselect the selected position.
selectedBoardPosition = null; selectedBoardPosition = null;
StateHasChanged();
return; return;
} }
if (piece == null)
if (selectedBoardPosition == null && pieceAtPosition?.Owner == Perspective)
{ {
// Select an owned piece.
Console.WriteLine("Selecting piece owned by {0} while I am perspective {1}", pieceAtPosition?.Owner, Perspective);
selectedBoardPosition = position;
// Prevent selecting pieces from the hand and board at the same time.
selectedPieceFromHand = null;
StateHasChanged();
return;
}
if (selectedPieceFromHand is not null)
{
if (pieceAtPosition is null)
{
Console.WriteLine("Moving piece from hand.");
// Placing a piece from the hand to an empty space.
// await ShogiApi.Move(
// Session.SessionName,
// new MovePieceCommand(selectedPieceFromHand.Value, position));
}
StateHasChanged();
return;
}
if (selectedBoardPosition != null)
{
if (pieceAtPosition == null || pieceAtPosition?.Owner != Perspective)
{
// Moving to an empty space or capturing an opponent's piece.
if (ShouldPromptForPromotion(position) || ShouldPromptForPromotion(selectedBoardPosition)) if (ShouldPromptForPromotion(position) || ShouldPromptForPromotion(selectedBoardPosition))
{ {
PromotePrompt.Show(Session.SessionName, new MovePieceCommand PromotePrompt.Show(
{ Session.SessionName,
From = selectedBoardPosition, new MovePieceCommand(selectedBoardPosition, position, false));
To = position
});
} }
else else
{ {
await ShogiApi.Move(Session.SessionName, new MovePieceCommand await ShogiApi.Move(Session.SessionName, new MovePieceCommand(selectedBoardPosition, position, false));
{ }
From = selectedBoardPosition, StateHasChanged();
IsPromotion = false, return;
To = position
});
} }
} }
} }
async Task OnClickHand(Piece piece) async Task OnClickHand(Piece piece)
{ {
selectedPieceFromHand = piece.WhichPiece; if (!IsMyTurn) return;
await Task.CompletedTask;
// Prevent selecting from both the hand and the board.
selectedBoardPosition = null;
selectedPieceFromHand = piece.WhichPiece == selectedPieceFromHand
// Deselecting the already-selected piece
? selectedPieceFromHand = null
: selectedPieceFromHand = piece.WhichPiece;
StateHasChanged();
} }
} }

View File

@@ -3,7 +3,7 @@
@inject IShogiApi ShogiApi; @inject IShogiApi ShogiApi;
<GameBoardPresentation IsSpectating="true" <GameBoardPresentation IsSpectating="true"
Perspective="WhichPlayer.Player1" Perspective="WhichPlayer.Player2"
Session="Session" Session="Session"
OnClickJoinGame="OnClickJoinGame" /> OnClickJoinGame="OnClickJoinGame" />

View File

@@ -1,6 +1,6 @@
@using Shogi.Contracts.Types @using Shogi.Contracts.Types
<div data-upsidedown="@(Piece?.Owner != Perspective)" data-owner="@Piece?.Owner.ToString()"> <div class="game-piece" data-upsidedown="@(Piece?.Owner != Perspective)" data-owner="@Piece?.Owner.ToString()">
@switch (Piece?.WhichPiece) @switch (Piece?.WhichPiece)
{ {
case WhichPiece.Bishop: case WhichPiece.Bishop:

View File

@@ -6,3 +6,7 @@
[data-upsidedown] { [data-upsidedown] {
transform: rotateZ(180deg); transform: rotateZ(180deg);
} }
.game-piece {
overflow: hidden; /* Because SVGs have weird sizes. */
}

View File

@@ -63,8 +63,6 @@ static void ConfigureDependencies(IServiceCollection services, IConfiguration co
var serializerOptions = new JsonSerializerOptions var serializerOptions = new JsonSerializerOptions
{ {
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true WriteIndented = true
}; };
services.AddScoped((sp) => serializerOptions); services.AddScoped((sp) => serializerOptions);

View File

@@ -29,7 +29,6 @@
void OnModalChange(object? sender, ModalVisibilityChangedEventArgs args) void OnModalChange(object? sender, ModalVisibilityChangedEventArgs args)
{ {
Console.WriteLine("Modal Change");
if (args != null) if (args != null)
{ {
shouldShow = args.LoginModalIsVisible || args.GuestAccountDescriptionIsVisible; shouldShow = args.LoginModalIsVisible || args.GuestAccountDescriptionIsVisible;

View File

@@ -38,11 +38,9 @@ public class ShogiSocket : IDisposable
}.ToQueryString().Value; }.ToQueryString().Value;
await socket.ConnectAsync(this.uriBuilder.Uri, cancelToken.Token); await socket.ConnectAsync(this.uriBuilder.Uri, cancelToken.Token);
Console.WriteLine("Socket Connected");
// Fire and forget! I'm way too lazy to write my own javascript interop to a web worker. Nooo thanks. // Fire and forget! I'm way too lazy to write my own javascript interop to a web worker. Nooo thanks.
_ = Listen().ContinueWith(async antecedent => _ = Listen().ContinueWith(async antecedent =>
{ {
Console.WriteLine($"Socket fault. {antecedent.Exception}");
this.cancelToken.Cancel(); this.cancelToken.Cancel();
await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Page was probably closed or refresh.", CancellationToken.None); await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Page was probably closed or refresh.", CancellationToken.None);
if (antecedent.Exception != null) if (antecedent.Exception != null)
@@ -59,9 +57,9 @@ public class ShogiSocket : IDisposable
var result = await socket.ReceiveAsync(this.memoryOwner.Memory, cancelToken.Token); var result = await socket.ReceiveAsync(this.memoryOwner.Memory, cancelToken.Token);
var memory = this.memoryOwner.Memory[..result.Count].ToArray(); var memory = this.memoryOwner.Memory[..result.Count].ToArray();
var action = JsonDocument var action = JsonDocument
.Parse(memory[..result.Count]) .Parse(memory)
.RootElement .RootElement
.GetProperty(nameof(ISocketResponse.Action)) .GetProperty(nameof(ISocketMessage.Action))
.Deserialize<SocketAction>(); .Deserialize<SocketAction>();
Console.WriteLine($"Socket action: {action}"); Console.WriteLine($"Socket action: {action}");
@@ -76,14 +74,14 @@ public class ShogiSocket : IDisposable
case SocketAction.SessionJoined: case SocketAction.SessionJoined:
if (this.OnSessionJoined is not null) if (this.OnSessionJoined is not null)
{ {
var args = JsonSerializer.Deserialize<SessionJoinedByPlayerSocketMessage>(memory[..result.Count], serializerOptions); var args = JsonSerializer.Deserialize<SessionJoinedByPlayerSocketMessage>(memory, serializerOptions);
await this.OnSessionJoined(args!); await this.OnSessionJoined(args!);
} }
break; break;
case SocketAction.PieceMoved: case SocketAction.PieceMoved:
if (this.OnPlayerMoved is not null) if (this.OnPlayerMoved is not null)
{ {
var args = JsonSerializer.Deserialize<PlayerHasMovedMessage>(memory[..result.Count], serializerOptions); var args = JsonSerializer.Deserialize<PlayerHasMovedMessage>(memory, serializerOptions);
await this.OnPlayerMoved(args!); await this.OnPlayerMoved(args!);
} }
break; break;

View File

@@ -37,7 +37,9 @@ public class AcceptanceTests : IClassFixture<GuestTestFixture>
// Assert // Assert
joinResponse.StatusCode.Should().Be(HttpStatusCode.OK); joinResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var readSessionResponse = await ReadTestSession(); var readSessionResponse = await ReadTestSession();
readSessionResponse.Session.Player2.Should().NotBeNullOrEmpty(); readSessionResponse.Session.Player2.Should().NotBeNull();
readSessionResponse.Session.Player2!.Id.Should().NotBeNullOrEmpty();;
readSessionResponse.Session.Player2.Name.Should().NotBeNullOrEmpty(); ;
} }
finally finally
{ {
@@ -55,7 +57,7 @@ public class AcceptanceTests : IClassFixture<GuestTestFixture>
var joinResponse = await guest2HttpClient.PatchAsync(new Uri("Sessions/Acceptance Tests/Join", UriKind.Relative), null); var joinResponse = await guest2HttpClient.PatchAsync(new Uri("Sessions/Acceptance Tests/Join", UriKind.Relative), null);
joinResponse.StatusCode.Should().Be(HttpStatusCode.OK); joinResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var readSessionResponse = await ReadTestSession(); var readSessionResponse = await ReadTestSession();
readSessionResponse.Session.Player2.Should().NotBeNullOrEmpty(); readSessionResponse.Session.Player2.Should().NotBeNull();
// Act // Act
joinResponse = await guest2HttpClient.PatchAsync(new Uri("Sessions/Acceptance Tests/Join", UriKind.Relative), null); joinResponse = await guest2HttpClient.PatchAsync(new Uri("Sessions/Acceptance Tests/Join", UriKind.Relative), null);
@@ -119,7 +121,7 @@ public class AcceptanceTests : IClassFixture<GuestTestFixture>
response.Session.BoardState.Player2Hand.Should().BeEmpty(); response.Session.BoardState.Player2Hand.Should().BeEmpty();
response.Session.BoardState.PlayerInCheck.Should().BeNull(); response.Session.BoardState.PlayerInCheck.Should().BeNull();
response.Session.BoardState.WhoseTurn.Should().Be(WhichPlayer.Player1); response.Session.BoardState.WhoseTurn.Should().Be(WhichPlayer.Player1);
response.Session.Player1.Should().NotBeNullOrEmpty(); response.Session.Player1.Should().NotBeNull();
response.Session.Player2.Should().BeNull(); response.Session.Player2.Should().BeNull();
response.Session.SessionName.Should().Be("Acceptance Tests"); response.Session.SessionName.Should().Be("Acceptance Tests");
} }