before deleting Rules

This commit is contained in:
2021-05-08 10:26:04 -05:00
parent 05a9c71499
commit f8f779e84c
80 changed files with 1109 additions and 832 deletions

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>5</AnalysisLevel>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\PathFinding\PathFinding.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,27 @@
using System.Diagnostics;
using System.Numerics;
namespace Gameboard.ShogiUI.Rules
{
[DebuggerDisplay("{From} - {To}")]
public class Move
{
public WhichPiece? PieceFromHand { get; }
public Vector2? From { get; }
public Vector2 To { get; }
public bool IsPromotion { get; }
public Move(Vector2 from, Vector2 to, bool isPromotion)
{
From = from;
To = to;
IsPromotion = isPromotion;
}
public Move(WhichPiece pieceFromHand, Vector2 to)
{
PieceFromHand = pieceFromHand;
To = to;
}
}
}

View File

@@ -0,0 +1,39 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class Bishop : Piece
{
private static readonly List<PathFinding.Move> Moves = 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)
};
private static readonly List<PathFinding.Move> PromotedMoves = 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 Bishop(WhichPlayer owner) : base(WhichPiece.Bishop, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, PromotedMoves);
}
public override Piece DeepClone()
{
var clone = new Bishop(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,30 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class GoldenGeneral : Piece
{
public static readonly List<PathFinding.Move> Moves = 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 GoldenGeneral(WhichPlayer owner) : base(WhichPiece.GoldGeneral, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, Moves);
}
public override Piece DeepClone()
{
var clone = new GoldenGeneral(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,32 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class King : Piece
{
private static readonly List<PathFinding.Move> Moves = 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 King(WhichPlayer owner) : base(WhichPiece.King, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, Moves);
}
public override Piece DeepClone()
{
var clone = new King(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,27 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class Knight : Piece
{
private static readonly List<PathFinding.Move> Moves = new(2)
{
new PathFinding.Move(Direction.KnightLeft),
new PathFinding.Move(Direction.KnightRight)
};
public Knight(WhichPlayer owner) : base(WhichPiece.Knight, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, GoldenGeneral.Moves);
}
public override Piece DeepClone()
{
var clone = new Knight(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,26 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class Lance : Piece
{
private static readonly List<PathFinding.Move> Moves = new(1)
{
new PathFinding.Move(Direction.Up, Distance.MultiStep),
};
public Lance(WhichPlayer owner) : base(WhichPiece.Lance, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, GoldenGeneral.Moves);
}
public override Piece DeepClone()
{
var clone = new Lance(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,26 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class Pawn : Piece
{
private static readonly List<PathFinding.Move> Moves = new(1)
{
new PathFinding.Move(Direction.Up)
};
public Pawn(WhichPlayer owner) : base(WhichPiece.Pawn, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, GoldenGeneral.Moves);
}
public override Piece DeepClone()
{
var clone = new Pawn(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,47 @@
using PathFinding;
using System.Diagnostics;
namespace Gameboard.ShogiUI.Rules.Pieces
{
[DebuggerDisplay("{WhichPiece} {Owner}")]
public abstract class Piece : IPlanarElement
{
protected MoveSet promotedMoveSet;
protected MoveSet moveSet;
public MoveSet MoveSet => IsPromoted ? promotedMoveSet : moveSet;
public abstract Piece DeepClone();
public WhichPiece WhichPiece { get; }
public WhichPlayer Owner { get; private set; }
public bool IsPromoted { get; private set; }
public bool IsUpsideDown => Owner == WhichPlayer.Player2;
public Piece(WhichPiece piece, WhichPlayer owner)
{
WhichPiece = piece;
Owner = owner;
IsPromoted = false;
}
public bool CanPromote => !IsPromoted
&& WhichPiece != WhichPiece.King
&& WhichPiece != WhichPiece.GoldGeneral;
public void ToggleOwnership()
{
Owner = Owner == WhichPlayer.Player1
? WhichPlayer.Player2
: WhichPlayer.Player1;
}
public void Promote() => IsPromoted = CanPromote;
public void Demote() => IsPromoted = false;
public void Capture()
{
ToggleOwnership();
Demote();
}
}
}

View File

@@ -0,0 +1,39 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class Rook : Piece
{
private static readonly List<PathFinding.Move> Moves = 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)
};
private static readonly List<PathFinding.Move> PromotedMoves = 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 Rook(WhichPlayer owner) : base(WhichPiece.Rook, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, PromotedMoves);
}
public override Piece DeepClone()
{
var clone = new Rook(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,29 @@
using PathFinding;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules.Pieces
{
public class SilverGeneral : Piece
{
private static readonly List<PathFinding.Move> Moves = 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)
};
public SilverGeneral(WhichPlayer owner) : base(WhichPiece.SilverGeneral, owner)
{
moveSet = new MoveSet(this, Moves);
promotedMoveSet = new MoveSet(this, GoldenGeneral.Moves);
}
public override Piece DeepClone()
{
var clone = new SilverGeneral(Owner);
if (IsPromoted) clone.Promote();
return clone;
}
}
}

View File

@@ -0,0 +1,59 @@
using PathFinding;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Gameboard.ShogiUI.Rules
{
public class PlanarCollection<T> : IPlanarCollection<T>, IEnumerable<T> where T : IPlanarElement
{
public delegate void ForEachDelegate(T element, int x, int y);
private readonly T?[] array;
private readonly int width;
private readonly int height;
public PlanarCollection(int width, int height)
{
this.width = width;
this.height = height;
array = new T[width * height];
}
public T? this[int x, int y]
{
get => array[y * width + x];
set => array[y * width + x] = value;
}
public T? this[float x, float y]
{
get => array[(int)y * width + (int)x];
set => array[(int)y * width + (int)x] = value;
}
public int GetLength(int dimension) => dimension switch
{
0 => width,
1 => height,
_ => throw new IndexOutOfRangeException()
};
public void ForEachNotNull(ForEachDelegate callback)
{
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
if (this[x, y] != null)
callback(this[x, y], x, y);
}
}
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in array) yield return item;
}
IEnumerator IEnumerable.GetEnumerator() => array.GetEnumerator();
}
}

View File

@@ -0,0 +1,385 @@
using Gameboard.ShogiUI.Rules.Pieces;
using PathFinding;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Gameboard.ShogiUI.Rules
{
/// <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, Vector2 position);
private readonly PathFinder2D<Piece> pathFinder;
private ShogiBoard? 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 ShogiBoard()
{
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);
InitializeBoardState();
player1King = new Vector2(4, 8);
player2King = new Vector2(4, 0);
Error = string.Empty;
}
public ShogiBoard(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 ShogiBoard(ShogiBoard 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[x, y];
if (piece != null)
{
Board[x, y] = piece.DeepClone();
}
}
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 ShogiBoard(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.X, move.To.Y] != 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.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.Value.X, move.From.Value.Y];
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.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 < 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.X, move.To.Y] = fromPiece;
Board[move.From.Value.X, move.From.Value.Y] = 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.X, from.Y];
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 ShogiBoard(this);
var moveToTry = new Move(from, position, false);
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[x, y] = null;
}
private void ResetFrontRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 6 : 2;
for (int x = 0; x < 9; x++) Board[x, y] = new Pawn(player);
}
private void ResetMiddleRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 7 : 1;
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 Bishop(player);
Board[7, y] = new Rook(player);
}
else
{
Board[1, y] = new Rook(player);
Board[7, y] = new Bishop(player);
}
}
private void ResetRearRow(WhichPlayer player)
{
int y = player == WhichPlayer.Player1 ? 8 : 0;
Board[0, y] = new Lance(player);
Board[1, y] = new Knight(player);
Board[2, y] = new SilverGeneral(player);
Board[3, y] = new GoldenGeneral(player);
Board[4, y] = new King(player);
Board[5, y] = new GoldenGeneral(player);
Board[6, y] = new SilverGeneral(player);
Board[7, y] = new Knight(player);
Board[8, y] = new 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
}
}

View File

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

View File

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