适用于 .NET 应用程序的轻量级、功能齐全的国际象棋解决方案,通过易位、过路、棋子提升和最小最大人工智能玩家展示正确的棋子移动。
使用静态 BoardFactory.CreateBoard 函数创建 Board 的实例,创建棋子位于默认位置的棋盘。该板遵循 X,Y 网格系统,其中 (0,0) 是左下方的网格方块,(7,7) 是右上方的网格方块。玩家一号棋子(白色)创建在底部两行,玩家二号棋子(黑色)创建在顶部两行。棋盘还存储当前回合,即棋盘最初创建时为玩家一号,并在移动时交换。
Board board = BoardFactory . CreateBoard ( ) ;
然后,您必须创建 ChessPlayers 实例并将它们添加到棋盘中。 ChessPlayer 类本身是抽象的,因此您必须创建派生类或仅使用现有的 BasicPlayer。实例化 ChessPlayer 时,您还必须指定他们所在的团队,玩家一或玩家二,然后将它们添加到棋盘上。然后,ChessPlayer 实例可以通过调用基本 MakeMove 函数来进行移动。
public abstract class ChessPlayer
{
public virtual void Update ( float deltaTime ) { }
protected virtual void OnGameStateChanged ( GameState state ) { }
protected virtual void OnTurnSwapped ( Player player ) { }
protected bool MovePiece ( BoardPieceMove boardPieceMove ) { }
}
_board = BoardFactory . CreateBoard ( ) ;
_board . AddPlayer ( new UnityChessPlayer ( _board , Player . PlayerOne ) ) ;
_board . AddPlayer ( new AIChessPlayer ( _board , Player . PlayerTwo ) ) ;
通过您的自定义 ChessPlayers,您可以拥有特定的玩家功能,例如为玩家移动的 AI,或为其中一名玩家应用移动的第 3 方输入管理器。
public class AIChessPlayer : ChessPlayer
{
public AIChessPlayer ( Board board , Player player ) : base ( board , player ) { }
protected override void BoardOnOnTurnSwapped ( Player player )
{
if ( player == _player )
{
ThreadPool . QueueUserWorkItem ( ( state ) => CalculateAndMove ( ) ) ;
}
}
private void CalculateAndMove ( )
{
MovePiece ( MinMaxMoveCalc . GetBestMove ( Board ) ) ;
}
}
移动由起始位置和终止位置定义。如果棋手已经添加到棋盘中,则可以通过调用 MovePiece 函数来进行走棋。
var pawnPos = new Vector2I ( 4 , 1 ) ;
var pawnDest = new Vector2I ( 4 , 3 ) ;
var move = new BoardPieceMove ( pawnPos , pawnDest ) ;
_player . MovePiece ( move ) ;
如果您所做的移动在任何方面都是无效的,ApplyMove 函数将返回 false;如果移动成功应用,则ApplyMove 函数将返回 true。由于以下原因,移动可能无效:
您可以订阅在整个国际象棋游戏中调用的各种回调,使您的应用程序可以轻松地对国际象棋游戏中的事件做出反应。 OnBoardChanged 回调很特殊,因为它为您提供上一回合应用于棋盘的每个操作的列表,例如棋子移动、棋子拿走、棋子升级等,并且包括棋子本身,为您提供棋子的“到”和“从”位置。移动。这可以让您制作运动动画或仅渲染板。
// Called when a player makes their move and its parameter is the current players go.
public event PlayerDelegate OnTurnSwapped ;
/// Called when a player is in checkmate and its parameter is the player in check.
public event PlayerDelegate OnPlayerInCheck ;
/// Called when a something on the board has changed and its parameter is a list of changes.
public event BoardChangesDelegate OnBoardChanged ;
/// Called when the state of the game changes, such as when a game is paused, resumed or ended.
public event BoardGameStateDelegate OnGameStateChanged ;