public override ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game, Func<Move, bool> gameMoveValidator) { ChessUtilities.ThrowIfNull(from, "from"); List<Move> validMoves = new List<Move>(); Piece piece = game.GetPieceAt(from); int l0 = game.BoardHeight; int l1 = game.BoardWidth; for (int i = -7; i < 8; i++) { if (i == 0) continue; if (from.Rank + i > 0 && from.Rank + i <= l0) { Move move = new Move(from, new Position(from.File, from.Rank + i), piece.Owner); if (gameMoveValidator(move)) { validMoves.Add(move); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } if ((int)from.File + i > -1 && (int)from.File + i < l1) { Move move = new Move(from, new Position(from.File + i, from.Rank), piece.Owner); if (gameMoveValidator(move)) { validMoves.Add(move); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } } return new ReadOnlyCollection<Move>(validMoves); }
public List<String> Generate(ChessGame game) { var result = game.Info.Select(tag => "[" + tag.Key + " \"" + tag.Value + "\"]").ToList(); result.Add(""); result.Add(GenerateMovetext(game)); return result; }
public void Set(ChessGame g) { idx = -1; move = null; total_moves = 0; if (g == null) { player = ChessGamePlayer. CreatePlayer (); return; } player = g.HasTag ("FEN") ? ChessGamePlayer. CreateFromFEN (g. GetTagValue ("FEN", null)) : ChessGamePlayer.CreatePlayer (); game = g; int n = game.Moves.Count; if (n > 0) { total_moves = n; } if (total_moves == 0) hasNext = false; else hasNext = true; }
public static void TestAfter1e4() { ChessGame game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); string fen = game.GetFen(); Assert.AreEqual("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1", fen); }
public static void TestAfter1c5() { ChessGame game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("C7", "C5", Player.Black), true); string fen = game.GetFen(); Assert.AreEqual("rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2", fen); }
public override ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game, Func<Move, bool> gameMoveValidator) { ChessUtilities.ThrowIfNull(from, "from"); ReadOnlyCollection<Move> horizontalVerticalMoves = new Rook(Owner).GetValidMoves(from, returnIfAny, game, gameMoveValidator); if (returnIfAny && horizontalVerticalMoves.Count > 0) return horizontalVerticalMoves; ReadOnlyCollection<Move> diagonalMoves = new Bishop(Owner).GetValidMoves(from, returnIfAny, game, gameMoveValidator); return new ReadOnlyCollection<Move>(horizontalVerticalMoves.Concat(diagonalMoves).ToList()); }
public static void TestMovingWhiteKingLosingCastlingRights() { ChessGame game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("C7", "C5", Player.Black), true); game.ApplyMove(new Move("E1", "E2", Player.White), true); string fen = game.GetFen(); Assert.AreEqual("rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPPKPPP/RNBQ1BNR b kq - 1 2", fen); }
public static void TestMovingBlackKingLosingCastlingRights() { ChessGame game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("E7", "E5", Player.Black), true); game.ApplyMove(new Move("G1", "F3", Player.White), true); game.ApplyMove(new Move("E8", "E7", Player.Black), true); string fen = game.GetFen(); Assert.AreEqual("rnbq1bnr/ppppkppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQ - 2 3", fen); }
public static int GetIndexOnBoard(this GamePeice peice, ChessGame game) { for (var i = 0; i < game.Board.Count; i++) { if (game.Board[i].Equals(peice)) { return(i); } } return(-1); }
static void Main(string[] args) { // Let's start by creating a chess game instance. ChessGame game = new ChessGame(); // Now the game's board is in the start position and it's white's turn. Console.WriteLine("It's this color's turn: {0}", game.WhoseTurn); // This is how to find out which piece is at a certain position: Piece pieceAtA1 = game.GetPieceAt(new Position("A1")); // Or "a1", the casing doesn't matter /* There are other overloading options as well: * game.GetPieceAt(new Position(File.A, 1)); * game.GetPieceAt(File.A, 1); * All those three options return the same. */ Console.WriteLine("What piece is there at A1? {0}", pieceAtA1.GetFenCharacter()); // GetFenCharacter() returns the FEN character for the given piece. White piece: uppercase, black piece: lowercase. The character is the first char of a piece's name (exception: Knight -> N/n because King -> K/k). // The Piece class is the abstract base class for pieces. All piece classes (e.g. Rook) derive from this class. // White has to make a turn. They want to move their E2 pawn to E4. Is that valid? Move e2e4 = new Move("E2", "E4", Player.White); bool isValid = game.IsValidMove(e2e4); Console.WriteLine("E2-E4 for white is valid: {0}", isValid); // Great, it's valid! So white wants to actually make that move. MoveType type = game.ApplyMove(e2e4, true); // The first argument is the move, the second argument indicates whether it's already validated. Here it is, so pass 'true'. If it's not validated yet, ApplyMove will do it. **Only pass `true` if it's really validated! If you pass `true`, ApplyMove won't do ANY validity checks.** // The return type is the MoveType enum. It holds one, or a combination, of these values: Invalid, Move, Capture, Castling, Promotion // Each valid move will always carry the 'Move' value. If it's also something else, it will carry both values (e.g. if the move is a capture, `type` will have the value MoveType.Move | MoveType.Capture). // MoveType is a flags enumeration. https://msdn.microsoft.com/en-us/library/ms229062%28v=vs.100%29.aspx // e4 is just a normal move, so `type` will just be MoveType.Move. Console.WriteLine("Move type: {0}", type); // Now it's black's turn. Console.WriteLine("It's this color's turn: {0}", game.WhoseTurn); // You can figure out all valid moves using GetValidMoves. IEnumerable <Move> validMoves = game.GetValidMoves(Player.Black); // Here it returns all valid moves for black, but you can also find all valid moves *from a certain position* by passing a Position instance as argument. Console.WriteLine("How many valid moves does black have? {0}", validMoves.Count()); // It might happen that you don't really care about all valid moves, but just want to know if there are valid moves. Chess.NET also has a method for that: bool hasValidMoves = game.HasAnyValidMoves(Player.Black); // Again, you can also pass a Position instance here. Console.WriteLine("Black has any valid moves: {0}", hasValidMoves); // Congratulations! You have learned about the most important methods of Chess.NET. Enjoy using the library :) Console.ReadKey(); }
public ChessGame AppliedTo(ChessGame game) { Player prevPlayer = game.WhoseTurn == Player.White ? Player.Black : Player.White; var creationData = game.GetGameCreationData(); creationData.WhoseTurn = prevPlayer; creationData.CanWhiteCastleKingSide = CouldWhiteCastleKingSide; creationData.CanWhiteCastleQueenSide = CouldWhiteCastleQueenSide; creationData.CanBlackCastleKingSide = CouldBlackCastleKingSide; creationData.CanBlackCastleQueenSide = CouldBlackCastleQueenSide; creationData.FullMoveNumber = 1; creationData.HalfMoveClock = 1; creationData.EnPassant = OldEpSquare; bool isCastling = IsCastling(game); if (isCastling) { UndoCastling(creationData); } else { Piece movedPiece = new Pawn(prevPlayer); if (Move.Promotion == null) { movedPiece = game.GetPieceAt(Move.NewPosition); } if (movedPiece is Pawn && OldEpSquare == Move.NewPosition) { int offset = prevPlayer == Player.White ? 1 : -1; creationData.Board[8 - Move.NewPosition.Rank + offset][(int)Move.NewPosition.File] = CapturedPiece; creationData.Board[8 - Move.NewPosition.Rank][(int)Move.NewPosition.File] = null; creationData.Board[8 - Move.OriginalPosition.Rank][(int)Move.OriginalPosition.File] = movedPiece; } else { creationData.Board[8 - Move.NewPosition.Rank][(int)Move.NewPosition.File] = CapturedPiece; creationData.Board[8 - Move.OriginalPosition.Rank][(int)Move.OriginalPosition.File] = movedPiece; } } creationData.Moves = new DetailedMove[0]; // IT ADDS A PAWN MOVE IF EnPassant IS SET... WTF IS THIS LIBRARY... return(new ChessGame(creationData)); }
private void fENToolStripMenuItem_Click(object sender, EventArgs e) { var fenForm = new FenForm(); fenForm.FEN = ChessGame.GetFEN(); if (fenForm.ShowDialog(this) == DialogResult.OK) { ChessGame.LoadFEN(fenForm.FEN); panel1.Invalidate(); } }
public ActionResult <ChessGame> Post([FromBody] ChessGame chessGame) { if (chessGame == null) { return(BadRequest()); } appContext.ChessGames.Add(chessGame); appContext.SaveChanges(); return(Ok(chessGame)); }
public void PrintBoard(ChessGame game) { if (game.ActiveColor.IsWhite()) { PrintWhiteBoard(game.Board); } else { PrintBlackBoard(game.Board); } }
public static void TestMovingBlackKingLosingCastlingRights() { var game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("E7", "E5", Player.Black), true); game.ApplyMove(new Move("G1", "F3", Player.White), true); game.ApplyMove(new Move("E8", "E7", Player.Black), true); Assert.AreEqual("rnbq1bnr/ppppkppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQ - 2 3", game.GetFen()); }
public static void TestMovingBlackARookLosingCastlingRights() { var game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("A7", "A6", Player.Black), true); game.ApplyMove(new Move("G1", "F3", Player.White), true); game.ApplyMove(new Move("A8", "A7", Player.Black), true); Assert.AreEqual("1nbqkbnr/rppppppp/p7/8/4P3/5N2/PPPP1PPP/RNBQKB1R w KQk - 2 3", game.GetFen()); }
public static void TestMovingBlackHRookLosingCastlingRights() { var game = new ChessGame(); game.ApplyMove(new Move("E2", "E4", Player.White), true); game.ApplyMove(new Move("H7", "H6", Player.Black), true); game.ApplyMove(new Move("G1", "F3", Player.White), true); game.ApplyMove(new Move("H8", "H7", Player.Black), true); Assert.AreEqual("rnbqkbn1/pppppppr/7p/8/4P3/5N2/PPPP1PPP/RNBQKB1R w KQq - 2 3", game.GetFen()); }
public async Task <IActionResult> Create([Bind("Id,Fen,gameDate,userName")] ChessGame chessGame) { if (ModelState.IsValid) { _context.Add(chessGame); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(chessGame)); }
private void SaveAllFens(IEnumerable <ChessMove> moves, ChessGame game, FinalGameResult result) { Positions.Add(FenData.FromGameState(game, result)); foreach (var move in moves) { game.MakeMove(move, true); var fenData = FenData.FromGameState(game, result); Positions.Add(fenData); } }
public ChessGame Parse(IEnumerable<String> pgn, IChessMoveNotation moveNotation) { var lines = pgn.GetEnumerator(); var metainfo = ParseTags(lines); var movetext = ParseMovetext(lines); var game = new ChessGame(metainfo); foreach (ChessMove cm in ParseMoves(movetext, moveNotation, game.Players)) game.AddMove(cm); return game; }
public static void printCaptured(ChessGame game) { Console.WriteLine("Captured:"); Console.Write("White: "); printHash(game.Captured(Color.white)); Console.Write("Black: "); ConsoleColor aux = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; printHash(game.Captured(Color.black)); Console.ForegroundColor = aux; }
/** * Toggles the menu on each hand. If the menu button is pressed then the menu will * initialize on the hand which the button was pressed. The menu will disappear if * the menu button is pressed while the menu is active. */ void ToggleMenu(string side) { game = GameObject.Find("Chess_set").GetComponent <ChessGame>(); if (isMenuActive) { GameObject leftController = this.transform.Find("Controller (left)").gameObject; GameObject rightController = this.transform.Find("Controller (right)").gameObject; leftController.GetComponent <NVRExampleTeleporter>().enabled = true; rightController.GetComponent <NVRExampleTeleporter>().enabled = true; leftController.transform.Find("Menu").gameObject.SetActive(false); rightController.transform.Find("Menu").gameObject.SetActive(false); leftController.transform.GetComponent <ChessMenuPointer>().enabled = false; leftController.transform.GetComponent <ChessMenuPointer>().enabled = false; isMenuActive = false; sideActive = ""; } else { if (side == "left") { GameObject leftController = this.transform.Find("Controller (left)").gameObject; GameObject rightController = this.transform.Find("Controller (right)").gameObject; leftController.GetComponent <NVRExampleTeleporter>().enabled = false; rightController.GetComponent <NVRExampleTeleporter>().enabled = false; leftController.transform.Find("Menu").gameObject.SetActive(true); rightController.transform.GetComponent <ChessMenuPointer>().enabled = true; sideActive = "left"; } if (side == "right") { GameObject leftController = this.transform.Find("Controller (left)").gameObject; GameObject rightController = this.transform.Find("Controller (right)").gameObject; leftController.GetComponent <NVRExampleTeleporter>().enabled = false; rightController.GetComponent <NVRExampleTeleporter>().enabled = false; rightController.transform.Find("Menu").gameObject.SetActive(true); leftController.transform.GetComponent <ChessMenuPointer>().enabled = true; sideActive = "right"; } isMenuActive = true; } }
public ChessBoardHistoryEntry(ChessGame game) { GCD = game.GetGameCreationData(); if (GCD.Moves.Length > 0) { Move = GCD.Moves.Last(); GCD.Moves = new DetailedMove[1] { Move }; } }
private string GetCapturedPieces(ChessGame game, ChessColor color) { StringBuilder sb = new StringBuilder(); ChessPiece[] captured = game.Board.CapturedPieces.Where(p => p.Color == color).ToArray(); sb = new StringBuilder(); foreach (ChessPiece cap in captured) { sb.Append(cap.ToString() + " "); } return((sb.ToString() + new string(' ', 16)).Substring(0, 16)); }
protected virtual bool CanCastle(Position origin, Position destination, ChessGame game) { if (!HasCastlingAbility) return false; if (Owner == Player.White) { if (origin.File != File.E || origin.Rank != 1) return false; if (game.IsInCheck(Player.White)) return false; if (destination.File == File.C) { if (!game.CanWhiteCastleQueenSide || game.GetPieceAt(File.D, 1) != null || game.GetPieceAt(File.C, 1) != null || game.GetPieceAt(File.B, 1) != null || game.WouldBeInCheckAfter(new Move(new Position(File.E, 1), new Position(File.D, 1), Player.White), Player.White) || game.WouldBeInCheckAfter(new Move(new Position(File.E, 1), new Position(File.C, 1), Player.White), Player.White)) return false; } else { if (!game.CanWhiteCastleKingSide || game.GetPieceAt(File.F, 1) != null || game.GetPieceAt(File.G, 1) != null || game.WouldBeInCheckAfter(new Move(new Position(File.E, 1), new Position(File.F, 1), Player.White), Player.White) || game.WouldBeInCheckAfter(new Move(new Position(File.E, 1), new Position(File.G, 1), Player.White), Player.White)) return false; } } else { if (origin.File != File.E || origin.Rank != 8) return false; if (game.IsInCheck(Player.Black)) return false; if (destination.File == File.C) { if (!game.CanBlackCastleQueenSide || game.GetPieceAt(File.D, 8) != null || game.GetPieceAt(File.C, 8) != null || game.GetPieceAt(File.B, 8) != null || game.WouldBeInCheckAfter(new Move(new Position(File.E, 8), new Position(File.D, 8), Player.Black), Player.Black) || game.WouldBeInCheckAfter(new Move(new Position(File.E, 8), new Position(File.C, 8), Player.Black), Player.Black)) return false; } else { if (!game.CanBlackCastleKingSide || game.GetPieceAt(File.F, 8) != null || game.GetPieceAt(File.G, 8) != null || game.WouldBeInCheckAfter(new Move(new Position(File.E, 8), new Position(File.F, 8), Player.Black), Player.Black) || game.WouldBeInCheckAfter(new Move(new Position(File.E, 8), new Position(File.G, 8), Player.Black), Player.Black)) return false; } } return true; }
public void SetInitialPosition(string fen) { Entries.Clear(); Plies = 0; var game = new ChessGame(fen); Entries = new List <ChessBoardHistoryEntry> { new ChessBoardHistoryEntry(game) }; Entries[0].Move = null; }
public ChessForm() { InitializeComponent(); chessPanel.BackColor = Color.Gray; GamePoint.SIDE_LENGTH = chessPanel.Height / 8; if (chessPanel.Height != chessPanel.Width) { throw new Exception("Chess game needs a square panel"); } game = new ChessGame(chessPanel.Height); Invalidate(); }
/// <summary> /// Parse a rochade draw from the given PGN content. /// </summary> /// <param name="game">The chess game with all previous draws.</param> /// <param name="content">The PGN content to be parsed.</param> /// <returns>The parsed rochade draw</returns> private ChessDraw?parseRochade(ChessGame game, string content) { int row = (game.SideToDraw == ChessColor.White) ? 0 : 7; int column = content.Equals(LITTLE_ROCHADE) ? 6 : 2; var oldPos = new ChessPosition(row, 4); var newPos = new ChessPosition(row, column); ChessDraw?draw = new ChessDraw(game.Board, oldPos, newPos); return(draw); }
public Move GenerateMove(ChessGame game) { if (!game.HasAnyValidMoves(game.WhoseTurn)) { return(null); } var moves = game.GetValidMoves(game.WhoseTurn).ToList(); var randomIndex = random.Next(0, moves.Count); return(moves[randomIndex]); }
public override bool IsValidMove(Move move, ChessGame game) { ChessUtilities.ThrowIfNull(move, "move"); ChessUtilities.ThrowIfNull(game, "game"); Position origin = move.OriginalPosition; Position destination = move.NewPosition; PositionDistance posDelta = new PositionDistance(origin, destination); if ((posDelta.DistanceX != 2 || posDelta.DistanceY != 1) && (posDelta.DistanceX != 1 || posDelta.DistanceY != 2)) return false; return true; }
internal override bool IsValidGameMove(Move move, ChessGame board) { // No need to do null checks here, this method isn't public and isn't annotated with nullable. // If the caller try to pass a possible null reference, the compiler should issue a warning. // TODO: Should I add [NotNull] attribute to the arguments? What's the benefit? // The arguments are already non-nullable. int deltaX = move.GetAbsDeltaX(); int deltaY = move.GetAbsDeltaY(); return((deltaX == 1 && deltaY == 2) || (deltaX == 2 && deltaY == 1)); }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) { var sfd = new SaveFileDialog(); if (sfd.ShowDialog(this) == DialogResult.OK) { while (MoveForWards()) { } ChessGame.Save(sfd.FileName); } }
public static void Test960CastlingBlack2() { ChessGame game = new ChessGame("r1k3br/pppp2pp/2n2p2/8/7N/8/PKP2PPP/3R2BR b kq - 2 12"); Assert.True(game.IsValidMove(new Move("C8", "A8", Player.Black)), "Queenside castling should be valid."); Assert.False(game.IsValidMove(new Move("C8", "H8", Player.Black)), "Kingside castling should be invalid."); Assert.Contains(new Move("C8", "A8", Player.Black), game.GetValidMoves(Player.Black)); Assert.Contains(new Move("C8", "A8", Player.Black), game.GetValidMoves(new Position("C8"))); game.MakeMove(new Move("C8", "A8", Player.Black), true); Assert.AreEqual("2kr2br/pppp2pp/2n2p2/8/7N/8/PKP2PPP/3R2BR w - - 3 13", game.GetFen()); }
public void PromptCommand(ChessGame game) { Console.ForegroundColor = PromptColor; if (game != null && game.GameStatus == ChessGameStatus.ChessGameStatus_Playing) { Console.Write("Chess[" + game.GameName + "]:" + game.NextTurnPlayer.ToString() + ":> "); } else { Console.Write("Chess:> "); } Console.ResetColor(); }
public static void Test960CastlingWhite2() { ChessGame game = new ChessGame("bbrqknr1/pp1ppppp/6n1/2p5/4P3/5Q2/PPPP1PPP/BBR1KNRN w KQkq - 2 3"); Assert.True(game.IsValidMove(new Move("E1", "C1", Player.White)), "Queenside castling should be valid."); Assert.False(game.IsValidMove(new Move("E1", "G1", Player.White)), "Kingside castling should be invalid."); Assert.Contains(new Move("E1", "C1", Player.White), game.GetValidMoves(Player.White)); Assert.Contains(new Move("E1", "C1", Player.White), game.GetValidMoves(new Position("E1"))); game.MakeMove(new Move("E1", "C1", Player.White), true); Assert.AreEqual("bbrqknr1/pp1ppppp/6n1/2p5/4P3/5Q2/PPPP1PPP/BBKR1NRN b kq - 3 3", game.GetFen()); }
public static void Test960CastlingBlack1() { ChessGame game = new ChessGame("q1nbrk1r/pp2p1pp/2npbp2/8/4P3/1P3P2/P1PP1BPP/QNNBRRK1 b kq - 3 6"); Assert.True(game.IsValidMove(new Move("F8", "H8", Player.Black)), "Kingside castling should be valid."); Assert.False(game.IsValidMove(new Move("F8", "E8", Player.Black)), "Queenside castling should be invalid."); Assert.Contains(new Move("F8", "H8", Player.Black), game.GetValidMoves(Player.Black)); Assert.Contains(new Move("F8", "H8", Player.Black), game.GetValidMoves(new Position("F8"))); game.MakeMove(new Move("F8", "H8", Player.Black), true); Assert.AreEqual("q1nbrrk1/pp2p1pp/2npbp2/8/4P3/1P3P2/P1PP1BPP/QNNBRRK1 w - - 4 7", game.GetFen()); }
private void newToolStripMenuItem_Click(object sender, EventArgs e) { if ( MessageBox.Show(this, "Are you sure?", "New chess game", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { checkBoxAIblack.Checked = false; checkBoxAI_white.Checked = false; listView1.Items.Clear(); ChessGame.New(); panel1.Invalidate(); } }
public ActionResult <ChessGame> Delete(int id) { ChessGame chessGame = appContext.ChessGames.FirstOrDefault(x => x.Id == id); if (chessGame == null) { return(NotFound()); } appContext.ChessGames.Remove(chessGame); appContext.SaveChanges(); return(Ok(chessGame)); }
public static void TestCastling_KingE_RooksCF() { ChessGame game = new ChessGame("bnrbkrnq/pppppppp/8/8/8/8/PPPPPPPP/BNRBKRNQ w KQkq - 0 1"); string[] moves = { "b2b3", "h7h6", "a1b2", "g7g6", "b1a3", "e7e6", "c2c3", "d7d6", "d1c2", "c7c6", "g1f3", "b7b6", "h2h3", "a7a6", "h1h2", "f7f6" }; foreach (string m in moves) { game.MakeMove(new Move(m.Substring(0, 2), m.Substring(2, 2), game.WhoseTurn), true); } Assert.True(game.IsValidMove(new Move("E1", "C1", Player.White))); Assert.True(game.IsValidMove(new Move("E1", "F1", Player.White))); }
public window(bool isStandardChess) { boxes = new List <PictureBox>(64); InitializeComponent(); AddBoxes(); currentGame = new ChessGame(isStandardChess); //this.playerWhiteName.Text = firstName; //this.playerBlackName.Text = SecondName; RefreshItColors(); RefreshFigures(); isWhitePlayersTurn = true; }
public ServerManager(IPlayer whitePlayer, IPlayer blackPlayer) { this.whitePlayer = whitePlayer; this.blackPlayer = blackPlayer; whitePlayer.PlayerActedEvent += SetPlayerAct; blackPlayer.PlayerActedEvent += SetPlayerAct; chessGame = new ChessGame(); GameSituation gameSituation = chessGame.InitializeBoard(); whitePlayer.SetGameSituation(gameSituation); blackPlayer.SetGameSituation(gameSituation); }
public static void Test960CastlingWhite1() { ChessGame game = new ChessGame("qnbbrkr1/pppp1ppp/6n1/4p3/8/1P4N1/P1PPPPPP/QNBBRKR1 w KQkq - 1 3"); Assert.True(game.IsValidMove(new Move("F1", "G1", Player.White)), "Kingside castling should be valid."); Assert.False(game.IsValidMove(new Move("F1", "E1", Player.White)), "Queenside castling should be invalid."); Assert.Contains(new Move("F1", "G1", Player.White), game.GetValidMoves(Player.White)); Assert.Contains(new Move("F1", "G1", Player.White), game.GetValidMoves(new Position("F1"))); game.MakeMove(new Move("F1", "G1", Player.White), true); Assert.AreEqual("qnbbrkr1/pppp1ppp/6n1/4p3/8/1P4N1/P1PPPPPP/QNBBRRK1 b kq - 2 3", game.GetFen()); }
public override bool IsValidMove(Move move, ChessGame game) { ChessUtilities.ThrowIfNull(move, "move"); Position origin = move.OriginalPosition; Position destination = move.NewPosition; PositionDistance distance = new PositionDistance(origin, destination); if ((distance.DistanceX != 1 || distance.DistanceY != 1) && (distance.DistanceX != 0 || distance.DistanceY != 1) && (distance.DistanceX != 1 || distance.DistanceY != 0) && (distance.DistanceX != 2 || distance.DistanceY != 0)) return false; if (distance.DistanceX != 2) return true; return CanCastle(origin, destination, game); }
public override bool IsValidMove(Move move, ChessGame game) { bool validByStandardRules = base.IsValidMove(move, game); if (validByStandardRules) return true; if (move.OriginalPosition.Rank == 1 && move.NewPosition.Rank == 3 && move.OriginalPosition.File == move.NewPosition.File && game.GetPieceAt(move.NewPosition) == null && game.GetPieceAt(new Position(move.OriginalPosition.File, move.OriginalPosition.Rank + 1)) == null) // Horde pawns at the first rank can also move two squares on their first move. However, these can't be en-passant captured. { return true; } return false; }
public String GenerateMovetext(ChessGame game) { var movetext = new StringBuilder(); var moveCount = 1; foreach (var m in game.Moves) { if (moveCount % 2 == 1) movetext.Append((moveCount+1)/2 + ". "); movetext.Append(m + " "); moveCount++; } if (movetext.Length > 0) movetext.Remove(movetext.Length - 1, 1); return movetext.ToString(); }
public override bool IsValidMove(Move move, ChessGame game) { ChessUtilities.ThrowIfNull(move, "move"); ChessUtilities.ThrowIfNull(game, "game"); Position origin = move.OriginalPosition; Position destination = move.NewPosition; PositionDistance posDelta = new PositionDistance(origin, destination); if (posDelta.DistanceX != 0 && posDelta.DistanceY != 0) return false; bool increasingRank = destination.Rank > origin.Rank; bool increasingFile = (int)destination.File > (int)origin.File; if (posDelta.DistanceX == 0) { int f = (int)origin.File; for (int r = origin.Rank + (increasingRank ? 1 : -1); increasingRank ? r < destination.Rank : r > destination.Rank; r += increasingRank ? 1 : -1) { if (game.GetPieceAt((File)f, r) != null) { return false; } } } else // (posDelta.DeltaY == 0) { int r = origin.Rank; for (int f = (int)origin.File + (increasingFile ? 1 : -1); increasingFile ? f < (int)destination.File : f > (int)destination.File; f += increasingFile ? 1 : -1) { if (game.GetPieceAt((File)f, r) != null) { return false; } } } return true; }
public override ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game, Func<Move, bool> gameMoveValidator) { List<Move> validMoves = new List<Move>(); Piece piece = game.GetPieceAt(from); int l0 = game.BoardHeight; int l1 = game.BoardWidth; int[][] directions = new int[][] { new int[] { 2, 1 }, new int[] { -2, -1 }, new int[] { 1, 2 }, new int[] { -1, -2 }, new int[] { 1, -2 }, new int[] { -1, 2 }, new int[] { 2, -1 }, new int[] { -2, 1 } }; foreach (int[] dir in directions) { if ((int)from.File + dir[0] < 0 || (int)from.File + dir[0] >= l1 || from.Rank + dir[1] < 1 || from.Rank + dir[1] > l0) continue; Move move = new Move(from, new Position(from.File + dir[0], from.Rank + dir[1]), piece.Owner); if (gameMoveValidator(move)) { validMoves.Add(move); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } return new ReadOnlyCollection<Move>(validMoves); }
public override ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game, Func<Move, bool> gameMoveValidator) { ChessUtilities.ThrowIfNull(from, "from"); List<Move> validMoves = new List<Move>(); Piece piece = game.GetPieceAt(from); int l0 = game.BoardHeight; int l1 = game.BoardWidth; int[][] directions; if (piece.Owner == Player.White) { directions = new int[][] { new int[] { 0, 1 }, new int[] { 0, 2 }, new int[] { 1, 1 }, new int[] { -1, 1 } }; } else { directions = new int[][] { new int[] { 0, -1 }, new int[] { 0, -2 }, new int[] { -1, -1 }, new int[] { 1, -1 } }; } foreach (int[] dir in directions) { if ((int)from.File + dir[0] < 0 || (int)from.File + dir[0] >= l1 || from.Rank + dir[1] < 1 || from.Rank + dir[1] > l0) continue; Move move = new Move(from, new Position(from.File + dir[0], from.Rank + dir[1]), piece.Owner); List<Move> moves = new List<Move>(); if ((move.NewPosition.Rank == 8 && move.Player == Player.White) || (move.NewPosition.Rank == 1 && move.Player == Player.Black)) { foreach (char pieceChar in ValidPromotionPieces.Where(x => char.IsUpper(x))) { moves.Add(new Move(move.OriginalPosition, move.NewPosition, move.Player, pieceChar)); } } else { moves.Add(move); } foreach (Move m in moves) { if (gameMoveValidator(m)) { validMoves.Add(m); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } } return new ReadOnlyCollection<Move>(validMoves); }
protected void FireGameSelectionEvent(ChessGame details) { if (GameSelectionEvent != null) GameSelectionEvent (details); }
public static void TestValidMoveBlackPawn_TwoSteps() { ChessGame cb = new ChessGame(); cb.ApplyMove(new Move(new Position(File.A, Rank.Two), new Position(File.A, Rank.Three), Player.White), true); Move move1 = new Move(new Position(File.D, Rank.Seven), new Position(File.D, Rank.Five), Player.Black); Assert.True(cb.IsValidMove(move1), "move1 should be valid"); }
public override bool IsValidMove(Move move, ChessGame game) { ChessUtilities.ThrowIfNull(move, "move"); ChessUtilities.ThrowIfNull(game, "game"); Position origin = move.OriginalPosition; Position destination = move.NewPosition; Piece promotion = null; if (move.Promotion.HasValue && ValidPromotionPieces.Contains(move.Promotion.Value)) { promotion = game.MapPgnCharToPiece(char.ToUpper(move.Promotion.Value), move.Player); } PositionDistance posDelta = new PositionDistance(origin, destination); if ((posDelta.DistanceX != 0 || posDelta.DistanceY != 1) && (posDelta.DistanceX != 1 || posDelta.DistanceY != 1) && (posDelta.DistanceX != 0 || posDelta.DistanceY != 2)) return false; if (Owner == Player.White) { if (origin.Rank > destination.Rank) return false; if (destination.Rank == 8) { if (promotion == null) return false; if (promotion.Owner != Player.White) return false; if (!ValidPromotionPieces.Contains(promotion.GetFenCharacter())) return false; } } if (Owner == Player.Black) { if (origin.Rank < destination.Rank) return false; if (destination.Rank == 1) { if (promotion == null) return false; if (promotion.Owner != Player.Black) return false; if (!ValidPromotionPieces.Contains(promotion.GetFenCharacter())) return false; } } bool checkEnPassant = false; if (posDelta.DistanceY == 2) { if ((origin.Rank != 2 && Owner == Player.White) || (origin.Rank != 7 && Owner == Player.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; } Piece pieceAtDestination = game.GetPieceAt(destination); if (posDelta.DistanceX == 0 && (posDelta.DistanceY == 1 || posDelta.DistanceY == 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 == Player.White) || (origin.Rank != 4 && Owner == Player.Black)) return false; Move latestMove = _moves[_moves.Count - 1]; if (latestMove.Player != ChessUtilities.GetOpponentOf(Owner)) return false; if (!(game.GetPieceAt(latestMove.NewPosition) is Pawn)) return false; if (game.GetPieceAt(latestMove.NewPosition).Owner == Owner) return false; if (Owner == Player.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 void GameStart_Click(object sender, RoutedEventArgs e) { AI_Information ai_a = AI_Construct(WhiteComboBox); AI_Information ai_b = AI_Construct(BlackComboBox); ChessGame chessGameWindow = new ChessGame(this, ai_a, ai_b); chessGameWindow.Show(); this.Hide(); }
public void AddGame(ChessGame game, GameRating rating, out PGNGameDetails updated) { FindOrCreateGame (game, out updated); if (updated.Rating != rating) { updated.Rating = rating; SaveGame (updated); } }
public void SetGame(ChessGame game) { this.game = game; curMoveIdx = -1; Refresh (); }
public void AddGame(ChessGame game, out PGNGameDetails updated) { AddGame (game, GameRating.Unknown, out updated); }
public void SaveGameDetails(ChessGame game, out ChessGame updated, bool overrite) { if (!(game is PGNGameDetails)) game = new PGNGameDetails (game); PGNGameDetails updatedgame; AddGame (game, out updatedgame); // this will check for duplicates updated = updatedgame; }
public bool FindOrCreateGame(ChessGame game, out PGNGameDetails updated) { PGNGameDetails info; if (game is PGNGameDetails) info = (PGNGameDetails) game; else info = new PGNGameDetails (game); PGNGameDetails existing; if (!FindGame (info, out existing)) { info.ID = Config.Instance.NextID (); db.Set (info); Config.Instance.Save (); updated = info; return true; // created } updated = existing; return false; }
public static void TestInvalidMoveBlackPawn_EnPassant() { ChessGame cb = new ChessGame(); Move move1 = new Move(new Position(File.B, Rank.One), new Position(File.A, Rank.Three), Player.White); Move move2 = new Move(new Position(File.E, Rank.Seven), new Position(File.E, Rank.Five), Player.Black); Move move3 = new Move(new Position(File.E, Rank.Two), new Position(File.E, Rank.Three), Player.White); Move move4 = new Move(new Position(File.E, Rank.Five), new Position(File.E, Rank.Four), Player.Black); Move move5 = new Move(new Position(File.H, Rank.Two), new Position(File.H, Rank.Four), Player.White); Move move6 = new Move(new Position(File.E, Rank.Four), new Position(File.D, Rank.Three), Player.Black); cb.ApplyMove(move1, true); cb.ApplyMove(move2, true); cb.ApplyMove(move3, true); cb.ApplyMove(move4, true); cb.ApplyMove(move5, true); Assert.False(cb.IsValidMove(move6)); }
public bool GetGameDetails(ChessGame game, out ChessGame details) { PGNGameDetails gamedetails; if (!(game is PGNGameDetails)) gamedetails = new PGNGameDetails (game); else gamedetails = (PGNGameDetails) game; PGNGameDetails dbgame; bool ret = FindGame (gamedetails, out dbgame); details = dbgame; return ret; }
public static void TestValidMoveBlackPawn_Capture() { ChessGame cb = new ChessGame(); Move move1 = new Move(new Position(File.A, Rank.Two), new Position(File.A, Rank.Three), Player.White); Move move2 = new Move(new Position(File.E, Rank.Seven), new Position(File.E, Rank.Five), Player.Black); Move move3 = new Move(new Position(File.D, Rank.Two), new Position(File.D, Rank.Four), Player.White); Move move4 = new Move(new Position(File.E, Rank.Five), new Position(File.D, Rank.Four), Player.Black); cb.ApplyMove(move1, true); cb.ApplyMove(move2, true); cb.ApplyMove(move3, true); Assert.True(cb.IsValidMove(move4)); }