checkpoint

This commit is contained in:
2021-02-23 18:03:23 -06:00
parent 8d79c75616
commit f644795cd3
38 changed files with 1451 additions and 177 deletions

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gameboard.ShogiUI.BoardState
{
public class Array2D<T> : IEnumerable
{
private readonly T[] array;
private readonly int width;
public Array2D(int width, int height)
{
this.width = width;
array = new T[width * height];
}
public T this[int x, int y]
{
get => array[y * width + x];
set => array[y * width + x] = value;
}
IEnumerator IEnumerable.GetEnumerator() => array.GetEnumerator();
}
}

View File

@@ -0,0 +1,62 @@
using System.Diagnostics;
namespace Gameboard.ShogiUI.BoardState
{
/// <summary>
/// Provides normalized BoardVectors relative to player.
/// "Up" for player 1 is "Down" for player 2; that sort of thing.
/// </summary>
public class Direction
{
private static readonly BoardVector PositiveX = new BoardVector(1, 0);
private static readonly BoardVector NegativeX = new BoardVector(-1, 0);
private static readonly BoardVector PositiveY = new BoardVector(0, 1);
private static readonly BoardVector NegativeY = new BoardVector(0, -1);
private static readonly BoardVector PositiveYX = new BoardVector(1, 1);
private static readonly BoardVector NegativeYX = new BoardVector(-1, -1);
private static readonly BoardVector NegativeYPositiveX = new BoardVector(1, -1);
private static readonly BoardVector PositiveYNegativeX = new BoardVector(-1, 1);
private readonly WhichPlayer whichPlayer;
public Direction(WhichPlayer whichPlayer)
{
this.whichPlayer = whichPlayer;
}
public BoardVector Up => whichPlayer == WhichPlayer.Player1 ? PositiveY : NegativeY;
public BoardVector Down => whichPlayer == WhichPlayer.Player1 ? NegativeY : PositiveY;
public BoardVector Left => whichPlayer == WhichPlayer.Player1 ? NegativeX : PositiveX;
public BoardVector Right => whichPlayer == WhichPlayer.Player1 ? PositiveX : NegativeX;
public BoardVector UpLeft => whichPlayer == WhichPlayer.Player1 ? PositiveYNegativeX : NegativeYPositiveX;
public BoardVector UpRight => whichPlayer == WhichPlayer.Player1 ? PositiveYX : NegativeYX;
public BoardVector DownLeft => whichPlayer == WhichPlayer.Player1 ? NegativeYX : PositiveYX;
public BoardVector DownRight => whichPlayer == WhichPlayer.Player1 ? NegativeYPositiveX : PositiveYNegativeX;
public BoardVector KnightLeft => whichPlayer == WhichPlayer.Player1 ? new BoardVector(-1, 2) : new BoardVector(1, -2);
public BoardVector KnightRight => whichPlayer == WhichPlayer.Player1 ? new BoardVector(1, 2) : new BoardVector(-1, -2);
}
[DebuggerDisplay("[{X}, {Y}]")]
public class BoardVector
{
public int X { get; set; }
public int Y { get; set; }
public bool IsValidBoardPosition => X > -1 && X < 9 && Y > -1 && Y < 9;
public bool IsHand => X < 0 && Y < 0; // TODO: Find a better way to distinguish positions vs hand.
public BoardVector(int x, int y)
{
X = x;
Y = y;
}
public BoardVector Add(BoardVector other) => new BoardVector(X + other.X, Y + other.Y);
public override bool Equals(object obj) => (obj is BoardVector other) && other.X == X && other.Y == Y;
public override int GetHashCode()
{
// [0,3] should hash different than [3,0]
return X.GetHashCode() * 3 + Y.GetHashCode() * 5;
}
public static bool operator ==(BoardVector a, BoardVector b) => a.Equals(b);
public static bool operator !=(BoardVector a, BoardVector b) => !a.Equals(b);
}
}

View File

@@ -0,0 +1,19 @@
using System;
namespace Gameboard.ShogiUI.BoardState
{
public static class Extensions
{
public static void ForEachNotNull(this Piece[,] array, Action<Piece, int, int> action)
{
for (var x = 0; x < array.GetLength(0); x++)
for (var y = 0; y < array.GetLength(1); y++)
{
var piece = array[x, y];
if (piece != null)
{
action(piece, x, y);
}
}
}
}
}

View File

@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,10 @@
namespace Gameboard.ShogiUI.BoardState
{
public class Move
{
public WhichPiece? PieceFromCaptured { get; set; }
public BoardVector From { get; set; }
public BoardVector To { get; set; }
public bool IsPromotion { get; set; }
}
}

View File

@@ -0,0 +1,53 @@
using System.Diagnostics;
namespace Gameboard.ShogiUI.BoardState
{
[DebuggerDisplay("{WhichPiece} {Owner}")]
public class Piece
{
public WhichPiece WhichPiece { get; }
public WhichPlayer Owner { get; private set; }
public bool IsPromoted { get; private set; }
public Piece(WhichPiece piece, WhichPlayer owner)
{
WhichPiece = piece;
Owner = owner;
IsPromoted = false;
}
public bool CanPromote => !IsPromoted
&& WhichPiece != WhichPiece.King
&& WhichPiece != WhichPiece.GoldenGeneral;
public string ShortName => WhichPiece switch
{
WhichPiece.King => " K ",
WhichPiece.GoldenGeneral => " G ",
WhichPiece.SilverGeneral => IsPromoted ? "^S^" : " S ",
WhichPiece.Bishop => IsPromoted ? "^B^" : " B ",
WhichPiece.Rook => IsPromoted ? "^R^" : " R ",
WhichPiece.Knight => IsPromoted ? "^k^" : " k ",
WhichPiece.Lance => IsPromoted ? "^L^" : " L ",
WhichPiece.Pawn => IsPromoted ? "^P^" : " P ",
_ => " ? ",
};
public void ToggleOwnership()
{
Owner = Owner == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
}
public void Promote() => IsPromoted = true;
public void Demote() => IsPromoted = false;
public void Capture()
{
ToggleOwnership();
Demote();
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
namespace Gameboard.ShogiUI.BoardState
{
public class Position
{
private int x;
private int y;
public int X
{
get => x;
set {
if (value > 8 || value < 0) throw new ArgumentOutOfRangeException();
x = value;
}
}
public int Y
{
get => y;
set
{
if (value > 8 || value < 0) throw new ArgumentOutOfRangeException();
y = value;
}
}
public Position(int x, int y)
{
X = x;
Y = y;
}
}
}

View File

@@ -0,0 +1,522 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Gameboard.ShogiUI.BoardState
{
/// <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 ShogiBoard
{
private delegate void MoveSetCallback(Piece piece, BoardVector position);
private ShogiBoard validationBoard;
public IReadOnlyDictionary<WhichPlayer, List<Piece>> Hands { get; }
public Piece[,] Board { get; }
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 ShogiBoard()
{
Board = new Piece[9, 9];
MoveHistory = new List<Move>(20);
Hands = new Dictionary<WhichPlayer, List<Piece>> {
{ WhichPlayer.Player1, new List<Piece>()},
{ WhichPlayer.Player2, new List<Piece>()},
};
InitializeBoardState();
}
public ShogiBoard(IList<Move> moves) : this()
{
for (var i = 0; i < moves.Count; i++)
{
if (!TryMove(moves[i]))
{
throw new InvalidOperationException($"Unable to construct ShogiBoard with the given move at index {i}.");
}
}
}
/// <summary>
/// Attempts a given move. Returns false if the move is illegal.
/// </summary>
public bool TryMove(Move move)
{
// Try making the move in a "throw away" board.
if (validationBoard == null)
{
validationBoard = new ShogiBoard(MoveHistory);
}
var isValid = move.PieceFromCaptured.HasValue
? validationBoard.PlaceFromHand(move)
: validationBoard.PlaceFromBoard(move);
if (!isValid)
{
// Invalidate the "throw away" board.
validationBoard = null;
return false;
}
// Assert that this move does not put the moving player in check.
if (validationBoard.EvaluateCheck(WhoseTurn)) return false;
var otherPlayer = WhoseTurn == WhichPlayer.Player1 ? WhichPlayer.Player2 : WhichPlayer.Player1;
// The move is valid and legal; update board state.
if (move.PieceFromCaptured.HasValue) PlaceFromHand(move);
else PlaceFromBoard(move);
// Evaluate check
InCheck = EvaluateCheck(otherPlayer) ? otherPlayer : null;
if (InCheck.HasValue)
{
//IsCheckmate = EvaluateCheckmate();
}
return true;
}
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...
{
if (!isCheckmate) return; // Short circuit
var from = new BoardVector(x, y);
if (piece.Owner == InCheck) // Owned by the player in check...
{
var positionsToCheck = new List<BoardVector>(10);
IterateMoveSet(from, (innerPiece, position) =>
{
if (innerPiece?.Owner != InCheck) positionsToCheck.Add(position); // Find possible moves...
});
// And evaluate if any move gets the player out of check.
foreach (var position in positionsToCheck)
{
var moveSuccess = validationBoard.TryMove(new Move { From = from, To = position });
if (moveSuccess)
{
Console.WriteLine($"Not check mate");
isCheckmate &= validationBoard.EvaluateCheck(InCheck.Value);
validationBoard = null;
}
}
}
});
return isCheckmate;
}
/// <returns>True if the move was successful.</returns>
private bool PlaceFromHand(Move move)
{
if (move.PieceFromCaptured.HasValue == false) return false; //Invalid move
var index = Hands[WhoseTurn].FindIndex(p => p.WhichPiece == move.PieceFromCaptured);
if (index < 0) return false; // Invalid move
if (Board[move.To.X, move.To.Y] != null) return false; // Invalid move; cannot capture while playing from the hand.
var minimumY = 0;
switch (move.PieceFromCaptured.Value)
{
case WhichPiece.Knight:
// Knight cannot be placed onto the farthest two ranks from the hand.
minimumY = WhoseTurn == WhichPlayer.Player1 ? 2 : 6;
break;
case WhichPiece.Lance:
case WhichPiece.Pawn:
// Lance and Pawn cannot be placed onto the farthest rank from the hand.
minimumY = WhoseTurn == WhichPlayer.Player1 ? 1 : 7;
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.X, move.To.Y] = 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.X, move.From.Y];
if (fromPiece == null) return false; // Invalid move
if (fromPiece.Owner != WhoseTurn) return false; // Invalid move; cannot move other players pieces.
if (ValidateMoveAgainstMoveSet(move) == false) return false; // Invalid move; move not part of move-set.
var captured = Board[move.To.X, move.To.Y];
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 > 5 || move.From.Y > 5))
{
fromPiece.Promote();
}
else if (WhoseTurn == WhichPlayer.Player2 && (move.To.Y < 3 || move.From.Y < 3))
{
fromPiece.Promote();
}
}
Board[move.To.X, move.To.Y] = fromPiece;
Board[move.From.X, move.From.Y] = null;
MoveHistory.Add(move);
return true;
}
public void PrintStateAsAscii()
{
var builder = new StringBuilder();
builder.Append(" Player 2");
builder.AppendLine();
for (var y = 8; y > -1; y--)
{
builder.Append("- ");
for (var x = 0; x < 8; x++) builder.Append("- - ");
builder.Append("- -");
builder.AppendLine();
builder.Append('|');
for (var x = 0; x < 9; x++)
{
var piece = Board[x, y];
if (piece == null)
{
builder.Append(" ");
}
else
{
builder.AppendFormat("{0}", piece.ShortName);
}
builder.Append('|');
}
builder.AppendLine();
}
builder.Append("- ");
for (var x = 0; x < 8; x++) builder.Append("- - ");
builder.Append("- -");
builder.AppendLine();
builder.Append(" Player 1");
Console.WriteLine(builder.ToString());
}
#region Rules Validation
/// <summary>
/// Evaluate if a player is in check given the current board state.
/// </summary>
private bool EvaluateCheck(WhichPlayer whichPlayer)
{
var inCheck = false;
// Iterate every board piece...
Board.ForEachNotNull((piece, x, y) =>
{
// ...that belongs to the opponent...
if (piece.Owner != whichPlayer)
{
IterateMoveSet(new BoardVector(x, y), (threatenedPiece, position) =>
{
// ...and threatens the player's king.
inCheck |=
threatenedPiece?.WhichPiece == WhichPiece.King
&& threatenedPiece?.Owner == whichPlayer;
});
}
});
return inCheck;
}
private bool EvaluateCheck2(WhichPlayer whichPlayer)
{
var inCheck = false;
MoveSetCallback checkKingThreat = (piece, position) =>
{
inCheck |=
piece?.WhichPiece == WhichPiece.King
&& piece?.Owner == whichPlayer;
};
// Find interesting pieces
var longRangePiecePositions = new List<BoardVector>(8);
Board.ForEachNotNull((piece, x, y) =>
{
if (piece.Owner != whichPlayer)
{
switch (piece.WhichPiece)
{
case WhichPiece.Bishop:
case WhichPiece.Rook:
longRangePiecePositions.Add(new BoardVector(x, y));
break;
case WhichPiece.Lance:
if (!piece.IsPromoted) longRangePiecePositions.Add(new BoardVector(x, y));
break;
}
}
});
foreach(var position in longRangePiecePositions)
{
IterateMoveSet(position, checkKingThreat);
}
return inCheck;
}
private bool ValidateMoveAgainstMoveSet(Move move)
{
var isValid = false;
IterateMoveSet(move.From, (piece, position) =>
{
if (piece?.Owner != WhoseTurn && position == move.To)
{
isValid = true;
}
});
return isValid;
}
/// <summary>
/// Iterate through the possible moves of a piece at a given position.
/// </summary>
private void IterateMoveSet(BoardVector from, MoveSetCallback callback)
{
// TODO: Make these are of the move To, so only possible moves towards the move To are iterated.
// Maybe separate functions? Sometimes I need to iterate the whole move-set, sometimes I need to iterate only the move-set towards the move To.
var piece = Board[from.X, from.Y];
switch (piece.WhichPiece)
{
case WhichPiece.King:
IterateKingMoveSet(from, callback);
break;
case WhichPiece.GoldenGeneral:
IterateGoldenGeneralMoveSet(from, callback);
break;
case WhichPiece.SilverGeneral:
IterateSilverGeneralMoveSet(from, callback);
break;
case WhichPiece.Bishop:
IterateBishopMoveSet(from, callback);
break;
case WhichPiece.Rook:
IterateRookMoveSet(from, callback);
break;
case WhichPiece.Knight:
IterateKnightMoveSet(from, callback);
break;
case WhichPiece.Lance:
IterateLanceMoveSet(from, callback);
break;
case WhichPiece.Pawn:
IteratePawnMoveSet(from, callback);
break;
}
}
private void IterateKingMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
var direction = new Direction(piece.Owner);
BoardStep(from, direction.Up, callback);
BoardStep(from, direction.UpLeft, callback);
BoardStep(from, direction.UpRight, callback);
BoardStep(from, direction.Down, callback);
BoardStep(from, direction.DownLeft, callback);
BoardStep(from, direction.DownRight, callback);
BoardStep(from, direction.Left, callback);
BoardStep(from, direction.Right, callback);
}
private void IterateGoldenGeneralMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
var direction = new Direction(piece.Owner);
BoardStep(from, direction.Up, callback);
BoardStep(from, direction.UpLeft, callback);
BoardStep(from, direction.UpRight, callback);
BoardStep(from, direction.Down, callback);
BoardStep(from, direction.Left, callback);
BoardStep(from, direction.Right, callback);
}
private void IterateSilverGeneralMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
var direction = new Direction(piece.Owner);
if (piece.IsPromoted)
{
IterateGoldenGeneralMoveSet(from, callback);
}
else
{
BoardStep(from, direction.Up, callback);
BoardStep(from, direction.UpLeft, callback);
BoardStep(from, direction.UpRight, callback);
BoardStep(from, direction.DownLeft, callback);
BoardStep(from, direction.DownRight, callback);
}
}
private void IterateBishopMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
var direction = new Direction(piece.Owner);
BoardWalk(from, direction.UpLeft, callback);
BoardWalk(from, direction.UpRight, callback);
BoardWalk(from, direction.DownLeft, callback);
BoardWalk(from, direction.DownRight, callback);
if (piece.IsPromoted)
{
BoardStep(from, direction.Up, callback);
BoardStep(from, direction.Left, callback);
BoardStep(from, direction.Right, callback);
BoardStep(from, direction.Down, callback);
}
}
private void IterateRookMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
var direction = new Direction(piece.Owner);
BoardWalk(from, direction.Up, callback);
BoardWalk(from, direction.Left, callback);
BoardWalk(from, direction.Right, callback);
BoardWalk(from, direction.Down, callback);
if (piece.IsPromoted)
{
BoardStep(from, direction.UpLeft, callback);
BoardStep(from, direction.UpRight, callback);
BoardStep(from, direction.DownLeft, callback);
BoardStep(from, direction.DownRight, callback);
}
}
private void IterateKnightMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
if (piece.IsPromoted)
{
IterateGoldenGeneralMoveSet(from, callback);
}
else
{
var direction = new Direction(piece.Owner);
BoardStep(from, direction.KnightLeft, callback);
BoardStep(from, direction.KnightRight, callback);
}
}
private void IterateLanceMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
if (piece.IsPromoted)
{
IterateGoldenGeneralMoveSet(from, callback);
}
else
{
var direction = new Direction(piece.Owner);
BoardWalk(from, direction.Up, callback);
}
}
private void IteratePawnMoveSet(BoardVector from, MoveSetCallback callback)
{
var piece = Board[from.X, from.Y];
if (piece?.WhichPiece == WhichPiece.Pawn)
{
if (piece.IsPromoted)
{
IterateGoldenGeneralMoveSet(from, callback);
}
else
{
var direction = new Direction(piece.Owner);
BoardStep(from, direction.Up, callback);
}
}
}
/// <summary>
/// Useful for iterating the board for pieces that move many spaces.
/// </summary>
/// <param name="callback">A function that returns true if walking should continue.</param>
private void BoardWalk(BoardVector from, BoardVector direction, MoveSetCallback callback)
{
var foundAnotherPiece = false;
var to = from.Add(direction);
while (to.IsValidBoardPosition && !foundAnotherPiece)
{
var piece = Board[to.X, to.Y];
callback(piece, to);
to = to.Add(direction);
foundAnotherPiece = piece != null;
}
}
/// <summary>
/// Useful for iterating the board for pieces that move only one space.
/// </summary>
private void BoardStep(BoardVector from, BoardVector direction, MoveSetCallback callback)
{
var to = from.Add(direction);
if (to.IsValidBoardPosition)
{
callback(Board[to.X, to.Y], to);
}
}
#endregion
#region Initialize
private void ResetEmptyRows()
{
for (int y = 3; y < 6; y++)
for (int x = 0; x < 9; x++)
Board[x, y] = null;
}
private void ResetFrontRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 2 : 6;
for (int x = 0; x < 9; x++) Board[x, y] = new Piece(WhichPiece.Pawn, player);
}
private void ResetMiddleRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 1 : 7;
Board[0, y] = null;
for (int x = 2; x < 7; x++) Board[x, y] = null;
Board[8, y] = null;
if (player == WhichPlayer.Player1)
{
Board[1, y] = new Piece(WhichPiece.Bishop, player);
Board[7, y] = new Piece(WhichPiece.Rook, player);
}
else
{
Board[1, y] = new Piece(WhichPiece.Rook, player);
Board[7, y] = new Piece(WhichPiece.Bishop, player);
}
}
private void ResetRearRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 0 : 8;
Board[0, y] = new Piece(WhichPiece.Lance, player);
Board[1, y] = new Piece(WhichPiece.Knight, player);
Board[2, y] = new Piece(WhichPiece.SilverGeneral, player);
Board[3, y] = new Piece(WhichPiece.GoldenGeneral, player);
Board[4, y] = new Piece(WhichPiece.King, player);
Board[5, y] = new Piece(WhichPiece.GoldenGeneral, player);
Board[6, y] = new Piece(WhichPiece.SilverGeneral, player);
Board[7, y] = new Piece(WhichPiece.Knight, player);
Board[8, y] = new Piece(WhichPiece.Lance, player);
}
private void InitializeBoardState()
{
ResetRearRow(WhichPlayer.Player1);
ResetMiddleRow(WhichPlayer.Player1);
ResetFrontRow(WhichPlayer.Player1);
ResetEmptyRows();
ResetFrontRow(WhichPlayer.Player2);
ResetMiddleRow(WhichPlayer.Player2);
ResetRearRow(WhichPlayer.Player2);
}
#endregion
}
}

View File

@@ -0,0 +1,14 @@
namespace Gameboard.ShogiUI.BoardState
{
public enum WhichPiece
{
King,
GoldenGeneral,
SilverGeneral,
Bishop,
Rook,
Knight,
Lance,
Pawn
}
}

View File

@@ -0,0 +1,8 @@
namespace Gameboard.ShogiUI.BoardState
{
public enum WhichPlayer
{
Player1,
Player2
}
}