87 lines
2.9 KiB
C#
87 lines
2.9 KiB
C#
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
|
|
{
|
|
private static readonly string BoardNotationRegex = @"(?<file>[A-I])(?<rank>[1-9])";
|
|
private static readonly char A = 'A';
|
|
|
|
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, 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.HasValue ? ToBoardNotation(From.Value) : null,
|
|
IsPromotion = IsPromotion,
|
|
PieceFromCaptured = PieceFromHand.HasValue ? PieceFromHand : null,
|
|
To = ToBoardNotation(To)
|
|
};
|
|
|
|
private static string ToBoardNotation(Vector2 vector)
|
|
{
|
|
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}");
|
|
}
|
|
}
|
|
}
|