Before changing Piece[,] to Dictionary<string,Piece>

This commit is contained in:
2021-07-26 06:28:56 -05:00
parent f8f779e84c
commit 178cb00253
73 changed files with 1537 additions and 1418 deletions

View File

@@ -1,66 +0,0 @@
using Gameboard.ShogiUI.Rules;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ServiceTypes = Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
namespace Gameboard.ShogiUI.Sockets.Models
{
public class BoardState
{
// TODO: Create a custom 2D array implementation which removes the (x,y) or (y,x) ambiguity.
public Piece?[,] Board { get; }
public IReadOnlyCollection<Piece> Player1Hand { get; }
public IReadOnlyCollection<Piece> Player2Hand { get; }
/// <summary>
/// Move is null in the first BoardState of a Session, before any moves have been made.
/// </summary>
public Move? Move { get; }
public BoardState() : this(new ShogiBoard()) { }
public BoardState(Piece?[,] board, IList<Piece> player1Hand, ICollection<Piece> player2Hand, Move move)
{
Board = board;
Player1Hand = new ReadOnlyCollection<Piece>(player1Hand);
}
public BoardState(ShogiBoard shogi)
{
Board = new Piece[9, 9];
for (var x = 0; x < 9; x++)
for (var y = 0; y < 9; y++)
{
var piece = shogi.Board[x, y];
if (piece != null)
{
Board[x, y] = new Piece(piece);
}
}
Player1Hand = shogi.Hands[WhichPlayer.Player1].Select(_ => new Piece(_)).ToList();
Player2Hand = shogi.Hands[WhichPlayer.Player2].Select(_ => new Piece(_)).ToList();
Move = new Move(shogi.MoveHistory[^1]);
}
public ServiceTypes.BoardState ToServiceModel()
{
var board = new ServiceTypes.Piece[9, 9];
for (var x = 0; x < 9; x++)
for (var y = 0; y < 9; y++)
{
var piece = Board[x, y];
if (piece != null)
{
board[x, y] = piece.ToServiceModel();
}
}
return new ServiceTypes.BoardState
{
Board = board,
Player1Hand = Player1Hand.Select(_ => _.ToServiceModel()).ToList(),
Player2Hand = Player2Hand.Select(_ => _.ToServiceModel()).ToList()
};
}
}
}

View File

@@ -1,41 +0,0 @@
using System;
using System.Text.RegularExpressions;
namespace Gameboard.ShogiUI.Sockets.Models
{
public class Coords
{
private const string BoardNotationRegex = @"(?<file>[A-I])(?<rank>[1-9])";
private const char A = 'A';
public int X { get; }
public int Y { get; }
public Coords(int x, int y)
{
X = x;
Y = y;
}
public string ToBoardNotation()
{
var file = (char)(X + A);
var rank = Y + 1;
return $"{file}{rank}";
}
public static Coords FromBoardNotation(string notation)
{
if (string.IsNullOrEmpty(notation))
{
if (Regex.IsMatch(notation, BoardNotationRegex))
{
var match = Regex.Match(notation, BoardNotationRegex);
char file = match.Groups["file"].Value[0];
int rank = int.Parse(match.Groups["rank"].Value);
return new Coords(file - A, rank);
}
throw new ArgumentException("Board notation not recognized."); // TODO: Move this error handling to the service layer.
}
return new Coords(-1, -1); // Temporarily this is how I tell Gameboard.API that a piece came from the hand.
}
}
}

View File

@@ -1,41 +1,86 @@
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
using System;
using System.Diagnostics;
using System.Numerics;
using System.Text.RegularExpressions;
namespace Gameboard.ShogiUI.Sockets.Models
{
[DebuggerDisplay("{From} - {To}")]
public class Move
{
public Coords? From { get; set; }
public bool IsPromotion { get; set; }
public WhichPiece? PieceFromHand { get; set; }
public Coords To { get; set; }
private static readonly string BoardNotationRegex = @"(?<file>[A-I])(?<rank>[1-9])";
private static readonly char A = 'A';
public Move(Coords from, Coords to, bool isPromotion)
public Vector2? From { get; }
public bool IsPromotion { get; }
public WhichPiece? PieceFromHand { get; }
public Vector2 To { get; }
public Move(Vector2 from, Vector2 to, bool isPromotion = false)
{
From = from;
To = to;
IsPromotion = isPromotion;
}
public Move(WhichPiece pieceFromHand, Coords to)
public Move(WhichPiece pieceFromHand, Vector2 to)
{
PieceFromHand = pieceFromHand;
To = to;
}
/// <summary>
/// Constructor to represent moving a piece on the Board to another position on the Board.
/// </summary>
/// <param name="fromNotation">Position the piece is being moved from.</param>
/// <param name="toNotation">Position the piece is being moved to.</param>
/// <param name="isPromotion">If the moving piece should be promoted.</param>
public Move(string fromNotation, string toNotation, bool isPromotion = false)
{
From = FromBoardNotation(fromNotation);
To = FromBoardNotation(toNotation);
IsPromotion = isPromotion;
}
/// <summary>
/// Constructor to represent moving a piece from the Hand to the Board.
/// </summary>
/// <param name="pieceFromHand">The piece being moved from the Hand to the Board.</param>
/// <param name="toNotation">Position the piece is being moved to.</param>
/// <param name="isPromotion">If the moving piece should be promoted.</param>
public Move(WhichPiece pieceFromHand, string toNotation, bool isPromotion = false)
{
From = null;
PieceFromHand = pieceFromHand;
To = FromBoardNotation(toNotation);
IsPromotion = isPromotion;
}
public ServiceModels.Socket.Types.Move ToServiceModel() => new()
{
From = From?.ToBoardNotation(),
From = From.HasValue ? ToBoardNotation(From.Value) : null,
IsPromotion = IsPromotion,
To = To.ToBoardNotation(),
PieceFromCaptured = PieceFromHand
PieceFromCaptured = PieceFromHand.HasValue ? PieceFromHand : null,
To = ToBoardNotation(To)
};
public Rules.Move ToRulesModel()
private static string ToBoardNotation(Vector2 vector)
{
return PieceFromHand != null
? new Rules.Move((Rules.WhichPiece)PieceFromHand, new Vector2(To.X, To.Y))
: new Rules.Move(new Vector2(From!.X, From.Y), new Vector2(To.X, To.Y), IsPromotion);
var file = (char)(vector.X + A);
var rank = vector.Y + 1;
return $"{file}{rank}";
}
private static Vector2 FromBoardNotation(string notation)
{
if (Regex.IsMatch(notation, BoardNotationRegex))
{
var match = Regex.Match(notation, BoardNotationRegex);
char file = match.Groups["file"].Value[0];
int rank = int.Parse(match.Groups["rank"].Value);
return new Vector2(file - A, rank);
}
throw new ArgumentException($"Board notation not recognized. Notation given: {notation}");
}
}
}

View File

@@ -0,0 +1,95 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Sockets.Models
{
public static class MoveSets
{
public static readonly List<PathFinding.Move> King = new(8)
{
new PathFinding.Move(Direction.Up),
new PathFinding.Move(Direction.Left),
new PathFinding.Move(Direction.Right),
new PathFinding.Move(Direction.Down),
new PathFinding.Move(Direction.UpLeft),
new PathFinding.Move(Direction.UpRight),
new PathFinding.Move(Direction.DownLeft),
new PathFinding.Move(Direction.DownRight)
};
public static readonly List<PathFinding.Move> Bishop = new(4)
{
new PathFinding.Move(Direction.UpLeft, Distance.MultiStep),
new PathFinding.Move(Direction.UpRight, Distance.MultiStep),
new PathFinding.Move(Direction.DownLeft, Distance.MultiStep),
new PathFinding.Move(Direction.DownRight, Distance.MultiStep)
};
public static readonly List<PathFinding.Move> PromotedBishop = new(8)
{
new PathFinding.Move(Direction.Up),
new PathFinding.Move(Direction.Left),
new PathFinding.Move(Direction.Right),
new PathFinding.Move(Direction.Down),
new PathFinding.Move(Direction.UpLeft, Distance.MultiStep),
new PathFinding.Move(Direction.UpRight, Distance.MultiStep),
new PathFinding.Move(Direction.DownLeft, Distance.MultiStep),
new PathFinding.Move(Direction.DownRight, Distance.MultiStep)
};
public static readonly List<PathFinding.Move> GoldGeneral = new(6)
{
new PathFinding.Move(Direction.Up),
new PathFinding.Move(Direction.UpLeft),
new PathFinding.Move(Direction.UpRight),
new PathFinding.Move(Direction.Left),
new PathFinding.Move(Direction.Right),
new PathFinding.Move(Direction.Down)
};
public static readonly List<PathFinding.Move> Knight = new(2)
{
new PathFinding.Move(Direction.KnightLeft),
new PathFinding.Move(Direction.KnightRight)
};
public static readonly List<PathFinding.Move> Lance = new(1)
{
new PathFinding.Move(Direction.Up, Distance.MultiStep),
};
public static readonly List<PathFinding.Move> Pawn = new(1)
{
new PathFinding.Move(Direction.Up)
};
public static readonly List<PathFinding.Move> Rook = new(4)
{
new PathFinding.Move(Direction.Up, Distance.MultiStep),
new PathFinding.Move(Direction.Left, Distance.MultiStep),
new PathFinding.Move(Direction.Right, Distance.MultiStep),
new PathFinding.Move(Direction.Down, Distance.MultiStep)
};
public static readonly List<PathFinding.Move> PromotedRook = new(8)
{
new PathFinding.Move(Direction.Up, Distance.MultiStep),
new PathFinding.Move(Direction.Left, Distance.MultiStep),
new PathFinding.Move(Direction.Right, Distance.MultiStep),
new PathFinding.Move(Direction.Down, Distance.MultiStep),
new PathFinding.Move(Direction.UpLeft),
new PathFinding.Move(Direction.UpRight),
new PathFinding.Move(Direction.DownLeft),
new PathFinding.Move(Direction.DownRight)
};
public static readonly List<PathFinding.Move> SilverGeneral = new(4)
{
new PathFinding.Move(Direction.Up),
new PathFinding.Move(Direction.UpLeft),
new PathFinding.Move(Direction.UpRight),
new PathFinding.Move(Direction.DownLeft),
new PathFinding.Move(Direction.DownRight)
};
}
}

View File

@@ -1,27 +1,59 @@
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
using PathFinding;
using System.Diagnostics;
namespace Gameboard.ShogiUI.Sockets.Models
{
public class Piece
[DebuggerDisplay("{WhichPiece} {Owner}")]
public class Piece : IPlanarElement
{
public bool IsPromoted { get; }
public WhichPlayer Owner { get; }
public WhichPiece WhichPiece { get; }
public WhichPlayer Owner { get; private set; }
public bool IsPromoted { get; private set; }
public bool IsUpsideDown => Owner == WhichPlayer.Player2;
public Piece(bool isPromoted, WhichPlayer owner, WhichPiece whichPiece)
public Piece(WhichPiece piece, WhichPlayer owner, bool isPromoted = false)
{
IsPromoted = isPromoted;
WhichPiece = piece;
Owner = owner;
WhichPiece = whichPiece;
IsPromoted = isPromoted;
}
public Piece(Rules.Pieces.Piece piece)
public bool CanPromote => !IsPromoted
&& WhichPiece != WhichPiece.King
&& WhichPiece != WhichPiece.GoldGeneral;
public void ToggleOwnership()
{
IsPromoted = piece.IsPromoted;
Owner = (WhichPlayer)piece.Owner;
WhichPiece = (WhichPiece)piece.WhichPiece;
Owner = Owner == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
}
public void Promote() => IsPromoted = CanPromote;
public void Demote() => IsPromoted = false;
public void Capture()
{
ToggleOwnership();
Demote();
}
// TODO: There is no reason to make "new" MoveSets every time this property is accessed.
public MoveSet MoveSet => WhichPiece switch
{
WhichPiece.King => new MoveSet(this, MoveSets.King),
WhichPiece.GoldGeneral => new MoveSet(this, MoveSets.GoldGeneral),
WhichPiece.SilverGeneral => new MoveSet(this, IsPromoted ? MoveSets.GoldGeneral : MoveSets.SilverGeneral),
WhichPiece.Bishop => new MoveSet(this, IsPromoted ? MoveSets.PromotedBishop : MoveSets.Bishop),
WhichPiece.Rook => new MoveSet(this, IsPromoted ? MoveSets.PromotedRook : MoveSets.Rook),
WhichPiece.Knight => new MoveSet(this, IsPromoted ? MoveSets.GoldGeneral : MoveSets.Knight),
WhichPiece.Lance => new MoveSet(this, IsPromoted ? MoveSets.GoldGeneral : MoveSets.Lance),
WhichPiece.Pawn => new MoveSet(this, IsPromoted ? MoveSets.GoldGeneral : MoveSets.Pawn),
_ => throw new System.NotImplementedException()
};
public ServiceModels.Socket.Types.Piece ToServiceModel()
{
return new ServiceModels.Socket.Types.Piece

View File

@@ -1,12 +0,0 @@
namespace Gameboard.ShogiUI.Sockets.Models
{
public class Player
{
public string Name { get; }
public Player(string name)
{
Name = name;
}
}
}

View File

@@ -1,22 +1,21 @@
using Gameboard.ShogiUI.Sockets.Extensions;
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
using Newtonsoft.Json;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading.Tasks;
namespace Gameboard.ShogiUI.Sockets.Models
{
public class Session
{
// TODO: Separate subscriptions to the Session from the Session.
[JsonIgnore] public ConcurrentDictionary<string, WebSocket> Subscriptions { get; }
public string Name { get; }
public string Player1 { get; }
public string? Player2 { get; }
public string? Player2 { get; private set; }
public bool IsPrivate { get; }
public Session(string name, bool isPrivate, string player1, string? player2 = null)
public Shogi Shogi { get; }
public Session(string name, bool isPrivate, Shogi shogi, string player1, string? player2 = null)
{
Subscriptions = new ConcurrentDictionary<string, WebSocket>();
@@ -24,48 +23,12 @@ namespace Gameboard.ShogiUI.Sockets.Models
Player1 = player1;
Player2 = player2;
IsPrivate = isPrivate;
Shogi = shogi;
}
public bool Subscribe(string playerName, WebSocket socket) => Subscriptions.TryAdd(playerName, socket);
public Task Broadcast(string message)
public void SetPlayer2(string userName)
{
var tasks = new List<Task>(Subscriptions.Count);
foreach (var kvp in Subscriptions)
{
var socket = kvp.Value;
tasks.Add(socket.SendTextAsync(message));
}
return Task.WhenAll(tasks);
}
public Task SendToPlayer1(string message)
{
if (Subscriptions.TryGetValue(Player1, out var socket))
{
return socket.SendTextAsync(message);
}
return Task.CompletedTask;
}
public Task SendToPlayer2(string message)
{
if (Player2 != null && Subscriptions.TryGetValue(Player2, out var socket))
{
return socket.SendTextAsync(message);
}
return Task.CompletedTask;
}
public Game ToServiceModel()
{
var players = new List<string>(2) { Player1 };
if (!string.IsNullOrWhiteSpace(Player2)) players.Add(Player2);
return new Game
{
GameName = Name,
Players = players.ToArray()
};
Player2 = userName;
}
}
}

View File

@@ -0,0 +1,30 @@
namespace Gameboard.ShogiUI.Sockets.Models
{
/// <summary>
/// A representation of a Session without the board and game-rules.
/// </summary>
public class SessionMetadata
{
public string Name { get; }
public string Player1 { get; }
public string? Player2 { get; }
public bool IsPrivate { get; }
public SessionMetadata(string name, bool isPrivate, string player1, string? player2)
{
Name = name;
IsPrivate = isPrivate;
Player1 = player1;
Player2 = player2;
}
public SessionMetadata(Session sessionModel)
{
Name = sessionModel.Name;
IsPrivate = sessionModel.IsPrivate;
Player1 = sessionModel.Player1;
Player2 = sessionModel.Player2;
}
public ServiceModels.Socket.Types.Game ToServiceModel() => new(Name, Player1, Player2);
}
}

View File

@@ -0,0 +1,410 @@
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
using PathFinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Gameboard.ShogiUI.Sockets.Models
{
/// <summary>
/// Facilitates Shogi board state transitions, cognisant of Shogi rules.
/// The board is always from Player1's perspective.
/// [0,0] is the lower-left position, [8,8] is the higher-right position
/// </summary>
public class Shogi
{
private delegate void MoveSetCallback(Piece piece, Vector2 position);
private readonly PathFinder2D<Piece> pathFinder;
private Shogi? validationBoard;
private Vector2 player1King;
private Vector2 player2King;
public IReadOnlyDictionary<WhichPlayer, List<Piece>> Hands { get; }
public PlanarCollection<Piece> Board { get; } //TODO: Hide this being a getter method
public List<Move> MoveHistory { get; }
public WhichPlayer WhoseTurn => MoveHistory.Count % 2 == 0 ? WhichPlayer.Player1 : WhichPlayer.Player2;
public WhichPlayer? InCheck { get; private set; }
public bool IsCheckmate { get; private set; }
public string Error { get; private set; }
public Shogi()
{
Board = new PlanarCollection<Piece>(9, 9);
MoveHistory = new List<Move>(20);
Hands = new Dictionary<WhichPlayer, List<Piece>> {
{ WhichPlayer.Player1, new List<Piece>()},
{ WhichPlayer.Player2, new List<Piece>()},
};
pathFinder = new PathFinder2D<Piece>(Board);
player1King = new Vector2(4, 8);
player2King = new Vector2(4, 0);
Error = string.Empty;
InitializeBoardState();
}
public Shogi(IList<Move> moves) : this()
{
for (var i = 0; i < moves.Count; i++)
{
if (!Move(moves[i]))
{
// Todo: Add some smarts to know why a move was invalid. In check? Piece not found? etc.
throw new InvalidOperationException($"Unable to construct ShogiBoard with the given move at index {i}. {Error}");
}
}
}
private Shogi(Shogi toCopy)
{
Board = new PlanarCollection<Piece>(9, 9);
for (var x = 0; x < 9; x++)
for (var y = 0; y < 9; y++)
{
var piece = toCopy.Board[y, x];
if (piece != null)
{
Board[y, x] = new Piece(piece.WhichPiece, piece.Owner, piece.IsPromoted);
}
}
pathFinder = new PathFinder2D<Piece>(Board);
MoveHistory = new List<Move>(toCopy.MoveHistory);
Hands = new Dictionary<WhichPlayer, List<Piece>>
{
{ WhichPlayer.Player1, new List<Piece>(toCopy.Hands[WhichPlayer.Player1]) },
{ WhichPlayer.Player2, new List<Piece>(toCopy.Hands[WhichPlayer.Player2]) }
};
player1King = toCopy.player1King;
player2King = toCopy.player2King;
Error = toCopy.Error;
}
public bool Move(Move move)
{
var otherPlayer = WhoseTurn == WhichPlayer.Player1 ? WhichPlayer.Player2 : WhichPlayer.Player1;
var moveSuccess = TryMove(move);
if (!moveSuccess)
{
return false;
}
// Evaluate check
if (EvaluateCheckAfterMove(move, otherPlayer))
{
InCheck = otherPlayer;
IsCheckmate = EvaluateCheckmate();
}
return true;
}
/// <summary>
/// Attempts a given move. Returns false if the move is illegal.
/// </summary>
private bool TryMove(Move move)
{
// Try making the move in a "throw away" board.
if (validationBoard == null)
{
validationBoard = new Shogi(this);
}
var isValid = move.PieceFromHand.HasValue
? validationBoard.PlaceFromHand(move)
: validationBoard.PlaceFromBoard(move);
if (!isValid)
{
// Invalidate the "throw away" board.
validationBoard = null;
return false;
}
// If already in check, assert the move that resulted in check no longer results in check.
if (InCheck == WhoseTurn)
{
if (validationBoard.EvaluateCheckAfterMove(MoveHistory[^1], WhoseTurn))
{
// Sneakily using this.WhoseTurn instead of validationBoard.WhoseTurn;
return false;
}
}
// The move is valid and legal; update board state.
if (move.PieceFromHand.HasValue) PlaceFromHand(move);
else PlaceFromBoard(move);
return true;
}
/// <returns>True if the move was successful.</returns>
private bool PlaceFromHand(Move move)
{
if (move.PieceFromHand.HasValue == false) return false; //Invalid move
var index = Hands[WhoseTurn].FindIndex(p => p.WhichPiece == move.PieceFromHand);
if (index < 0) return false; // Invalid move
if (Board[move.To.Y, move.To.X] != null) return false; // Invalid move; cannot capture while playing from the hand.
var minimumY = 0;
switch (move.PieceFromHand.Value)
{
case WhichPiece.Knight:
// Knight cannot be placed onto the farthest two ranks from the hand.
minimumY = WhoseTurn == WhichPlayer.Player1 ? 6 : 2;
break;
case WhichPiece.Lance:
case WhichPiece.Pawn:
// Lance and Pawn cannot be placed onto the farthest rank from the hand.
minimumY = WhoseTurn == WhichPlayer.Player1 ? 7 : 1;
break;
}
if (WhoseTurn == WhichPlayer.Player1 && move.To.Y < minimumY) return false;
if (WhoseTurn == WhichPlayer.Player2 && move.To.Y > minimumY) return false;
// Mutate the board.
Board[move.To.Y, move.To.X] = Hands[WhoseTurn][index];
Hands[WhoseTurn].RemoveAt(index);
return true;
}
/// <returns>True if the move was successful.</returns>
private bool PlaceFromBoard(Move move)
{
var fromPiece = Board[move.From.Value.Y, move.From.Value.X];
if (fromPiece == null)
{
Error = $"No piece exists at {nameof(move)}.{nameof(move.From)}.";
return false; // Invalid move
}
if (fromPiece.Owner != WhoseTurn)
{
Error = "Not allowed to move the opponents piece";
return false; // Invalid move; cannot move other players pieces.
}
if (IsPathable(move.From.Value, move.To) == false)
{
Error = $"Illegal move for {fromPiece.WhichPiece}. {nameof(move)}.{nameof(move.To)} is not part of the move-set.";
return false; // Invalid move; move not part of move-set.
}
var captured = Board[move.To.Y, move.To.X];
if (captured != null)
{
if (captured.Owner == WhoseTurn) return false; // Invalid move; cannot capture your own piece.
captured.Capture();
Hands[captured.Owner].Add(captured);
}
//Mutate the board.
if (move.IsPromotion)
{
if (WhoseTurn == WhichPlayer.Player1 && (move.To.Y < 3 || move.From.Value.Y < 3))
{
fromPiece.Promote();
}
else if (WhoseTurn == WhichPlayer.Player2 && (move.To.Y > 5 || move.From.Value.Y > 5))
{
fromPiece.Promote();
}
}
Board[move.To.Y, move.To.X] = fromPiece;
Board[move.From.Value.Y, move.From.Value.X] = null;
if (fromPiece.WhichPiece == WhichPiece.King)
{
if (fromPiece.Owner == WhichPlayer.Player1)
{
player1King.X = move.To.X;
player1King.Y = move.To.Y;
}
else if (fromPiece.Owner == WhichPlayer.Player2)
{
player2King.X = move.To.X;
player2King.Y = move.To.Y;
}
}
MoveHistory.Add(move);
return true;
}
private bool IsPathable(Vector2 from, Vector2 to)
{
var piece = Board[from.Y, from.X];
if (piece == null) return false;
var isObstructed = false;
var isPathable = pathFinder.PathTo(from, to, (other, position) =>
{
if (other.Owner == piece.Owner) isObstructed = true;
});
return !isObstructed && isPathable;
}
#region Rules Validation
private bool EvaluateCheckAfterMove(Move move, WhichPlayer whichPlayer)
{
var isCheck = false;
var kingPosition = whichPlayer == WhichPlayer.Player1 ? player1King : player2King;
// Check if the move put the king in check.
if (pathFinder.PathTo(move.To, kingPosition)) return true;
// Get line equation from king through the now-unoccupied location.
var direction = Vector2.Subtract(kingPosition, move.From.Value);
var slope = Math.Abs(direction.Y / direction.X);
// If absolute slope is 45°, look for a bishop along the line.
// If absolute slope is 0° or 90°, look for a rook along the line.
// if absolute slope is 0°, look for lance along the line.
if (float.IsInfinity(slope))
{
// if slope of the move is also infinity...can skip this?
pathFinder.LinePathTo(kingPosition, direction, (piece, position) =>
{
if (piece.Owner != whichPlayer)
{
switch (piece.WhichPiece)
{
case WhichPiece.Rook:
isCheck = true;
break;
case WhichPiece.Lance:
if (!piece.IsPromoted) isCheck = true;
break;
}
}
});
}
else if (slope == 1)
{
pathFinder.LinePathTo(kingPosition, direction, (piece, position) =>
{
if (piece.Owner != whichPlayer && piece.WhichPiece == WhichPiece.Bishop)
{
isCheck = true;
}
});
}
else if (slope == 0)
{
pathFinder.LinePathTo(kingPosition, direction, (piece, position) =>
{
if (piece.Owner != whichPlayer && piece.WhichPiece == WhichPiece.Rook)
{
isCheck = true;
}
});
}
return isCheck;
}
private bool EvaluateCheckmate()
{
if (!InCheck.HasValue) return false;
// Assume true and try to disprove.
var isCheckmate = true;
Board.ForEachNotNull((piece, x, y) => // For each piece...
{
// Short circuit
if (!isCheckmate) return;
var from = new Vector2(x, y);
if (piece.Owner == InCheck) // ...owned by the player in check...
{
// ...evaluate if any move gets the player out of check.
pathFinder.PathEvery(from, (other, position) =>
{
if (validationBoard == null) validationBoard = new Shogi(this);
var moveToTry = new Move(from, position);
var moveSuccess = validationBoard.TryMove(moveToTry);
if (moveSuccess)
{
validationBoard = null;
if (!EvaluateCheckAfterMove(moveToTry, InCheck.Value))
{
isCheckmate = false;
}
}
});
}
});
return isCheckmate;
}
#endregion
#region Initialize
private void ResetEmptyRows()
{
for (int y = 3; y < 6; y++)
for (int x = 0; x < 9; x++)
Board[y, x] = null;
}
private void ResetFrontRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 6 : 2;
for (int x = 0; x < 9; x++) Board[y, x] = new Piece(WhichPiece.Pawn, player);
}
private void ResetMiddleRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 7 : 1;
Board[y, 0] = null;
for (int x = 2; x < 7; x++) Board[y, x] = null;
Board[y, 8] = null;
if (player == WhichPlayer.Player1)
{
Board[y, 1] = new Piece(WhichPiece.Bishop, player);
Board[y, 7] = new Piece(WhichPiece.Rook, player);
}
else
{
Board[y, 1] = new Piece(WhichPiece.Rook, player);
Board[y, 7] = new Piece(WhichPiece.Bishop, player);
}
}
private void ResetRearRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 8 : 0;
Board[y, 0] = new Piece(WhichPiece.Lance, player);
Board[y, 1] = new Piece(WhichPiece.Knight, player);
Board[y, 2] = new Piece(WhichPiece.SilverGeneral, player);
Board[y, 3] = new Piece(WhichPiece.GoldGeneral, player);
Board[y, 4] = new Piece(WhichPiece.King, player);
Board[y, 5] = new Piece(WhichPiece.GoldGeneral, player);
Board[y, 6] = new Piece(WhichPiece.SilverGeneral, player);
Board[y, 7] = new Piece(WhichPiece.Knight, player);
Board[y, 8] = new Piece(WhichPiece.Lance, player);
}
private void InitializeBoardState()
{
ResetRearRow(WhichPlayer.Player2);
ResetMiddleRow(WhichPlayer.Player2);
ResetFrontRow(WhichPlayer.Player2);
ResetEmptyRows();
ResetFrontRow(WhichPlayer.Player1);
ResetMiddleRow(WhichPlayer.Player1);
ResetRearRow(WhichPlayer.Player1);
}
#endregion
public BoardState ToServiceModel()
{
var board = new ServiceModels.Socket.Types.Piece[9, 9];
for (var x = 0; x < 9; x++)
for (var y = 0; y < 9; y++)
{
var piece = Board[y, x];
if (piece != null)
{
board[y, x] = piece.ToServiceModel();
}
}
return new BoardState
{
Board = board,
PlayerInCheck = InCheck,
WhoseTurn = WhoseTurn,
Player1Hand = Hands[WhichPlayer.Player1].Select(_ => _.ToServiceModel()).ToList(),
Player2Hand = Hands[WhichPlayer.Player2].Select(_ => _.ToServiceModel()).ToList()
};
}
}
}