/// <summary> /// Helper constructor that creates a new chess board based off of a Fen string. /// </summary> /// <param name="fenBoard">The Fen string that represents the board.</param> public ChessBoard(string fenBoard) { Profiler.AddToMainProfile((int)ProfilerMethodKey.ChessBoard_ctor_string); Board = new ChessPiece[NumberOfRows, NumberOfColumns]; FromFenBoard(fenBoard); }
/////////////////////////////////////////////////////////////////////////// public override bool IsReady() { potentialTargets = new ArrayList (); foreach (ChessPiece player1Piece in scenario.GetAllChessPiecesForPlayer(1)) { foreach (ChessPiece player2Piece in scenario.GetAllChessPiecesForPlayer(2)) { if (player1Piece.CanCaptureXY (player2Piece.x, player2Piece.y)) potentialTargets.Add (player1Piece); } } int targetValue = 0; foreach (ChessPiece piece in potentialTargets) { if (piece.GetValue () > targetValue) { targetValue = piece.GetValue (); targetChessPiece = piece; } } if (targetChessPiece == null) { return false; } else { potentialPlacesToMoveTarget = new ArrayList (); foreach (PotentialMove move in targetChessPiece.GetMoveList()) { //Debug.Log (player2Piece.gameObject.name + ": Has " + player2Piece.GetMoveList().Count + " potential moves"); //int goodmoves = 0; foreach (ChessPiece player2Piece in scenario.GetAllChessPiecesForPlayer(2)) { //Debug.Log ("checked" + counter + "moves"); if (player2Piece.CanCaptureChessPieceIfItMovedToXY (targetChessPiece, move.x, move.y)) { if (GameObject.FindGameObjectWithTag ("Scenario").GetComponent<Scenario> ().GetPieceAtXY (move.x, move.y) == null) { //goodmoves++; potentialPlacesToMoveTarget.Add (move); Debug.Log(potentialPlacesToMoveTarget.Count); } } } // Debug.Log (player2Piece.gameObject.name + ": Potential Places to Move Target: " + goodmoves); } } if(potentialPlacesToMoveTarget.Count > 0){ return true; } else { return false; } }
/////////////////////////////////////////////////////////////////////////// public override bool IsReady() { potentialTargets = new ArrayList (); foreach (ChessPiece player1Piece in scenario.GetAllChessPiecesForPlayer(1)) { foreach (ChessPiece player2Piece in scenario.GetAllChessPiecesForPlayer(2)) { if (player1Piece.CanCaptureXY (player2Piece.x, player2Piece.y) && !player1Piece.IsDepressed()) { potentialTargets.Add (player1Piece); } } } int targetValue = 0; foreach (ChessPiece piece in potentialTargets) { if (piece.GetValue () > targetValue) { targetValue = piece.GetValue (); targetChessPiece = piece; } } if (targetChessPiece == null) { return false; } else { return true; } }
public void SetPiece( ChessPiece chessPiece ) { this.gameObject = chessPiece.gameObject; this.playerSide = chessPiece.playerSide; this.pieceType = chessPiece.pieceType; this.piecePlayerType = chessPiece.piecePlayerType; }
public override string getNotation(ChessSide side, ChessPiece[,] positions, int sr, int sf, int dr, int df, PromotionType promotion_type) { string str; if (sf == df) { str = "" + (char) ('a' + df) + (dr + 1); } else { str = "" + (char) ('a' + sf); if (positions[dr, df] != null) str += 'x'; str += "" + (char) ('a' + df) + (dr + 1); } if (dr == 7 || dr == 0) { /* No need to verify for specific colors * only whites can reach 7 and blacks can reach 0 */ str += ChessPiece. getPromotionString (promotion_type); } return str; }
public override bool isValidMove(int i, int j, ChessPiece[,] positions, int flags) { if (!base. isValidMove (i, j, positions, flags)) return false; int r_diff = i - rank; int f_diff = j - file; if (r_diff < 0) r_diff = -r_diff; if (f_diff < 0) f_diff = -f_diff; if (r_diff < 2 && f_diff < 2) return true; // if( castling ) { // if( file == ChessBoardConstants.e && j == ChessBoardConstants.g ) // return true; // if( file == ChessBoardConstants.e && j == ChessBoardConstants.c ) // return true; // } return false; }
public ChessPieceViewModel(ChessPiece i_ChessPiece, PieceColor i_PieceColor, PieceSide i_PieceSide, int i_File, int i_Rank) { ChessCoord tempChessCoord = new ChessCoord(); tempChessCoord.File = i_File; tempChessCoord.Rank = i_Rank; m_ChessPieceModel = new ChessPieceModel(i_ChessPiece, i_PieceColor, i_PieceSide, tempChessCoord); }
/////////////////////////////////////////////////////////////////////////// public override void Deactivate() { base.Deactivate (); primaryTarget = null; collateralTarget = null; Destroy(transform.GetComponent<Rigidbody>()); }
public void CopyFrom( ChessPiece chessPiece ) { this.gameObject = chessPiece.gameObject; this.playerSide = chessPiece.playerSide; this.pieceType = chessPiece.pieceType; this.piecePlayerType = chessPiece.piecePlayerType; this.bEnPassantCapture = chessPiece.bEnPassantCapture; }
protected override Int32 Evaluate(ChessBoard myBoard, ChessPiece turn, Int16 depth) { IncrementSearchCount(); var materialValue = (turn == ChessPiece.White ? 1 : -1) * myBoard.GetMaterialValue(this.ChessPieceRelativeValues, depth); var positionalValue = (turn == ChessPiece.White ? 1 : -1) * myBoard.GetPositionalValue(); return MaterialFactor * materialValue + PositionalFactor * positionalValue; }
public ChessBoardSquare( ChessPiece piece, ParticleSystem moveablePSystem, int nPile, int nRank ) { this.position = new ChessPosition( nRank, nPile ); this.piece = piece; if( this.piece != null ) this.piece.SetPosition( this.position.Get3DPosition() ); SetMovableEffect( moveablePSystem ); }
public void ClearPiece( bool bClearGameObject = false ) { if( IsBlank() ) return; if( bClearGameObject ) piece.Clear( true ); piece = null; }
public override string getNotation(ChessSide side, ChessPiece[,] positions, int sr, int sf, int dr, int df, PromotionType promotion) { return "K" + (char) ('a' + df) + (dr + 1); }
internal Piece(Piece piece) { PieceColor = piece.PieceColor; PieceType = piece.PieceType; Moved = piece.Moved; PieceValue = piece.PieceValue; PieceActionValue = piece.PieceActionValue; if (piece.ValidMoves != null) LastValidMoveCount = piece.ValidMoves.Count; }
public List<Tuple<int, int>[]> GetRelativePaths(ChessPiece p) { int direction = p.Direction; return new List<Tuple<int, int>[]>() { new[] { new Tuple<int, int>(direction, -1), }, new[] { new Tuple<int, int>(direction, 0), }, new[] { new Tuple<int, int>(direction * 2, 0), }, new[] { new Tuple<int, int>(direction, 1) }, }; }
public List<Tuple<int, int>[]> GetRelativePaths(ChessPiece p) { var l = new List<Tuple<int, int>[]>(); foreach (var subPath in new RookRelativePathProvider().GetRelativePaths(p)) l.Add(subPath); foreach (var subPath in new BishopRelativePathProvider().GetRelativePaths(p)) l.Add(subPath); return l; }
public static void TestInequality_DifferentPieceAndPlayer() { ChessPiece piece1 = new ChessPiece(Piece.King, Player.White); ChessPiece piece2 = new ChessPiece(Piece.Queen, Player.Black); Assert.AreNotEqual(piece1, piece2, "piece1 and piece2 are equal"); Assert.False(piece1.Equals(piece2), "piece1.Equals(piece2) should be false"); Assert.False(piece2.Equals(piece1), "piece2.Equals(piece1) should be false"); Assert.False(piece1 == piece2, "piece1 == piece2 should be false"); Assert.False(piece2 == piece1, "piece2 == piece1 should be false"); Assert.True(piece1 != piece2, "piece1 != piece2 should be True"); Assert.True(piece2 != piece1, "piece2 != piece1 should be True"); Assert.AreNotEqual(piece1.GetHashCode(), piece2.GetHashCode(), "Hash codes are equal"); }
public static void TestEquality() { ChessPiece piece1 = new ChessPiece(Piece.King, Player.White); ChessPiece piece2 = new ChessPiece(Piece.King, Player.White); Assert.AreEqual(piece1, piece2, "piece1 and piece2 are not equal"); Assert.True(piece1.Equals(piece2), "piece1.Equals(piece2) should be True"); Assert.True(piece2.Equals(piece1), "piece2.Equals(piece1) should be True"); Assert.True(piece1 == piece2, "piece1 == piece2 should be True"); Assert.True(piece2 == piece1, "piece2 == piece1 should be True"); Assert.False(piece1 != piece2, "piece1 != piece2 should be false"); Assert.False(piece2 != piece1, "piece2 != piece1 should be false"); Assert.AreEqual(piece1.GetHashCode(), piece2.GetHashCode(), "Hash codes are different"); }
public void ClearPiece( bool bClearGameObject = false ) { if( IsBlank() ) return; //if( bClearGameObject ) // UnityEngine.Debug.Log( "---------------------------------------ChessBoardSquare::Clear() - success!!!! piece type : " + piece.pieceType + // " File : " + position.nPile + " Rank : " + position.nRank ); piece.Clear( bClearGameObject ); piece = null; }
public static void TestThrowIfNull() { Assert.Throws<ArgumentNullException>(delegate () { object value = null; Utilities.ThrowIfNull(value, "value"); }); Assert.DoesNotThrow(delegate () { ChessPiece piece = new ChessPiece(Piece.Bishop, Player.White); Utilities.ThrowIfNull(piece, "piece"); }); }
public List<Tuple<int, int>[]> GetRelativePaths(ChessPiece p) { return new List<Tuple<int, int>[]>() { new[] { new Tuple<int, int>(-2, -1), }, new[] { new Tuple<int, int>(-2, 1), }, new[] { new Tuple<int, int>(-1, 2), }, new[] { new Tuple<int, int>(1, 2) }, new[] { new Tuple<int, int>(2, 1) }, new[] { new Tuple<int, int>(2, -1) }, new[] { new Tuple<int, int>(1, -2) }, new[] { new Tuple<int, int>(-1, -2) }, }; }
public override bool isValidMove(int i, int j, ChessPiece[,] positions, int flags) { if (!base. isValidMove (i, j, positions, flags)) return false; int tmp_r = rank, tmp_f = file; int rinc, finc, rdiff, fdiff; if (rank < i) { rinc = 1; rdiff = i - rank; } else { rinc = -1; rdiff = rank - i; } if (file < j) { finc = 1; fdiff = j - file; } else { finc = -1; fdiff = file - j; } if (rdiff != fdiff) return false; for (int dist = rdiff - 1; dist > 0; dist--) { tmp_r += rinc; tmp_f += finc; if (positions[tmp_r, tmp_f] != null) { return false; } } return true; }
public static bool isPawnPromotion(ChessPiece piece, int file) { if (piece.Type != PieceType.PAWN) return false; if (piece.Color == ColorType.WHITE && file == 7) return true; if (piece.Color == ColorType.BLACK && file == 0) return true; return false; }
public ChessPieceModel(ChessPiece i_ChessPiece, PieceColor i_PieceColor, PieceSide i_PieceSide, ChessCoord i_ChessCoord) { ChessPiece = i_ChessPiece; PieceColor = i_PieceColor; PieceSide = i_PieceSide; ChessCoord = i_ChessCoord; string PieceColorStr; if (i_PieceColor == PieceColor.White) { PieceColorStr = "White"; } else { PieceColorStr = "Black"; } switch (i_ChessPiece) { case ChessPiece.King: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_King.png"; break; case ChessPiece.Queen: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_Queen.png"; break; case ChessPiece.Bishop: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_Bishop.png"; break; case ChessPiece.Knight: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_Knight.png"; break; case ChessPiece.Rook: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_Rook.png"; break; case ChessPiece.Pawn: ResourceURI = @"/ChessAI;component/Resources/Pieces/" + PieceColorStr + "_Pawn.png"; break; } }
public static string ChessPieceTypeToNotation(ChessPiece chessPiece) { switch (chessPiece & ChessPiece.Type) { case ChessPiece.Pawn: return "P"; case ChessPiece.Knight: return "N"; case ChessPiece.Bishop: return "B"; case ChessPiece.Rook: return "R"; case ChessPiece.Queen: return "Q"; case ChessPiece.King: return "K"; } return ""; }
public ChessMove(string moveString) { string[] coords = moveString.Split('-'); if (coords.Length != 2) throw new ArgumentException("ChessMove must cotnain two coordinates separated by a hyphen"); if (coords[0].Length != 2) throw new ArgumentException("First component of ChessMove must be 2 characters"); if (coords[1].Length == 2) promotion = ChessPiece.Empty; else { if (coords[1].Length != 3) throw new ArgumentException("Second component of ChessMove must be 2 or 3 characters"); promotion = GetChessPiece(coords[1][2]); coords[1] = coords[1].Substring(0, 2); } source = new Coordinate(coords[0]); target = new Coordinate(coords[1]); }
/// <summary> /// 评价单个点的价值,仅为实验使用,不含神经网络 /// </summary> /// <param name="gs"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="type">棋子类型</param> /// <returns></returns> private static int EvaluatePointSimple(GameState gs, int x, int y, ChessPiece type) { int ans = 0; for (int i = 0; i < 4; i++) { if (x + d_x[i] >= 0 && x + d_x[i] < Settings.BOARD_SIZE && y + d_y[i] >= 0 && y + d_y[i] < Settings.BOARD_SIZE) ans += ChessPiece.EMPTY != gs.chessboard[x + d_x[i], y + d_y[i]] ? 1 : 0; } for (int i = 4; i < 8; i++) { if (x + d_x[i] >= 0 && x + d_x[i] < Settings.BOARD_SIZE && y + d_y[i] >= 0 && y + d_y[i] < Settings.BOARD_SIZE) ans += (ChessPiece.EMPTY != gs.chessboard[x + d_x[i], y + d_y[i]] ? 2 : 0); } return ans; }
public static void TestInEquality_OneIsNull() { ChessPiece piece1 = new ChessPiece(Piece.Rook, Player.White); ChessPiece piece2 = null; Assert.AreNotEqual(piece1, piece2, "piece1 and piece2 are equal"); Assert.False(piece1.Equals(piece2), "piece1.Equals(piece2) should be false"); Assert.False(piece1 == piece2, "piece1 == piece2 should be false"); Assert.False(piece2 == piece1, "piece2 == piece1 should be false"); Assert.True(piece1 != piece2, "piece1 != piece2 should be True"); Assert.True(piece2 != piece1, "piece2 != piece1 should be True"); piece1 = null; piece2 = new ChessPiece(Piece.Bishop, Player.Black); Assert.AreNotEqual(piece1, piece2, "piece1 and piece2 are equal"); Assert.False(piece2.Equals(piece1), "piece1.Equals(piece2) should be false"); Assert.False(piece1 == piece2, "piece1 == piece2 should be false"); Assert.False(piece2 == piece1, "piece2 == piece1 should be false"); Assert.True(piece1 != piece2, "piece1 != piece2 should be True"); Assert.True(piece2 != piece1, "piece2 != piece1 should be True"); }
void OnMouseDown() { if (spaceState == SpaceState.Open) { GameManager.currentInstance.MovePiece(this); GameManager.currentInstance.AdvanceGameState(); } else if (spaceState == SpaceState.Contested) { if (this.OccupyingPiece != null) { GameManager.currentInstance.RemovePiece(this.OccupyingPiece); //default capture case } else if (Pawn.EnPassantPossible) { BoardSpace enPassantSpace = GameManager.currentInstance.Board.getAdjacentSpace(this, SpaceDirection.Back, GameManager.currentInstance.activePiece.PieceColor,false); GameManager.currentInstance.RemovePiece(enPassantSpace.OccupyingPiece); } GameManager.currentInstance.MovePiece(this); OccupyingPiece = GameManager.currentInstance.activePiece; GameManager.currentInstance.AdvanceGameState(); } }
public List<Tuple<int, int>[]> GetRelativePaths(ChessPiece p) { int direction = p.Direction; var l = new List<Tuple<int, int>>(); var lResult = new List<Tuple<int, int>[]>(); for (int i = 1; i < 8; i++) { l.Add(new Tuple<int, int>(direction * i, 0)); } lResult.Add(l.ToArray()); l.Clear(); for (int i = 1; i < 8; i++) { l.Add(new Tuple<int, int>(direction * i * -1, 0)); } lResult.Add(l.ToArray()); l.Clear(); for (int i = 1; i < 8; i++) { l.Add(new Tuple<int, int>(0, -1 * i)); } lResult.Add(l.ToArray()); l.Clear(); for (int i = 1; i < 8; i++) { l.Add(new Tuple<int, int>(0, 1 * i)); } lResult.Add(l.ToArray()); return lResult; }
public void SetContainedPiece(ChessPiece piece) { containedPiece = piece; }
/// <summary> /// This method is used to determine the situation on the board after each move. /// The king has to know what has moved and how is this affecting him. /// </summary> public void UpdateKingsCurrentState() { movesInCheck = new bool[8, 8]; bool[,] possitionsToBreakCheck = new bool[8, 8]; army = new List <ChessPiece>(); IsKingInCheck = false; ChessPiece causeOfCheck = null; BoardVisualEffects.Instance.HideKingVisuals(); PossibleMoves(); for (int i = 0; i < BoardManager.BOARD_SIZE; i++) { for (int j = 0; j < BoardManager.BOARD_SIZE; j++) { ChessPiece piece = BoardManager.Instance.ChessBoardArr[i, j]; if (piece != null) { if (piece.IsWhite != IsWhite) { bool[,] pieceCheckPositions = piece.GetCheckPositions(); if (pieceCheckPositions[CurrentX, CurrentY]) { //in check BoardVisualEffects.Instance.DisplayKingInCheck(CurrentX, CurrentY); IsKingInCheck = true; causeOfCheck = piece; possitionsToBreakCheck = GetCheckPossitionsToKing(causeOfCheck); } for (int x = 0; x < BoardManager.BOARD_SIZE; x++) { for (int y = 0; y < BoardManager.BOARD_SIZE; y++) { if (pieceCheckPositions[x, y] == true) { if (pieceCheckPositions[x, y] == legalMoves[x, y]) { if (movesInCheck[x, y] != true) { movesInCheck[x, y] = true; numberOfPossibleMoves--; } } } } } } else { army.Add(piece); } } } } if (numberOfPossibleMoves == 0 && IsKingInCheck) { //if any of the King's pieces can hit the enemy causing the check => King is not yet dead! bool kingIsStillAlive = false; foreach (ChessPiece p in army) { bool[,] possibleMoves = p.PossibleMoves(); for (int x = 0; x < BoardManager.BOARD_SIZE; x++) { for (int y = 0; y < BoardManager.BOARD_SIZE; y++) { if ((possibleMoves[causeOfCheck.CurrentX, causeOfCheck.CurrentY]) || (possitionsToBreakCheck[x, y])) { kingIsStillAlive = true; break; } } } } if (!kingIsStillAlive) { CheckMate(); // weeell... at least we tried } } }
private void MoveChessPiece(int x, int y) { if (allowedMoves[x, y]) { ChessPiece enemyPiece = ChessPiecePositions[x, y]; if (enemyPiece != null && enemyPiece.isLight != isLightTurn) { piecesActive.Remove(enemyPiece.gameObject); Destroy(enemyPiece.gameObject); if (enemyPiece.GetType() == typeof(King)) { selectedPiece.transform.position = GetTileCenter(x, y); EndGame(); return; } } if (x == EnPassantMove[0] && y == EnPassantMove[1]) { if (isLightTurn) { enemyPiece = ChessPiecePositions[x, y - 1]; } else { enemyPiece = ChessPiecePositions[x, y + 1]; } piecesActive.Remove(enemyPiece.gameObject); Destroy(enemyPiece.gameObject); } EnPassantMove[0] = -1; EnPassantMove[1] = -1; if (selectedPiece.GetType() == typeof(Pawn)) { if (y == 7) // белая пешка в ферзя { piecesActive.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(1, x, y); selectedPiece = ChessPiecePositions[x, y]; } else if (y == 0) // черная пешка в ферзя { piecesActive.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(7, x, y); selectedPiece = ChessPiecePositions[x, y]; } // взятие на проходе EnPassantMove[0] = x; if (selectedPiece.CurrentY == 1 && y == 3) { EnPassantMove[1] = y - 1; } else if (selectedPiece.CurrentY == 6 && y == 4) { EnPassantMove[1] = y + 1; } } ChessPiecePositions[selectedPiece.CurrentX, selectedPiece.CurrentY] = null; ChessPiecePositions[x, y] = selectedPiece; selectedPiece.transform.position = GetTileCenter(x, y); selectedPiece.SetPosition(x, y); isLightTurn = !isLightTurn; } BoardHighlighting.Instance.HideHighlights(); selectedPiece = null; }
public override ReadOnlyCollection <Move> GetCandidateMoves(BoardState board, ChessPiece piece) { List <Move> CandidateMoves = new List <Move>(); if (!piece.HasMoved) { ReadOnlyCollection <Tile> CandidateTiles = GetCandidateTiles(board, piece); foreach (Tile Tile in CandidateTiles) { if (piece is IEnPassantable) { CandidateMoves.Add(new EnPassantableStartingMove(board[piece.Row, piece.Column], Tile)); } else { CandidateMoves.Add(new MovementMove(board[piece.Row, piece.Column], Tile)); } } } return(CandidateMoves.AsReadOnly()); }
public bool DidMovePiece(ChessPiece piece, Location destination) { return(false); }
/** Check if the specified piece can legally be moved the specified change in tiles. */ public static bool CanMovePiece(ChessPiece chessPiece, IntVector2 deltaTiles) { // FEATURE add a method that returns the reason for false // UNITTEST if (deltaTiles.IsZero()) { return(false); } switch (chessPiece.pieceType) { case ChessPiece.PieceType.PAWN: // Pawn normally only moves vertically if (!deltaTiles.IsVertical()) { return(false); } // Cannot move more than two tiles if (deltaTiles.stepMagnitude > 2) { return(false); } // Make sure the pawn is allowed to move two if it is trying to if (deltaTiles.stepMagnitude == 2) { if (!currentRuleSet.pawnCanMoveTwoOnFirstMove || chessPiece.movementsMade > 0) { return(false); } } // Cannot move pawns backwards if (chessPiece.pieceColor == ChessPiece.PieceColor.WHITE) { if (deltaTiles.y < 0) { return(false); } } else { if (deltaTiles.y > 0) { return(false); } } return(true); case ChessPiece.PieceType.BISHOP: return(deltaTiles.IsDiagonal()); case ChessPiece.PieceType.KNIGHT: int dx = Mathf.Abs(deltaTiles.x); int dy = Mathf.Abs(deltaTiles.y); return((dx == 1 && dy == 2) || (dx == 2 && dy == 1)); case ChessPiece.PieceType.ROOK: return(deltaTiles.IsHorizontal() || deltaTiles.IsVertical()); case ChessPiece.PieceType.QUEEN: return(deltaTiles.IsDiagonal() || deltaTiles.IsHorizontal() || deltaTiles.IsVertical()); case ChessPiece.PieceType.KING: return(deltaTiles.IsInUnitForm()); default: Debug.LogWarning("Unhandled chess piece type. Value:" + (int)chessPiece.pieceType); return(false); } }
public static bool IsEnPassantPossible(ChessPiece attackingPiece, ChessPiece defendingPiece, ChessBoard chessBoard) { // TODO implement return(false); }
private static bool IsPathClearRecursive(ChessPiece chessPiece, IntVector2 targetCoordinates, ChessBoard chessBoard) { // FEATURE add a method that returns the reason for false IntVector2 startCoords = chessBoard.GetTileCoordinates(chessPiece); IntVector2 deltaTiles = targetCoordinates - startCoords; ChessPiece pieceAt = chessBoard.GetChessPieceAt(targetCoordinates); // If the target is occupied, we cannot move through it if (pieceAt != null) { Debug.Log(pieceAt); return(false); } IntVector2 newTarget = IntVector2.zero; // Check if the path up to the target is clear switch (chessPiece.pieceType) { case ChessPiece.PieceType.PAWN: // Handled completely in the non-recursive portion return(true); case ChessPiece.PieceType.BISHOP: if (deltaTiles.IsInUnitForm()) { return(true); } newTarget = targetCoordinates; if (deltaTiles.y > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } if (deltaTiles.x > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); case ChessPiece.PieceType.KNIGHT: // Handled completely in the non-recursive portion return(true); case ChessPiece.PieceType.ROOK: int moveDelta = deltaTiles.x + deltaTiles.y; if (Mathf.Abs(moveDelta) != 1) { newTarget = targetCoordinates; if (deltaTiles.IsHorizontal()) { if (moveDelta > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else { if (moveDelta > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); } return(true); case ChessPiece.PieceType.QUEEN: if (deltaTiles.IsInUnitForm()) { return(true); } newTarget = targetCoordinates; if (deltaTiles.IsDiagonal()) { if (deltaTiles.y > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } if (deltaTiles.x > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else if (deltaTiles.IsHorizontal() || deltaTiles.IsVertical()) { moveDelta = deltaTiles.x + deltaTiles.y; if (deltaTiles.IsHorizontal()) { if (moveDelta > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else { if (moveDelta > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } } } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); case ChessPiece.PieceType.KING: // Handled completely in the non-recursive portion return(true); default: Debug.LogWarning("Unhandled chess piece type. Value:" + (int)chessPiece.pieceType); return(false); } }
/** Check if the piece would encounter other pieces it cannot pass over while moving to the specified tile. * This method should only be called with verified legal target coordinates; illegal movement will return a * meaningless/undefined result. Legal coordinates are coordinates within the board that return true for * CanMovePiece(ChessPiece chessPiece, Vector2 deltaTiles). */ public static bool IsPathClear(ChessPiece chessPiece, IntVector2 targetCoordinates, ChessBoard chessBoard) { // TODO implement // FEATURE add a method that returns the reason for false IntVector2 startCoords = chessBoard.GetTileCoordinates(chessPiece); IntVector2 deltaTiles = targetCoordinates - chessBoard.GetTileCoordinates(chessPiece); ChessPiece pieceAt = chessBoard.GetChessPieceAt(targetCoordinates); // Cannot move to a space if it is occupied by a piece of the same color if (pieceAt != null && pieceAt.pieceColor == chessPiece.pieceColor) { return(false); } int moveDelta = 0; IntVector2 newTarget = IntVector2.zero; switch (chessPiece.pieceType) { case ChessPiece.PieceType.PAWN: moveDelta = deltaTiles.y; if (Mathf.Abs(moveDelta) == 2) { if (moveDelta > 0) { if (chessBoard.GetChessPieceAt(startCoords.x, startCoords.y + 1) != null) { return(false); } } else { if (chessBoard.GetChessPieceAt(startCoords.x, startCoords.y - 1) != null) { return(false); } } } return(pieceAt == null); case ChessPiece.PieceType.BISHOP: if (deltaTiles.IsInUnitForm()) { return(true); } newTarget = targetCoordinates; if (deltaTiles.y > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } if (deltaTiles.x > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); case ChessPiece.PieceType.KNIGHT: // The knight does not have to pass through intermediate tiles, so if it got this far it can move there return(true); case ChessPiece.PieceType.ROOK: moveDelta = deltaTiles.x + deltaTiles.y; if (Mathf.Abs(moveDelta) != 1) { newTarget = targetCoordinates; if (deltaTiles.IsHorizontal()) { if (moveDelta > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else { if (moveDelta > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); } return(true); case ChessPiece.PieceType.QUEEN: if (deltaTiles.IsInUnitForm()) { return(true); } newTarget = targetCoordinates; if (deltaTiles.IsDiagonal()) { if (deltaTiles.y > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } if (deltaTiles.x > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else if (deltaTiles.IsHorizontal() || deltaTiles.IsVertical()) { moveDelta = deltaTiles.x + deltaTiles.y; if (deltaTiles.IsHorizontal()) { if (moveDelta > 0) { newTarget.x -= 1; } else { newTarget.x += 1; } } else { if (moveDelta > 0) { newTarget.y -= 1; } else { newTarget.y += 1; } } } return(IsPathClearRecursive(chessPiece, newTarget, chessBoard)); case ChessPiece.PieceType.KING: return(deltaTiles.IsInUnitForm()); default: Debug.LogWarning("Unhandled chess piece type. Value:" + (int)chessPiece.pieceType); return(false); } }
public void PlacePiece(Rank rank, File file, ChessPiece piece) { int square = SquareFromRankAndFile(rank, file); _squares[square].Piece = piece; }
// assuming you create the set of pieces programatically, use this constructor public ChessPiece(ChessPiece piece, ChessColor color) { FenId = color == ChessColor.Black ? FenIds[piece].ToLower() : FenIds[piece].ToUpper(); }
public static bool TestRand(ref string[][] generatedPairs, int Sign, int MyModuleId, out string BoardString) { BoardString = ""; try { string[] RandPieces = new string[6]; string TestString = ""; int ji = 0; while (ji < 6) { string temp = (char)(UnityEngine.Random.Range(0, 6) + 'a') + "" + (UnityEngine.Random.Range(0, 6) + 1); if (!TestString.Contains(temp)) { RandPieces[ji] = temp; TestString += temp; ji++; } } BoardState[,] chessBoard = new BoardState[6, 6]; ChessPiece[] myPieces; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { chessBoard[i, j] = BoardState.Empty; } } myPieces = new ChessPiece[6]; myPieces[1] = new ChessPiece((RandPieces[1][0]) - 'a', (RandPieces[1][1]) - '1', (Sign == 0 ? ChessPieceType.Knight : ChessPieceType.Rook), ref chessBoard); myPieces[3] = new ChessPiece(RandPieces[3][0] - 'a', RandPieces[3][1] - '1', ChessPieceType.Rook, ref chessBoard); if (ChessPiece.getWhite(RandPieces[4][0] - 'a', RandPieces[4][1] - '1')) { myPieces[4] = new ChessPiece(RandPieces[4][0] - 'a', RandPieces[4][1] - '1', ChessPieceType.Queen, ref chessBoard); myPieces[0] = new ChessPiece(RandPieces[0][0] - 'a', RandPieces[0][1] - '1', ChessPieceType.King, ref chessBoard); } else { myPieces[4] = new ChessPiece(RandPieces[4][0] - 'a', RandPieces[4][1] - '1', ChessPieceType.Rook, ref chessBoard); myPieces[0] = new ChessPiece(RandPieces[0][0] - 'a', RandPieces[0][1] - '1', ChessPieceType.Bishop, ref chessBoard); } if (Sign == 1 || myPieces[4].piece == ChessPieceType.Rook) { myPieces[2] = new ChessPiece(RandPieces[2][0] - 'a', RandPieces[2][1] - '1', ChessPieceType.King, ref chessBoard); } else { myPieces[2] = new ChessPiece(RandPieces[2][0] - 'a', RandPieces[2][1] - '1', ChessPieceType.Queen, ref chessBoard); } bool hasQueen = false; bool hasKnight = false; for (int i = 0; i < 5; i++) { if (myPieces[i].piece == ChessPieceType.Queen) { hasQueen = true; } if (myPieces[i].piece == ChessPieceType.Knight) { hasKnight = true; } } if (!hasQueen) { myPieces[5] = new ChessPiece(RandPieces[5][0] - 'a', RandPieces[5][1] - '1', ChessPieceType.Queen, ref chessBoard); } else if (!hasKnight) { myPieces[5] = new ChessPiece(RandPieces[5][0] - 'a', RandPieces[5][1] - '1', ChessPieceType.Knight, ref chessBoard); } else { myPieces[5] = new ChessPiece(RandPieces[5][0] - 'a', RandPieces[5][1] - '1', ChessPieceType.Bishop, ref chessBoard); } foreach (ChessPiece i in myPieces) { i.getTouchable(ref chessBoard); } int empty = 0; List <string> emptyArr = new List <string>(); for (int i = 5; i >= 0 && empty < 2; i--) { for (int j = 0; j < 6 && empty < 2; j++) { if (chessBoard[j, i] == BoardState.Empty) { empty++; emptyArr.Add((char)(j + 'a') + "" + (i + 1)); } } } if (empty == 1) { for (int i = 0; i < 6; i++) { generatedPairs[Sign][i] = RandPieces[i]; } generatedPairs[Sign][6] = emptyArr[0]; int[] Numbers = new int[6]; int SolutionNumber; { string s1 = generatedPairs[Sign][6]; SolutionNumber = ((s1[0] - 'a')) + 6 * (s1[1] - '1'); for (int i = 0; i < 6; i++) { s1 = generatedPairs[Sign][i]; Numbers[i] = ((s1[0] - 'a')) + 6 * (s1[1] - '1'); } } StringBuilder s = new StringBuilder("┌───┬───┬───┬───┬───┬───┐"); for (int i = 0; i < 11; i++) { s.Append("\n"); if (i % 2 == 0) { int v = 5 - (i / 2); for (int j = 0; j < 6; j++) { s.Append("│"); int o = Array.FindIndex(Numbers, x => x == v * 6 + j); s.Append(" "); if (o != -1) { ChessPieceType c = myPieces[o].piece; char pieceChar = ' '; switch (c) { case ChessPieceType.Bishop: pieceChar = 'B'; break; case ChessPieceType.King: pieceChar = 'K'; break; case ChessPieceType.Queen: pieceChar = 'Q'; break; case ChessPieceType.Knight: pieceChar = 'N'; break; case ChessPieceType.Rook: pieceChar = 'R'; break; } s.Append(pieceChar); } else { if (v * 6 + j == SolutionNumber) { s.Append('×'); } else { s.Append(" "); } } s.Append(" "); } s.Append("│"); } else { s.Append("├───┼───┼───┼───┼───┼───┤"); } } s.Append("\n"); s.Append("└───┴───┴───┴───┴───┴───┘"); BoardString = s.ToString(); return(true); } }catch (UnityException e) { Debug.Log("[Chess #" + MyModuleId + "] TestRand exception: " + e.Message); } return(false); }
public override ReadOnlyCollection <Move> GetCandidateMoves(BoardState board, ChessPiece piece) { ReadOnlyCollection <Tile> CandidateTiles = GetCandidateTiles(board, piece); List <Move> CandidateMoves = new List <Move>(); foreach (Tile tile in CandidateTiles) { CandidateMoves.Add(new BasicCaptureMove(board[piece.Row, piece.Column], tile)); } return(CandidateMoves.AsReadOnly()); }
/* * @InsertNewPiece -> Funcao de suporte para facilitar a insercao de novas pecas no tabuleiro * a partir da partida atual */ public void InsertNewPiece(char column, int line, ChessPiece piece) { Board.InsertPiece(piece, new ChessPosition(column, line).ToChessPosition()); Pieces.Add(piece); }
public void PrintBoard() { chessboard = new string[xValue, yValue]; chessPiece = new ChessPiece(); while (endProgram == false) { System.Console.Clear(); ChessBoardHeader(); try { for (int rowX = 0; rowX < xValue; rowX++) { //Indent System.Console.Write(("").PadRight(5)); for (int columnY = 0; columnY < yValue; columnY++) { //Draw Rows System.Console.Write(rowBorder); } System.Console.Write("+\n"); for (int columnY = 0; columnY < yValue; columnY++) { if (columnY == 0) { // Y-Axis Header + Indent System.Console.Write((((rowX + 1).ToString().PadLeft(4)) + " ").PadRight(3)); } else { //System.Console.Write(" "); } System.Console.Write((columnBorder).PadRight(2)); //Print Symbol or Space? System.Console.Write((ChessPiece.chessPiece[rowX, columnY]).PadLeft(1).PadRight(2)); } //End of Column System.Console.Write(("|\n").PadLeft(2)); } System.Console.Write((" ").PadRight(5)); for (int columnY = 0; columnY < yValue; columnY++) { System.Console.Write((rowBorder)); } System.Console.Write("+\n\n"); System.Console.WriteLine(); chessPiece.MovePiece(); if (endProgram == true) { break; } if (endProgram == false) { continue; } } //commit test catch { } } }
private bool CanMove(Position position) { ChessPiece cp = Chessboard.ChessPiece(position); return(cp == null || cp.Color != Color); }
public void OnSelect(ChessPiece piece) { SelectPiece = piece; }
private void MovePiece(int x, int y) { if (allowedMoves[x, y]) { // Get the piece in the destination tile ChessPiece piece = Board[x, y]; // If there is a piece at this place and it is not on our team if (piece != null && piece.isWhite != isWhiteTurn) { // Capture the piece // If it's the king if (piece.GetType() == typeof(King)) { EndGame(false); return; } activeChessPieces.Remove(piece.gameObject); Destroy(piece.gameObject); } // If it was an EnPassantMove if (x == EnPassantMove[0] && y == EnPassantMove[1]) { if (isWhiteTurn) { piece = Board[x, y - 1]; } else { piece = Board[x, y + 1]; } activeChessPieces.Remove(piece.gameObject); Destroy(piece.gameObject); } // Reset the EnPassantMove before calculating it EnPassantMove[0] = -1; EnPassantMove[1] = -1; // If we are moving a pawn, calculate EnPassantMove if (selectedPiece.GetType() == typeof(Pawn)) { if (y == 7) { // If white has reached the top, promote it activeChessPieces.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(10, x, y); selectedPiece = Board[x, y]; } else if (y == 0) { // if black has reached the bottom, promote it activeChessPieces.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(4, x, y); selectedPiece = Board[x, y]; } if (selectedPiece.CurrentY == 1 && y == 3) { // set the black enPassantMove EnPassantMove[0] = x; EnPassantMove[1] = y - 1; } else if (selectedPiece.CurrentY == 6 && y == 4) { // set the white enPassantMove EnPassantMove[0] = x; EnPassantMove[1] = y + 1; } } // Remove the piece from the grid's current position Board[selectedPiece.CurrentX, selectedPiece.CurrentY] = null; // Move the object StartCoroutine(MovePiece(selectedPiece.transform.localPosition, GetPosition(x, y), selectedPiece.transform)); selectedPiece.SetPosition(x, y); // Move the piece on the virtual board Board[x, y] = selectedPiece; // Swap turns isWhiteTurn = !isWhiteTurn; } // Hide the highlights after the movement BoardHighlights.Instance.Hidehighlights(); // Deselect the piece after the movement selectedPiece = null; }
public List <GridSquare> getMoves(GridSquare g) { ChessPiece piece = g.getPiece(); int curRow = g.getRow(); int curCol = g.getCol(); List <GridSquare> possibleMoves = new List <GridSquare>(); Dictionary <MoveType, List <MoveOffset> > offsetMap = new Dictionary <MoveType, List <MoveOffset> >(); Player friendly = (whiteTurn ? whitePlayer : blackPlayer); Player enemy = (whiteTurn ? blackPlayer : whitePlayer); Player playerOfPiece = g.getPlayer(); GridSquare candidateMove; Player candidatePlayer; // add the move types of the piece to the map offsetMap.Add(MoveType.UP, piece.getUpMoveOffsets()); offsetMap.Add(MoveType.DOWN, piece.getDownMoveOffsets()); offsetMap.Add(MoveType.RIGHT, piece.getRightMoveOffsets()); offsetMap.Add(MoveType.LEFT, piece.getLeftMoveOffsets()); offsetMap.Add(MoveType.DIAG_NE, piece.getNEDiagMoveOffsets()); offsetMap.Add(MoveType.DIAG_NW, piece.getNWDiagMoveOffsets()); offsetMap.Add(MoveType.DIAG_SW, piece.getSWDiagMoveOffsets()); offsetMap.Add(MoveType.DIAG_SE, piece.getSEDiagMoveOffsets()); // handle the knights separately for simplicitly if (piece is Knight) { foreach (MoveOffset offset in piece.getKnightMoveOffsets()) { int moveRow = curRow + offset.getRow(); int moveCol = curCol + offset.getCol(); if (boundaryCheck(moveRow, moveCol)) { candidateMove = grid[moveRow, moveCol]; candidatePlayer = candidateMove.getPlayer(); if (candidatePlayer == null || candidatePlayer == enemy) { possibleMoves.Add(candidateMove); } if (candidatePlayer == null) { candidateMove.markOpenPath(); } if (candidatePlayer == enemy) { candidateMove.markEnemy(); } } } // we do not need to consider the other move types return(possibleMoves); } // add pawn attacking moves to possibleMoves if (piece is Pawn) { // check the possible attacking pawn moves foreach (MoveOffset offset in piece.getSpecialMoveOffsets()) { int moveRow = curRow + offset.getRow(); int moveCol = curCol + offset.getCol(); // black pawns move down the board if (playerOfPiece == blackPlayer) { // so we need to correct the row offset moveRow = curRow - offset.getRow(); } // add the offseted square to the list of possible moves if // it contains an enemy if (boundaryCheck(moveRow, moveCol)) { candidateMove = grid[moveRow, moveCol]; candidatePlayer = candidateMove.getPlayer(); if (candidatePlayer == enemy) { possibleMoves.Add(candidateMove); candidateMove.markEnemy(); } } } } // iterate through the non-special move types foreach (KeyValuePair <MoveType, List <MoveOffset> > kvp in offsetMap) { MoveType moveType = kvp.Key; List <MoveOffset> possibleOffsets = kvp.Value; foreach (MoveOffset offset in possibleOffsets) { int moveRow = curRow + offset.getRow(); int moveCol = curCol + offset.getCol(); // black pawns move down the board if (piece is Pawn && playerOfPiece == blackPlayer) { // so we need to correct the row offset moveRow = curRow - offset.getRow(); } if (!boundaryCheck(moveRow, moveCol)) // invalid square // All squares beyond this square are also invalid. // This isn't true in the case of a knight, so it is // considered separately. { break; } candidateMove = grid[moveRow, moveCol]; candidatePlayer = candidateMove.getPlayer(); if (candidatePlayer == null) { possibleMoves.Add(candidateMove); candidateMove.markOpenPath(); } else if (candidatePlayer == enemy) { // when moving upwards, everything except the pawn can take a piece if (!(piece is Pawn)) { possibleMoves.Add(candidateMove); candidateMove.markEnemy(); } break; } else // friendly piece { break; } } } return(possibleMoves); }
public override bool IsLegalMove(Move move, ChessGame game) { ChessUtility.ThrowIfNull(move, "move"); ChessUtility.ThrowIfNull(game, "game"); BoardPosition origin = move.OriginalPosition; BoardPosition destination = move.NewPosition; ChessPiece promotion = null; if (move.Promotion.HasValue && ValidPromotionPieces.Contains(move.Promotion.Value)) { promotion = game.MapPgnCharToPiece(char.ToUpper(move.Promotion.Value), move.Player); } BoardDistance posDelta = new BoardDistance(origin, destination); if ((posDelta.X != 0 || posDelta.Y != 1) && (posDelta.X != 1 || posDelta.Y != 1) && (posDelta.X != 0 || posDelta.Y != 2)) { return(false); } if (Owner == ChessPlayer.White) { if (origin.Rank > destination.Rank) { return(false); } if (destination.Rank == 8) { if (promotion == null) { return(false); } if (promotion.Owner != ChessPlayer.White) { return(false); } if (!ValidPromotionPieces.Contains(promotion.GetFENLetter())) { return(false); } } } if (Owner == ChessPlayer.Black) { if (origin.Rank < destination.Rank) { return(false); } if (destination.Rank == 1) { if (promotion == null) { return(false); } if (promotion.Owner != ChessPlayer.Black) { return(false); } if (!ValidPromotionPieces.Contains(promotion.GetFENLetter())) { return(false); } } } bool checkEnPassant = false; if (posDelta.Y == 2) { if ((origin.Rank != 2 && Owner == ChessPlayer.White) || (origin.Rank != 7 && Owner == ChessPlayer.Black)) { return(false); } if (origin.Rank == 2 && game.GetPieceAt(origin.File, 3) != null) { return(false); } if (origin.Rank == 7 && game.GetPieceAt(origin.File, 6) != null) { return(false); } } ChessPiece pieceAtDestination = game.GetPieceAt(destination); if (posDelta.X == 0 && (posDelta.Y == 1 || posDelta.Y == 2)) { if (pieceAtDestination != null) { return(false); } } else { if (pieceAtDestination == null) { checkEnPassant = true; } else if (pieceAtDestination.Owner == Owner) { return(false); } } if (checkEnPassant) { ReadOnlyCollection <DetailedMove> _moves = game.Moves; if (_moves.Count == 0) { return(false); } if ((origin.Rank != 5 && Owner == ChessPlayer.White) || (origin.Rank != 4 && Owner == ChessPlayer.Black)) { return(false); } Move latestMove = _moves[_moves.Count - 1]; if (latestMove.Player != ChessUtility.GetOpponentOf(Owner)) { return(false); } if (!(game.GetPieceAt(latestMove.NewPosition) is Pawn)) { return(false); } if (game.GetPieceAt(latestMove.NewPosition).Owner == Owner) { return(false); } if (Owner == ChessPlayer.White) { if (latestMove.OriginalPosition.Rank != 7 || latestMove.NewPosition.Rank != 5) { return(false); } } else // (m.Player == Players.Black) { if (latestMove.OriginalPosition.Rank != 2 || latestMove.NewPosition.Rank != 4) { return(false); } } if (destination.File != latestMove.NewPosition.File) { return(false); } } return(true); }
private bool[,] GetCheckPossitionsToKing(ChessPiece checkPiece) { bool[,] result = new bool[8, 8]; if (checkPiece.GetType() != typeof(Knight)) { if (checkPiece.CurrentX == CurrentX) //vertical { if (checkPiece.CurrentY > CurrentY) { for (int y = checkPiece.CurrentY - 1; y > CurrentY; y--) { result [CurrentX, y] = true; } } else { for (int y = checkPiece.CurrentY + 1; y < CurrentY; y++) { result [CurrentX, y] = true; } } } else if (checkPiece.CurrentY == CurrentY) //horizontal { if (checkPiece.CurrentX > CurrentX) { for (int x = checkPiece.CurrentX - 1; x > CurrentX; x--) { result [x, CurrentY] = true; } } else { for (int x = checkPiece.CurrentX + 1; x < CurrentX; x++) { result [x, CurrentY] = true; } } } else //diagonal { int x = checkPiece.CurrentX, y = checkPiece.CurrentY; if (checkPiece.CurrentX > CurrentX && checkPiece.CurrentY > CurrentY) { while (x - 1 > CurrentX && y - 1 > CurrentY) { result [--x, --y] = true; } } else if (checkPiece.CurrentX > CurrentX && checkPiece.CurrentY < CurrentY) { while (x - 1 > CurrentX && y + 1 < CurrentY) { result [--x, ++y] = true; } } else if (checkPiece.CurrentX < CurrentX && checkPiece.CurrentY < CurrentY) { while (x + 1 < CurrentX && y + 1 < CurrentY) { result [++x, ++y] = true; } } else { while (x + 1 < CurrentX && y - 1 > CurrentY) { result [++x, --y] = true; } } } } return(result); }
public Game() { //TODO: Setup board board = new ChessPiece[BOARD_WIDTH][]; for (int i = 0; i < BOARD_WIDTH; i++) { board[i] = new ChessPiece[BOARD_HEIGHT]; } turn = -1; /*Generate board*/ /**Pawns**/ //Black for (int i = 0; i < BOARD_WIDTH; i++) { board[i][1] = new Pawn(i, 1, 1); } //White for (int i = 0; i < BOARD_WIDTH; i++) { board[i][6] = new Pawn(i, 6, -1); } /**Rooks**/ //Black board[0][0] = new Rook(0, 0, 1); board[BOARD_WIDTH - 1][0] = new Rook(BOARD_WIDTH - 1, 0, 1); //White board[0][BOARD_HEIGHT - 1] = new Rook(0, BOARD_HEIGHT - 1, -1); board[BOARD_WIDTH - 1][BOARD_HEIGHT - 1] = new Rook(BOARD_WIDTH - 1, BOARD_HEIGHT - 1, -1); /**Knights**/ //Black board[1][0] = new Knight(1, 0, 1); board[BOARD_WIDTH - 2][0] = new Knight(BOARD_WIDTH - 2, 0, 1); //White board[1][BOARD_HEIGHT - 1] = new Knight(1, BOARD_HEIGHT - 1, -1); board[BOARD_WIDTH - 2][BOARD_HEIGHT - 1] = new Knight(BOARD_WIDTH - 2, BOARD_HEIGHT - 1, -1); /**Bishops**/ //Black board[2][0] = new Bishop(2, 0, 1); board[BOARD_WIDTH - 3][0] = new Bishop(BOARD_WIDTH - 3, 0, 1); //White board[2][BOARD_HEIGHT - 1] = new Bishop(2, BOARD_HEIGHT - 1, -1); board[BOARD_WIDTH - 3][BOARD_HEIGHT - 1] = new Bishop(BOARD_WIDTH - 3, BOARD_HEIGHT - 1, -1); /**Kings**/ //Black board[3][0] = new King(3, 0, 1); //White board[3][BOARD_HEIGHT - 1] = new King(3, BOARD_HEIGHT - 1, -1); /**Queens**/ //Black board[4][0] = new Queen(4, 0, 1); //White board[4][BOARD_HEIGHT - 1] = new Queen(4, BOARD_HEIGHT - 1, -1); }
public GameState(GameState gs) { chessboard = (ChessPiece[, ])gs.chessboard.Clone(); turn = gs.turn; last_modify = (int[])gs.last_modify.Clone(); }
private void Update() { if (!currentCamera) { currentCamera = Camera.main; return; } RaycastHit info; Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile", "Hover", "Highlight"))) { // Get the indexes of a tile i've hit Vector2Int hitPosition = LookupTileIndex(info.transform.gameObject); // if we are hovring a tile after not hovring any tiles if (currentHover == -Vector2Int.one) { currentHover = hitPosition; tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover"); } // if we were already hovring a tile, change the previous one if (currentHover != hitPosition) { tiles[currentHover.x, currentHover.y].layer = (ContainsValidMove(ref availableMoves, currentHover)) ? LayerMask.NameToLayer("Highlight") : LayerMask.NameToLayer("Tile"); currentHover = hitPosition; tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover"); } // if we press down on the mouse if (Input.GetMouseButtonDown(0)) { if (chessPieces[hitPosition.x, hitPosition.y] != null) { // Is it our turn if ((chessPieces[hitPosition.x, hitPosition.y].team == 0 && isWhiteTurn) || (chessPieces[hitPosition.x, hitPosition.y].team == 1 && !isWhiteTurn)) { currentlyDragging = chessPieces[hitPosition.x, hitPosition.y]; // Get a list of where i can go, highlights tile as well availableMoves = currentlyDragging.GetAvailableMoves(ref chessPieces, TILE_COUNT_X, TILE_COUNT_Y); HighlightTiles(); } } } // if we are releasing the mouse if (currentlyDragging != null && Input.GetMouseButtonUp(0)) { Vector2Int previousPosition = new Vector2Int(currentlyDragging.currentX, currentlyDragging.currentY); bool validMove = MoveTo(currentlyDragging, hitPosition.x, hitPosition.y); if (!validMove) { currentlyDragging.SetPosition(GetTileCenter(previousPosition.x, previousPosition.y)); } currentlyDragging = null; RemoveHighlightTiles(); } } else { if (currentHover != -Vector2Int.one) { tiles[currentHover.x, currentHover.y].layer = (ContainsValidMove(ref availableMoves, currentHover)) ? LayerMask.NameToLayer("Highlight") : LayerMask.NameToLayer("Tile"); currentHover = -Vector2Int.one; } if (currentlyDragging && Input.GetMouseButtonUp(0)) { currentlyDragging.SetPosition(GetTileCenter(currentlyDragging.currentX, currentlyDragging.currentY)); currentlyDragging = null; RemoveHighlightTiles(); } } // if we are dragging a piece if (currentlyDragging) { Plane horizontalPlane = new Plane(Vector3.up, Vector3.up * yoffset); float distance = 0.0f; if (horizontalPlane.Raycast(ray, out distance)) { currentlyDragging.SetPosition(ray.GetPoint(distance) + Vector3.up * dragOffset); } } }
/// <summary> /// 得到另一位选手 /// </summary> /// <param name="cp"></param> /// <returns></returns> public static ChessPiece AnotherPlayer(ChessPiece cp) { return(cp == ChessPiece.CROSS ? ChessPiece.NOUGHT : ChessPiece.CROSS); }
/// <summary> /// Checks if the move from startPosition to endPosition is valid. /// Assumes that startPosition and endPosition are valid parameters. /// Returns false if there is no piece at startPosition, or the piece otherwise /// cannot complete the requested move. /// </summary> /// <param name="startPosition">The position of the piece to move.</param> /// <param name="endPosition">The destination of the piece.</param> /// <returns></returns> public bool IsMoveValid(Position startPosition, Position endPosition) { // Get piece at input location ChessPiece startPiece = board.PieceAt(startPosition); ChessPiece endPiece = board.PieceAt(endPosition); // If there is no piece at the requested start position, return false if (startPiece == null) { return(false); } // Piece can't move if it's not this pieces turn to move if (startPiece.Team != board.WhoseTurn) { return(false); } //get places this piece could move ignoring obstructions IReadOnlyList <Vector2D> pieceMovementVectors; if (endPiece == null) //replace with DoesMoveCapture when implementing En Passant { pieceMovementVectors = startPiece.GetAllowedMotionVectors(); } else { // If there is a piece in the way and it is a friendly piece, then we can't move there if (endPiece.Team == startPiece.Team) { return(false); } pieceMovementVectors = startPiece.GetAttackMotionVectors(); } //checks if destination is in one of the positions this piece could move (ignoring obsturctions for now) var requestedMoveVector = (Point2D)endPosition - (Point2D)startPosition; bool onPieceVector = false; foreach (var v in pieceMovementVectors) //TODO: make more efficient { if (v == requestedMoveVector) { onPieceVector = true; break; } } if (!onPieceVector) { System.Diagnostics.Debug.WriteLine("Destination not on this piece's vectors."); return(false); } /*try * { * var matchingMove = pieceMovementVectors.Single(v => v == requestedMoveVector); * } * catch (InvalidOperationException) * { * // Could not retrieve a matching vector from the allowed moves * return false; * }*/ // If the piece can jump, it doesn't matter if something is in the way if (startPiece.CanJump) { return(true); } return(isPathClear(startPosition, endPosition)); }
private void testCatchDraws() { // simulate for white and black side for each ally and target chess pieces for (int colorValues = 0; colorValues < 4; colorValues++) { // TODO: try to figure out why the code crashes in third loop (ally=black, target=white) var allyColor = (ChessColor)(colorValues / 2); var targetColor = (ChessColor)(colorValues % 2); // check for all rows on the chess board for (int rowDiff = 0; rowDiff < 6; rowDiff++) { int allyRow = (allyColor == ChessColor.White) ? (1 + rowDiff) : (6 - rowDiff); int nextRow = (allyColor == ChessColor.White) ? (allyRow + 1) : (allyRow - 1); // get the column where the peasant is moving foreward for (int allyCol = 0; allyCol < 8; allyCol++) { var oldPos = new ChessPosition(allyRow, allyCol); for (int targetColMiddle = 1; targetColMiddle < 7; targetColMiddle++) { var targetPosLeft = new ChessPosition(nextRow, targetColMiddle - 1); var targetPosRight = new ChessPosition(nextRow, targetColMiddle + 1); var allyPeasant = new ChessPiece(ChessPieceType.Peasant, allyColor, true); var enemyPeasant = new ChessPiece(ChessPieceType.Peasant, targetColor, true); int kingsRow = (allyColor == ChessColor.White) ? 0 : 7; var pieces = new List <ChessPieceAtPos>() { new ChessPieceAtPos(oldPos, allyPeasant), new ChessPieceAtPos(targetPosLeft, enemyPeasant), new ChessPieceAtPos(targetPosRight, enemyPeasant), new ChessPieceAtPos(new ChessPosition(kingsRow, 0), new ChessPiece(ChessPieceType.King, ChessColor.White, false)), new ChessPieceAtPos(new ChessPosition(kingsRow, 7), new ChessPiece(ChessPieceType.King, ChessColor.Black, false)), }; //output.WriteLine($"current constellation: allyColor={allyColor}, targetColor={targetColor}, allyRow={allyRow}, allyCol={allyCol}, targetColMiddle={targetColMiddle}"); var board = new ChessBitboard(new ChessBoard(pieces)); var catchDraws = board.GetAllDraws(allyColor, null, true).Where(x => x.OldPosition == oldPos && x.OldPosition.Column != x.NewPosition.Column); // get the expected draws count (for catch draw onto level 8, there are 4 draws instead of just 1 due to the peasant promotion) int expectedCatchDrawsCount = (targetColor == allyColor) ? 0 : (targetColMiddle == allyCol) ? 2 : ((Math.Abs(targetColMiddle - allyCol) == 2) ? 1 : 0); expectedCatchDrawsCount = ((rowDiff == 5) ? 4 : 1) * expectedCatchDrawsCount; Assert.True(catchDraws.Count() == expectedCatchDrawsCount); // check if the draws are correctly applied to the chess board foreach (var draw in catchDraws) { var simBoard = board.ApplyDraw(draw); var pieceCmp = new ChessPiece(ChessPieceType.Peasant, allyColor, true); Assert.True(!simBoard.IsCapturedAt(draw.OldPosition) && (simBoard.GetPieceAt(draw.NewPosition) == pieceCmp || (rowDiff == 5))); } } } } } }
public bool IsCheckMoveValid(Point2D startPoint, Point2D endPoint) { // Get piece at input location ChessPiece startPiece = board.PieceAt(startPoint); ChessPiece endPiece = board.PieceAt(endPoint); // If there is no piece at the requested start position, return false if (startPiece == null) { return(false); } IReadOnlyList <Vector2D> pieceMovementVectors; if (endPiece == null) { pieceMovementVectors = startPiece.GetAllowedMotionVectors(); } else { // If there is a piece in the way and it is a friendly piece, then we can't move there if (endPiece.Team == startPiece.Team) { return(false); } pieceMovementVectors = startPiece.GetAttackMotionVectors(); } var requestedMoveVector = endPoint - startPoint; bool matchingVector = false; // true if requested MoveVector matches a movement vector in pieceMovementVectors foreach (var moveVector in pieceMovementVectors) { if (requestedMoveVector == moveVector) { matchingVector = true; break; } } if (!matchingVector) { System.Diagnostics.Debug.WriteLine("Move illegal because it no piece vectors match that vector"); return(false); } /*try * { * var matchingMove = pieceMovementVectors.Single(v => v == requestedMoveVector); * } * catch (InvalidOperationException) * { * // Could not retrieve a matching vector from the allowed moves * return false; * }*///TODO: Remove this code // If the piece can jump, it doesn't matter if something is in the way if (startPiece.CanJump) { return(true); } return(isPathClear(startPoint, endPoint)); }
public void setPiece(ChessPiece piece) { this.piece = piece; }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); //Draw Squares and Pieces Color squareColor = Color.White; for (byte i = 0; i < boardInfo.pieces.Length; ++i) { if ((int)(i / Constants.NumberOfRanks) % 2 == 0) { if (i % 2 == 0) { squareColor = Color.White; } else { squareColor = Color.Gray; } } else { if (i % 2 == 0) { squareColor = Color.Gray; } else { squareColor = Color.White; } } ChessPiece piece = boardInfo.pieces[i]; if (piece != null) { if (piece.isSelected) { squareColor = Color.Blue; } spriteBatch.Draw(dummyTexture, new Rectangle((i % Constants.NumberOfFiles) * Constants.SquareSize, (int)(i / Constants.NumberOfRanks) * Constants.SquareSize, Constants.SquareSize, Constants.SquareSize), squareColor); Texture2D textureToDraw; if (piece.PieceColor == ChessPieceColor.White) { textureToDraw = textureArray[(int)piece.Identifier]; } else { textureToDraw = textureArray[(int)ChessPieceType.None + (int)piece.Identifier]; } spriteBatch.Draw(textureToDraw, new Rectangle((i % Constants.NumberOfFiles) * Constants.SquareSize, (int)(i / Constants.NumberOfRanks) * Constants.SquareSize, Constants.SquareSize, Constants.SquareSize), Color.White); } else { spriteBatch.Draw(dummyTexture, new Rectangle((i % Constants.NumberOfFiles) * Constants.SquareSize, (int)(i / Constants.NumberOfRanks) * Constants.SquareSize, Constants.SquareSize, Constants.SquareSize), squareColor); } } spriteBatch.End(); base.Draw(gameTime); }