This commit is contained in:
2024-10-20 22:27:08 -05:00
parent f75553a0ad
commit 3593785421
27 changed files with 1020 additions and 1081 deletions

View File

@@ -10,6 +10,8 @@
/**
* Local setup instructions, in order:
* 1. To setup the Shogi database, use the publish menu option in visual studio with the Shogi.Database project.
* 2. Install the Entity Framework dotnet tools, via power shell run this command: dotnet tool install --global dotnet-ef
* 2. To setup the Entity Framework users database, run this powershell command using Shogi.Api as the target project: dotnet ef database update
*
* 2. Setup Entity Framework because that's what the login system uses.
* 2.a. Install the Entity Framework dotnet tools, via power shell run this command: dotnet tool install --global dotnet-ef
* 2.b. To setup the Entity Framework users database, run this powershell command using Shogi.Api as the target project: dotnet ef database update
*/

View File

@@ -1,81 +0,0 @@
namespace Shogi.Domain.Other;
/// <summary>
/// </summary>
/// <typeparam name="TPiece"></typeparam>
/// <param name="boardState">A 2D array of pieces, representing your board. Indexed as [x, y].</param>
public class BoardRules<TPiece>(TPiece?[,] boardState) where TPiece : IRulesLifecycle<TPiece>
{
private readonly Vector2 MaxIndex = new(boardState.GetLength(0) - 1, boardState.GetLength(1) - 1);
/// <summary>
/// Validates a move, invoking the <see cref="IRulesLifecycle{TPiece}.OnMoveValidation(MoveValidationContext{TPiece})"/> callback which you should implement.
/// A move is considered valid if it could be made legally, ignoring check or check-mate rules.
/// Check and check-mate verifying happens in a different lifecycle callback.
/// </summary>
/// <param name="from">The position of the piece being moved.</param>
/// <param name="to">The desired destination of the piece being moved.</param>
/// <param name="isPromotion">TODO</param>
/// <returns></returns>
public RulesLifecycleResult ValidateMove(Vector2 from, Vector2 to, bool isPromotion)
{
if (IsWithinBounds(from) && IsWithinBounds(to))
{
var piece = boardState[(int)from.X, (int)from.Y];
if (piece == null)
{
return new RulesLifecycleResult(IsError: true, $"There is no piece at position {from}.");
}
return piece.OnMoveValidation(new MoveValidationContext<TPiece>(from, to, isPromotion, boardState));
}
return new RulesLifecycleResult(IsError: true, "test message");
}
//foreach (var piece in boardState)
//{
// if (piece != null)
// {
// var result = piece.OnMoveValidation(new MoveValidationContext<TPiece>(from, to, isPromotion, boardState));
// if (result.IsError)
// {
// return result;
// }
// }
//}
//public int ValidateMove(Vector2 start, Vector2 end)
//{
// if (board.GetLength(0) != boardSize.X || board.GetLength(1) != boardSize.Y)
// {
// throw new ArgumentException($"2D array dimensions must match boardSize given during {nameof(CreateNewRules)} method.", nameof(board));
// }
// if (start - start != Vector2.Zero)
// {
// throw new ArgumentException("Negative values not allowed.", nameof(start));
// }
// if (end - end != Vector2.Zero)
// {
// throw new ArgumentException("Negative values not allowed.", nameof(end));
// }
// if (start.X >= boardSize.X || start.Y >= boardSize.Y)
// {
// throw new ArgumentException("Start position must be within the given boardSize.", nameof(start));
// }
// if (end.X >= boardSize.X || end.Y >= boardSize.Y)
// {
// throw new ArgumentException("End position must be within the given boardSize.", nameof(end));
// }
// return 0;
//}
private bool IsWithinBounds(Vector2 position)
{
var isPositive = position - position == Vector2.Zero;
return isPositive && position.X <= MaxIndex.X && position.Y <= MaxIndex.Y;
}
}

View File

@@ -1,15 +0,0 @@
namespace Shogi.Domain.Other;
public interface IRulesLifecycle<TPiece> where TPiece : IRulesLifecycle<TPiece>
{
/// <summary>
/// Invoked by <see cref="BoardRules{TPiece}.ValidateMove(Vector2, Vector2, bool)"/> during the MoveValidation life cycle event.
/// If a move begins or ends outside the board space coordinates, this function is not called.
/// The purpose is to ensure a proposed board move is valid with regard to the moved piece's rules.
/// This event does not worry about check or check-mate, or if a move is legal.
///
/// </summary>
/// <param name="context">A context object with information for you to use to assess whether a move is valid for your implementing piece.</param>
/// <returns>A new <see cref="RulesLifecycleResult"/> object indicating whether or not the move is valid.</returns>
RulesLifecycleResult OnMoveValidation(MoveValidationContext<TPiece> context);
}

View File

@@ -1,14 +0,0 @@
namespace Shogi.Domain.Other;
public record MoveValidationContext<TPiece>(
Vector2 From,
Vector2 To,
bool IsPromotion,
TPiece?[,] BoardState) where TPiece : IRulesLifecycle<TPiece>
{
public TPiece? GetPieceByRelativePosition(Vector2 relativePosition)
{
var absolute = From + relativePosition;
return BoardState[(int)absolute.X, (int)absolute.Y];
}
}

View File

@@ -1,5 +0,0 @@
namespace Shogi.Domain.Other;
public record RulesLifecycleResult(bool IsError, string ResultMessage = "")
{
}

View File

@@ -39,7 +39,7 @@ public class BoardState
}
/// <summary>
/// Copy constructor.
/// Copy constructor. Creates a deep copy.
/// </summary>
public BoardState(BoardState other)
{
@@ -115,6 +115,7 @@ public class BoardState
var fromPiece = this[fromNotation]
?? throw new InvalidOperationException($"No piece exists at position {fromNotation}.");
if (isPromotionRequested &&
(IsWithinPromotionZone(to) || IsWithinPromotionZone(from)))
{

View File

@@ -5,17 +5,17 @@ namespace Shogi.Domain.ValueObjects;
internal record class GoldGeneral : Piece
{
private static readonly ReadOnlyCollection<Path> Player1Paths = new(new List<Path>(6)
{
public static readonly ReadOnlyCollection<Path> Player1Paths = new(
[
new Path(Direction.Forward),
new Path(Direction.ForwardLeft),
new Path(Direction.ForwardRight),
new Path(Direction.Left),
new Path(Direction.Right),
new Path(Direction.Backward)
});
]);
private static readonly ReadOnlyCollection<Path> Player2Paths =
public static readonly ReadOnlyCollection<Path> Player2Paths =
Player1Paths
.Select(p => p.Invert())
.ToList()

View File

@@ -0,0 +1,9 @@
namespace Shogi.Domain.ValueObjects;
[Flags]
internal enum InCheckResult
{
NobodyInCheck = 1, // This kinda doesn't make sense from a Flags perspective, but it works. =/
Player1InCheck = 2,
Player2InCheck = 4
}

View File

@@ -1,14 +1,6 @@
namespace Shogi.Domain.ValueObjects
{
public class MoveResult
public record MoveResult(bool IsSuccess, string Reason = "")
{
public bool Success { get; }
public string Reason { get; }
public MoveResult(bool isSuccess, string reason = "")
{
Success = isSuccess;
Reason = reason;
}
}
}

View File

@@ -1,11 +1,10 @@
using Shogi.Domain.Other;
using Shogi.Domain.YetToBeAssimilatedIntoDDD.Pathing;
using Shogi.Domain.YetToBeAssimilatedIntoDDD.Pathing;
using System.Diagnostics;
namespace Shogi.Domain.ValueObjects
{
[DebuggerDisplay("{WhichPiece} {Owner}")]
public abstract record class Piece : IRulesLifecycle<Piece>
public abstract record class Piece
{
public static Piece Create(WhichPiece piece, WhichPlayer owner, bool isPromoted = false)
{
@@ -65,7 +64,7 @@ namespace Shogi.Domain.ValueObjects
var position = start;
while (Vector2.Distance(start, position) < Vector2.Distance(start, end))
{
position += path.NormalizedDirection;
position += path.Step;
steps.Add(position);
if (path.Distance == Distance.OneStep) break;
@@ -76,51 +75,7 @@ namespace Shogi.Domain.ValueObjects
return steps;
}
return Array.Empty<Vector2>();
return [];
}
#region IRulesLifecycle
public RulesLifecycleResult OnMoveValidation(MoveValidationContext<Piece> ctx)
{
var paths = this.MoveSet;
var matchingPaths = paths.Where(p => p.NormalizedDirection == Vector2.Normalize(ctx.To - ctx.From));
if (!matchingPaths.Any())
{
return new RulesLifecycleResult(IsError: true, "Piece cannot move like that.");
}
var multiStepPaths = matchingPaths.Where(p => p.Distance == Distance.MultiStep).ToArray();
foreach (var path in multiStepPaths)
{
// Assert that no pieces exist along the from -> to path.
var isPathObstructed = GetPositionsAlongPath(ctx.From, ctx.To, path)
.Any(pos => ctx.BoardState[(int)pos.X, (int)pos.Y] != null);
if (isPathObstructed)
{
return new RulesLifecycleResult(IsError: true, "Piece cannot move through other pieces.");
}
}
var pieceAtTo = ctx.BoardState[(int)ctx.To.X, (int)ctx.To.Y];
if (pieceAtTo?.Owner == this.Owner)
{
return new RulesLifecycleResult(IsError: true, "Cannot capture your own pieces.");
}
return new RulesLifecycleResult(IsError: false);
static IEnumerable<Vector2> GetPositionsAlongPath(Vector2 from, Vector2 to, Path path)
{
var next = from;
while (next != to && next.X >= 0 && next.X < 9 && next.Y >= 0 && next.Y < 9)
{
next += path.NormalizedDirection;
yield return next;
}
}
}
#endregion
}
}

View File

@@ -1,7 +1,4 @@
using System.Text;
using Shogi.Domain.Other;
using Shogi.Domain.YetToBeAssimilatedIntoDDD;
using Shogi.Domain.YetToBeAssimilatedIntoDDD;
namespace Shogi.Domain.ValueObjects;
/// <summary>
@@ -12,6 +9,7 @@ namespace Shogi.Domain.ValueObjects;
public sealed class ShogiBoard
{
private readonly StandardRules rules;
private static readonly Vector2 BoardSize = new Vector2(9, 9);
public ShogiBoard(BoardState initialState)
{
@@ -29,239 +27,273 @@ public sealed class ShogiBoard
/// validate legal vs illegal moves without having to worry about reverting board state.
/// </remarks>
/// <exception cref="InvalidOperationException"></exception>
public void Move(string from, string to, bool isPromotion = false)
public MoveResult Move(string from, string to, bool isPromotion = false)
{
// Validate the move
var rulesState = new Piece?[9, 9];
for (int x = 0; x < 9; x++)
for (int y = 0; y < 9; y++)
var moveResult = IsMoveValid(Notation.FromBoardNotation(from), Notation.FromBoardNotation(to));
if (!moveResult.IsSuccess)
{
rulesState[x, y] = this.BoardState[x, y];
}
var rules = new BoardRules<Piece>(rulesState);
var validationResult = rules.ValidateMove(Notation.FromBoardNotation(from), Notation.FromBoardNotation(to), isPromotion);
if (validationResult.IsError)
{
throw new InvalidOperationException(validationResult.ResultMessage);
return moveResult;
}
// Move is valid, but is it legal?
// Check for correct player's turn.
if (BoardState.WhoseTurn != BoardState[from]!.Owner)
{
throw new InvalidOperationException("Not allowed to move the opponent's pieces.");
return new MoveResult(false, "Not allowed to move the opponent's pieces.");
}
// Simulate the move on a throw -away state and look for "check" and "check-mate".
var simulationState = new BoardState(BoardState);
var moveResult = simulationState.Move(from, to, isPromotion);
if (!moveResult.Success)
// Simulate the move on a throw-away state and look for "check" and "check-mate".
var simState = new BoardState(BoardState);
moveResult = simState.Move(from, to, isPromotion);
if (!moveResult.IsSuccess)
{
throw new InvalidOperationException(moveResult.Reason);
return moveResult;
}
var simulation = new StandardRules(simulationState);
// If already in check, assert the move that resulted in check no longer results in check.
if (BoardState.InCheck == BoardState.WhoseTurn
&& simulation.IsOpposingKingThreatenedByPosition(BoardState.PreviousMove.To))
{
throw new InvalidOperationException("Unable to move because you are still in check.");
}
var kings = simState.State
.Where(kvp => kvp.Value?.WhichPiece == WhichPiece.King)
.Cast<KeyValuePair<string, Piece>>()
.ToArray();
if (simulation.DidPlayerPutThemselfInCheck())
{
throw new InvalidOperationException("Illegal move. This move places you in check.");
}
if (kings.Length != 2) throw new InvalidOperationException("Unexpected scenario: board does not have two kings in play.");
var otherPlayer = BoardState.WhoseTurn == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
_ = BoardState.Move(from, to, isPromotion); // "Rules" should not be doing any data changes. "State" should do that.
if (rules.IsOpponentInCheckAfterMove())
// Look for threats against the kings.
var inCheckResult = simState.State
.Where(kvp => kvp.Value != null)
.Cast<KeyValuePair<string, Piece>>()
.Aggregate(InCheckResult.NobodyInCheck, (inCheckResult, kvp) =>
{
BoardState.InCheck = otherPlayer;
if (rules.IsOpponentInCheckMate())
var newInCheckResult = inCheckResult;
var threatPiece = kvp.Value;
var opposingKingPosition = Notation.FromBoardNotation(kings.Single(king => king.Value.Owner != threatPiece.Owner).Key);
var candidatePositions = threatPiece.GetPathFromStartToEnd(Notation.FromBoardNotation(kvp.Key), opposingKingPosition);
foreach (var position in candidatePositions)
{
BoardState.IsCheckmate = true;
}
// No piece at this position, so pathing is unobstructed. Continue pathing.
if (simState[position] == null) continue;
var pieceAtPosition = simState[position]!;
if (pieceAtPosition.WhichPiece == WhichPiece.King && pieceAtPosition.Owner != threatPiece.Owner)
{
newInCheckResult &= pieceAtPosition.Owner == WhichPlayer.Player1 ? InCheckResult.Player2InCheck : InCheckResult.Player1InCheck;
}
else
{
BoardState.InCheck = null;
break;
}
BoardState.WhoseTurn = otherPlayer;
}
return newInCheckResult;
});
var playerPutThemselfInCheck = BoardState.WhoseTurn == WhichPlayer.Player1
? inCheckResult.HasFlag(InCheckResult.Player1InCheck)
: inCheckResult.HasFlag(InCheckResult.Player2InCheck);
if (playerPutThemselfInCheck)
{
return new MoveResult(false, "This move puts the moving player in check, which is illega.");
}
// Move is legal; mutate the real state.
BoardState.Move(from, to, isPromotion);
var playerPutOpponentInCheck = BoardState.WhoseTurn == WhichPlayer.Player1
? inCheckResult.HasFlag(InCheckResult.Player2InCheck)
: inCheckResult.HasFlag(InCheckResult.Player1InCheck);
if (playerPutOpponentInCheck)
{
BoardState.InCheck = BoardState.WhoseTurn == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
}
// TODO: Look for check-mate.
return new MoveResult(true);
//var simulation = new StandardRules(simState);
//// If already in check, assert the move that resulted in check no longer results in check.
//if (BoardState.InCheck == BoardState.WhoseTurn
// && simulation.IsOpposingKingThreatenedByPosition(BoardState.PreviousMove.To))
//{
// throw new InvalidOperationException("Unable to move because you are still in check.");
//}
//if (simulation.DidPlayerPutThemselfInCheck())
//{
// throw new InvalidOperationException("Illegal move. This move places you in check.");
//}
//var otherPlayer = BoardState.WhoseTurn == WhichPlayer.Player1
// ? WhichPlayer.Player2
// : WhichPlayer.Player1;
//_ = BoardState.Move(from, to, isPromotion); // "Rules" should not be doing any data changes. "State" should do that.
//if (rules.IsOpponentInCheckAfterMove())
//{
// BoardState.InCheck = otherPlayer;
// if (rules.IsOpponentInCheckMate())
// {
// BoardState.IsCheckmate = true;
// }
//}
//else
//{
// BoardState.InCheck = null;
//}
//BoardState.WhoseTurn = otherPlayer;
}
public void Move(WhichPiece pieceInHand, string to)
{
var index = BoardState.ActivePlayerHand.FindIndex(p => p.WhichPiece == pieceInHand);
if (index == -1)
{
throw new InvalidOperationException($"{pieceInHand} does not exist in the hand.");
}
//var index = BoardState.ActivePlayerHand.FindIndex(p => p.WhichPiece == pieceInHand);
//if (index == -1)
//{
// throw new InvalidOperationException($"{pieceInHand} does not exist in the hand.");
//}
if (BoardState[to] != null)
{
throw new InvalidOperationException("Illegal placement of piece from the hand. Destination is not empty.");
}
//if (BoardState[to] != null)
//{
// throw new InvalidOperationException("Illegal placement of piece from the hand. Destination is not empty.");
//}
var toVector = Notation.FromBoardNotation(to);
switch (pieceInHand)
{
case WhichPiece.Knight:
{
// Knight cannot be placed onto the farthest two ranks from the hand.
if (BoardState.WhoseTurn == WhichPlayer.Player1 && toVector.Y > 6
|| BoardState.WhoseTurn == WhichPlayer.Player2 && toVector.Y < 2)
{
throw new InvalidOperationException("Illegal move. Knight has no valid moves after placement.");
}
break;
}
case WhichPiece.Lance:
case WhichPiece.Pawn:
{
// Lance and Pawn cannot be placed onto the farthest rank from the hand.
if (BoardState.WhoseTurn == WhichPlayer.Player1 && toVector.Y == 8
|| BoardState.WhoseTurn == WhichPlayer.Player2 && toVector.Y == 0)
{
throw new InvalidOperationException($"Illegal move. {pieceInHand} has no valid moves after placement.");
}
break;
}
}
//var toVector = Notation.FromBoardNotation(to);
//switch (pieceInHand)
//{
// case WhichPiece.Knight:
// {
// // Knight cannot be placed onto the farthest two ranks from the hand.
// if (BoardState.WhoseTurn == WhichPlayer.Player1 && toVector.Y > 6
// || BoardState.WhoseTurn == WhichPlayer.Player2 && toVector.Y < 2)
// {
// throw new InvalidOperationException("Illegal move. Knight has no valid moves after placement.");
// }
// break;
// }
// case WhichPiece.Lance:
// case WhichPiece.Pawn:
// {
// // Lance and Pawn cannot be placed onto the farthest rank from the hand.
// if (BoardState.WhoseTurn == WhichPlayer.Player1 && toVector.Y == 8
// || BoardState.WhoseTurn == WhichPlayer.Player2 && toVector.Y == 0)
// {
// throw new InvalidOperationException($"Illegal move. {pieceInHand} has no valid moves after placement.");
// }
// break;
// }
//}
var tempBoard = new BoardState(BoardState);
var simulation = new StandardRules(tempBoard);
var moveResult = simulation.Move(pieceInHand, to);
if (!moveResult.Success)
{
throw new InvalidOperationException(moveResult.Reason);
}
//var tempBoard = new BoardState(BoardState);
//var simulation = new StandardRules(tempBoard);
//var moveResult = simulation.Move(pieceInHand, to);
//if (!moveResult.Success)
//{
// throw new InvalidOperationException(moveResult.Reason);
//}
// If already in check, assert the move that resulted in check no longer results in check.
if (BoardState.InCheck == BoardState.WhoseTurn
&& simulation.IsOpposingKingThreatenedByPosition(BoardState.PreviousMove.To))
{
throw new InvalidOperationException("Unable to drop piece becauase you are still in check.");
}
//// If already in check, assert the move that resulted in check no longer results in check.
//if (BoardState.InCheck == BoardState.WhoseTurn
// && simulation.IsOpposingKingThreatenedByPosition(BoardState.PreviousMove.To))
//{
// throw new InvalidOperationException("Unable to drop piece becauase you are still in check.");
//}
if (simulation.DidPlayerPutThemselfInCheck())
{
throw new InvalidOperationException("Illegal move. This move places you in check.");
}
//if (simulation.DidPlayerPutThemselfInCheck())
//{
// throw new InvalidOperationException("Illegal move. This move places you in check.");
//}
// Update the non-simulation board.
var otherPlayer = tempBoard.WhoseTurn == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
_ = rules.Move(pieceInHand, to);
if (rules.IsOpponentInCheckAfterMove())
{
BoardState.InCheck = otherPlayer;
// A pawn, placed from the hand, cannot be the cause of checkmate.
if (rules.IsOpponentInCheckMate() && pieceInHand != WhichPiece.Pawn)
{
BoardState.IsCheckmate = true;
}
}
//// Update the non-simulation board.
//var otherPlayer = tempBoard.WhoseTurn == WhichPlayer.Player1
// ? WhichPlayer.Player2
// : WhichPlayer.Player1;
//_ = rules.Move(pieceInHand, to);
//if (rules.IsOpponentInCheckAfterMove())
//{
// BoardState.InCheck = otherPlayer;
// // A pawn, placed from the hand, cannot be the cause of checkmate.
// if (rules.IsOpponentInCheckMate() && pieceInHand != WhichPiece.Pawn)
// {
// BoardState.IsCheckmate = true;
// }
//}
var kingPosition = otherPlayer == WhichPlayer.Player1
? tempBoard.Player1KingPosition
: tempBoard.Player2KingPosition;
BoardState.WhoseTurn = otherPlayer;
//var kingPosition = otherPlayer == WhichPlayer.Player1
// ? tempBoard.Player1KingPosition
// : tempBoard.Player2KingPosition;
//BoardState.WhoseTurn = otherPlayer;
}
/// <summary>
/// Prints a ASCII representation of the board for debugging board state.
/// The purpose is to ensure a proposed board move is valid with regard to the moved piece's rules.
/// This event does not worry about check or check-mate, or if a move is legal according to all Shogi rules.
/// It asserts that a proposed move is possible and worthy of further validation (check, check-mate, etc).
/// </summary>
/// <returns></returns>
public string ToStringStateAsAscii()
private MoveResult IsMoveValid(Vector2 from, Vector2 to)
{
var builder = new StringBuilder();
builder.Append(" ");
builder.Append("Player 2");
builder.AppendLine();
for (var rank = 8; rank >= 0; rank--)
if (IsWithinBounds(from) && IsWithinBounds(to))
{
// Horizontal line
builder.Append(" - ");
for (var file = 0; file < 8; file++) builder.Append("- - ");
builder.Append("- -");
if (BoardState[to]?.WhichPiece == WhichPiece.King)
{
return new MoveResult(false, "Kings may not be captured.");
}
// Print Rank ruler.
builder.AppendLine();
builder.Append($"{rank + 1} ");
// Print pieces.
builder.Append(" |");
for (var x = 0; x < 9; x++)
{
var piece = BoardState[x, rank];
var piece = BoardState[from];
if (piece == null)
{
builder.Append(" ");
return new MoveResult(false, $"There is no piece at position {from}.");
}
else
var matchingPaths = piece.MoveSet.Where(p => p.NormalizedStep == Vector2.Normalize(to - from));
if (!matchingPaths.Any())
{
builder.AppendFormat("{0}", ToAscii(piece));
}
builder.Append('|');
}
builder.AppendLine();
return new MoveResult(false, "Piece cannot move like that.");
}
// Horizontal line
builder.Append(" - ");
for (var x = 0; x < 8; x++) builder.Append("- - ");
builder.Append("- -");
builder.AppendLine();
builder.Append(" ");
builder.Append("Player 1");
builder.AppendLine();
builder.AppendLine();
// Print File ruler.
builder.Append(" ");
builder.Append(" A B C D E F G H I ");
return builder.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="piece"></param>
/// <returns>
/// A string with three characters.
/// The first character indicates promotion status.
/// The second character indicates piece.
/// The third character indicates ownership.
/// </returns>
private static string ToAscii(Piece piece)
var multiStepPaths = matchingPaths.Where(path => path.Distance == YetToBeAssimilatedIntoDDD.Pathing.Distance.MultiStep).ToArray();
foreach (var path in multiStepPaths)
{
var builder = new StringBuilder();
if (piece.IsPromoted) builder.Append('^');
else builder.Append(' ');
var name = piece.WhichPiece switch
// Assert that no pieces exist along the from -> to path.
var isPathObstructed = GetPositionsAlongPath(from, to, path)
.Any(pos => BoardState[pos] != null);
if (isPathObstructed)
{
WhichPiece.King => "K",
WhichPiece.GoldGeneral => "G",
WhichPiece.SilverGeneral => "S",
WhichPiece.Bishop => "B",
WhichPiece.Rook => "R",
WhichPiece.Knight => "k",
WhichPiece.Lance => "L",
WhichPiece.Pawn => "P",
_ => throw new ArgumentException($"Unknown value for {nameof(WhichPiece)}."),
};
builder.Append(name);
return new MoveResult(false, "Piece cannot move through other pieces.");
}
if (piece.Owner == WhichPlayer.Player2) builder.Append('.');
else builder.Append(' ');
}
return builder.ToString();
var pieceAtTo = BoardState[to];
if (pieceAtTo?.Owner == piece.Owner)
{
return new MoveResult(false, "Cannot capture your own pieces.");
}
}
return new MoveResult(true);
}
private static IEnumerable<Vector2> GetPositionsAlongPath(Vector2 from, Vector2 to, YetToBeAssimilatedIntoDDD.Pathing.Path path)
{
var next = from;
while (next != to && next.X >= 0 && next.X < 9 && next.Y >= 0 && next.Y < 9)
{
next += path.Step;
yield return next;
}
}
private static bool IsWithinBounds(Vector2 position)
{
var isPositive = position - position == Vector2.Zero;
return isPositive && position.X <= BoardSize.X && position.Y <= BoardSize.Y;
}
}

View File

@@ -147,7 +147,7 @@ namespace Shogi.Domain.ValueObjects
var paths = boardState[kingPosition]!.MoveSet;
return paths
.Select(path => path.NormalizedDirection + kingPosition)
.Select(path => path.Step + kingPosition)
// Because the king could be on the edge of the board, where some of its paths do not make sense.
.Where(newPosition => newPosition.IsInsideBoardBoundary())
// Where tile at position is empty, meaning the king could move there.

View File

@@ -5,15 +5,15 @@ public enum WhichPiece
King,
GoldGeneral,
SilverGeneral,
PromotedSilverGeneral,
//PromotedSilverGeneral,
Bishop,
PromotedBishop,
//PromotedBishop,
Rook,
PromotedRook,
//PromotedRook,
Knight,
PromotedKnight,
//PromotedKnight,
Lance,
PromotedLance,
Pawn
PromotedPawn
//PromotedLance,
Pawn,
//PromotedPawn,
}

View File

@@ -1,19 +1,32 @@
using System.Diagnostics;
using static Shogi.Domain.YetToBeAssimilatedIntoDDD.Pathing.Path;
namespace Shogi.Domain.YetToBeAssimilatedIntoDDD.Pathing;
[DebuggerDisplay("{Direction} - {Distance}")]
[DebuggerDisplay("{Step} - {Distance}")]
public record Path
{
public Vector2 NormalizedDirection { get; }
public Vector2 Step { get; }
public Vector2 NormalizedStep => Vector2.Normalize(Step);
public Distance Distance { get; }
public Path(Vector2 direction, Distance distance = Distance.OneStep)
/// <summary>
///
/// </summary>
/// <param name="step">The smallest distance that can occur during a move.</param>
/// <param name="distance"></param>
public Path(Vector2 step, Distance distance = Distance.OneStep)
{
NormalizedDirection = Vector2.Normalize(direction);
Step = step;
this.Distance = distance;
}
public Path Invert() => new(Vector2.Negate(NormalizedDirection), Distance);
public Path Invert() => new(Vector2.Negate(Step), Distance);
//public enum PathingResult
//{
// Obstructed,
// CompletedWithoutObstruction
//}
}
public static class PathExtensions
@@ -28,8 +41,8 @@ public static class PathExtensions
var shortestPath = paths.First();
foreach (var path in paths.Skip(1))
{
var distance = Vector2.Distance(start + path.NormalizedDirection, end); //Normalizing the direction probably broke this.
var shortestDistance = Vector2.Distance(start + shortestPath.NormalizedDirection, end); // And this.
var distance = Vector2.Distance(start + path.Step, end);
var shortestDistance = Vector2.Distance(start + shortestPath.Step, end);
if (distance < shortestDistance)
{
shortestPath = path;

View File

@@ -5,7 +5,6 @@
@implements IDisposable
@inject ShogiApi ShogiApi
@inject PromotePrompt PromotePrompt
@inject GameHubNode hubNode
@inject NavigationManager navigator

View File

@@ -1,6 +1,5 @@
@using Shogi.Contracts.Types;
@using System.Text.Json;
@inject PromotePrompt PromotePrompt;
<article class="game-board">
@if (IsSpectating)
@@ -53,16 +52,6 @@
<span>H</span>
<span>I</span>
</div>
<!-- Promote prompt -->
<div class="promote-prompt" data-visible="@PromotePrompt.IsVisible">
<p>Do you wish to promote?</p>
<div>
<button type="button">Yes</button>
<button type="button">No</button>
<button type="button">Cancel</button>
</div>
</div>
</section>
<!-- Side board -->
@@ -121,13 +110,6 @@
</article>
@code {
static readonly string[] Files = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
/// <summary>

View File

@@ -111,19 +111,3 @@
place-items: center start;
padding: 0.5rem;
}
.promote-prompt {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #444;
padding: 1rem;
box-shadow: 1px 1px 1px #444;
text-align: center;
}
.promote-prompt[data-visible="true"] {
display: block;
}

View File

@@ -2,10 +2,10 @@
@using Shogi.Contracts.Types;
@using System.Text.RegularExpressions;
@using System.Net;
@inject PromotePrompt PromotePrompt;
@inject ShogiApi ShogiApi;
<GameBoardPresentation Session="Session"
<div style="position: relative;">
<GameBoardPresentation Session="Session"
Perspective="Perspective"
OnClickHand="OnClickHand"
OnClickTile="OnClickTile"
@@ -13,6 +13,21 @@
SelectedPieceFromHand="@selectedPieceFromHand"
IsMyTurn="IsMyTurn" />
@if (showPromotePrompt)
{
<!-- Promote prompt -->
<!-- TODO: Add a background div which prevents mouse inputs to the board while this decision is being made. -->
<section class="promote-prompt">
<p>Do you wish to promote?</p>
<div>
<button type="button" @onclick="() => OnClickPromotionChoice(true)">Yes</button>
<button type="button" @onclick="() => OnClickPromotionChoice(false)">No</button>
<button type="button" @onclick="() => showPromotePrompt = false">Cancel</button>
</div>
</section>
}
</div>
@code {
[Parameter, EditorRequired]
public WhichPlayer Perspective { get; set; }
@@ -21,6 +36,8 @@
private bool IsMyTurn => Session?.BoardState.WhoseTurn == Perspective;
private string? selectedBoardPosition;
private WhichPiece? selectedPieceFromHand;
private bool showPromotePrompt;
private string? moveTo;
protected override void OnParametersSet()
{
@@ -75,7 +92,7 @@
{
// Placing a piece from the hand to an empty space.
var success = await ShogiApi.Move(
Session.SessionId.ToString(),
Session.SessionId,
new MovePieceCommand(selectedPieceFromHand.Value, position));
if (!success)
{
@@ -88,18 +105,24 @@
if (selectedBoardPosition != null)
{
Console.WriteLine("pieceAtPosition is null? {0}", pieceAtPosition == null);
if (pieceAtPosition == null || pieceAtPosition?.Owner != Perspective)
{
// Moving to an empty space or capturing an opponent's piece.
if (ShouldPromptForPromotion(position) || ShouldPromptForPromotion(selectedBoardPosition))
{
PromotePrompt.Show(
Session.SessionId.ToString(),
new MovePieceCommand(selectedBoardPosition, position, false));
Console.WriteLine("Prompt!");
moveTo = position;
showPromotePrompt = true;
}
else
{
var success = await ShogiApi.Move(Session.SessionId.ToString(), new MovePieceCommand(selectedBoardPosition, position, false));
Console.WriteLine("OnClick to move to {0}", position);
var success = await ShogiApi.Move(Session.SessionId, new MovePieceCommand(selectedBoardPosition, position, false));
Console.WriteLine("Success? {0}", success);
if (!success)
{
selectedBoardPosition = null;
@@ -125,4 +148,14 @@
StateHasChanged();
}
private Task OnClickPromotionChoice(bool shouldPromote)
{
if (selectedBoardPosition == null && selectedPieceFromHand.HasValue && moveTo != null)
{
return ShogiApi.Move(Session.SessionId, new MovePieceCommand(selectedPieceFromHand.Value, moveTo));
}
throw new InvalidOperationException("Unexpected scenario during OnClickPromotionChoice.");
}
}

View File

@@ -0,0 +1,14 @@
.promote-prompt {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #444;
padding: 1rem;
box-shadow: 1px 1px 1px #444;
text-align: center;
z-index: 101;
background-color: #444;
border: 1px solid black;
}

View File

@@ -1,58 +0,0 @@
using Shogi.Contracts.Api;
using Shogi.UI.Shared;
namespace Shogi.UI.Pages.Play;
public class PromotePrompt
{
private readonly ShogiApi shogiApi;
private string? sessionName;
private MovePieceCommand? command;
public PromotePrompt(ShogiApi shogiApi)
{
this.shogiApi = shogiApi;
this.IsVisible = false;
this.OnClickCancel = this.Hide;
}
public bool IsVisible { get; private set; }
public Action OnClickCancel;
public Func<Task>? OnClickNo;
public Func<Task>? OnClickYes;
public void Show(string sessionName, MovePieceCommand command)
{
this.sessionName = sessionName;
this.command = command;
this.IsVisible = true;
this.OnClickNo = this.Move;
this.OnClickYes = this.MoveAndPromote;
}
public void Hide()
{
this.IsVisible = false;
this.OnClickNo = null;
this.OnClickYes = null;
}
private Task Move()
{
if (this.command != null && this.sessionName != null)
{
this.command.IsPromotion = false;
return this.shogiApi.Move(this.sessionName, this.command);
}
return Task.CompletedTask;
}
private Task MoveAndPromote()
{
if (this.command != null && this.sessionName != null)
{
this.command.IsPromotion = true;
return this.shogiApi.Move(this.sessionName, this.command);
}
return Task.CompletedTask;
}
}

View File

@@ -39,8 +39,7 @@ static void ConfigureDependencies(IServiceCollection services, IConfiguration co
services
.AddTransient<CookieCredentialsMessageHandler>()
.AddTransient<ILocalStorage, LocalStorage>()
.AddSingleton<PromotePrompt>();
.AddTransient<ILocalStorage, LocalStorage>();
// Identity
services

View File

@@ -52,7 +52,7 @@ public class ShogiApi(HttpClient httpClient)
/// <summary>
/// Returns false if the move was not accepted by the server.
/// </summary>
public async Task<bool> Move(string sessionName, MovePieceCommand command)
public async Task<bool> Move(Guid sessionName, MovePieceCommand command)
{
var response = await httpClient.PatchAsync(Relative($"Sessions/{sessionName}/Move"), JsonContent.Create(command));
return response.IsSuccessStatusCode;

View File

@@ -0,0 +1,97 @@
using Shogi.Domain.ValueObjects;
using System;
using System.Text;
namespace UnitTests;
public static class Extensions
{
/// <summary>
/// Prints a ASCII representation of the board for debugging board state.
/// </summary>
/// <returns></returns>
public static string ToStringStateAsAscii(this ShogiBoard board)
{
var boardState = board.BoardState;
var builder = new StringBuilder();
builder.Append(" ");
builder.Append("Player 2");
builder.AppendLine();
for (var rank = 8; rank >= 0; rank--)
{
// Horizontal line
builder.Append(" - ");
for (var file = 0; file < 8; file++) builder.Append("- - ");
builder.Append("- -");
// Print Rank ruler.
builder.AppendLine();
builder.Append($"{rank + 1} ");
// Print pieces.
builder.Append(" |");
for (var x = 0; x < 9; x++)
{
var piece = boardState[x, rank];
if (piece == null)
{
builder.Append(" ");
}
else
{
builder.AppendFormat("{0}", ToAscii(piece));
}
builder.Append('|');
}
builder.AppendLine();
}
// Horizontal line
builder.Append(" - ");
for (var x = 0; x < 8; x++) builder.Append("- - ");
builder.Append("- -");
builder.AppendLine();
builder.Append(" ");
builder.Append("Player 1");
builder.AppendLine();
builder.AppendLine();
// Print File ruler.
builder.Append(" ");
builder.Append(" A B C D E F G H I ");
return builder.ToString();
}
/// <returns>
/// A string with three characters.
/// The first character indicates promotion status.
/// The second character indicates piece.
/// The third character indicates ownership.
/// </returns>
private static string ToAscii(Piece piece)
{
var builder = new StringBuilder();
if (piece.IsPromoted) builder.Append('^');
else builder.Append(' ');
var name = piece.WhichPiece switch
{
WhichPiece.King => "K",
WhichPiece.GoldGeneral => "G",
WhichPiece.SilverGeneral => "S",
WhichPiece.Bishop => "B",
WhichPiece.Rook => "R",
WhichPiece.Knight => "k",
WhichPiece.Lance => "L",
WhichPiece.Pawn => "P",
_ => throw new ArgumentException($"Unknown value for {nameof(WhichPiece)}."),
};
builder.Append(name);
if (piece.Owner == WhichPlayer.Player2) builder.Append('.');
else builder.Append(' ');
return builder.ToString();
}
}

View File

@@ -1,7 +1,7 @@
using System.Numerics;
using Shogi.Domain.YetToBeAssimilatedIntoDDD;
namespace Shogi.Domain.UnitTests
namespace UnitTests
{
public class NotationShould
{

View File

@@ -2,7 +2,7 @@
using Shogi.Domain.YetToBeAssimilatedIntoDDD.Pathing;
using System.Numerics;
namespace Shogi.Domain.UnitTests;
namespace UnitTests;
public class RookShould
{
@@ -13,8 +13,8 @@ public class RookShould
public MoveSet()
{
this.rook1 = new Rook(WhichPlayer.Player1);
this.rook2 = new Rook(WhichPlayer.Player2);
rook1 = new Rook(WhichPlayer.Player1);
rook2 = new Rook(WhichPlayer.Player2);
}
[Fact]
@@ -85,17 +85,17 @@ public class RookShould
public RookShould()
{
this.rookPlayer1 = new Rook(WhichPlayer.Player1);
rookPlayer1 = new Rook(WhichPlayer.Player1);
}
[Fact]
public void Promote()
{
this.rookPlayer1.IsPromoted.Should().BeFalse();
this.rookPlayer1.CanPromote.Should().BeTrue();
this.rookPlayer1.Promote();
this.rookPlayer1.IsPromoted.Should().BeTrue();
this.rookPlayer1.CanPromote.Should().BeFalse();
rookPlayer1.IsPromoted.Should().BeFalse();
rookPlayer1.CanPromote.Should().BeTrue();
rookPlayer1.Promote();
rookPlayer1.IsPromoted.Should().BeTrue();
rookPlayer1.CanPromote.Should().BeFalse();
}
[Fact]

View File

@@ -1,6 +1,6 @@
using Shogi.Domain.ValueObjects;
namespace Shogi.Domain.UnitTests;
namespace UnitTests;
public class ShogiBoardStateShould
{

View File

@@ -2,7 +2,7 @@
using System;
using System.Linq;
namespace Shogi.Domain.UnitTests
namespace UnitTests
{
public class ShogiShould
{