public void updateAttacksOnKing(ChessmanColor color) { attacksOnBlackKing = new List <Move>(); attacksOnWhiteKing = new List <Move>(); for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (boardState[row, col].piece != null && boardState[row, col].piece.GetType() != typeof(King) && boardState[row, col].piece.color != color) { List <Move> checkMoves = boardState[row, col].piece.getAvailableMoves(this).Where(m => m.toSpace == ((color == ChessmanColor.white) ? whiteKingPos : blackKingPos)).ToList(); if (checkMoves.Count > 0) { if (color == ChessmanColor.white) { attacksOnWhiteKing.AddRange(checkMoves); } else { attacksOnBlackKing.AddRange(checkMoves); } } } else if (boardState[row, col].piece != null && boardState[row, col].piece.GetType() == typeof(King) && boardState[row, col].piece.color != color) { // Add King on King Check Moves if the kigs are close to each other } } } }
public String printBoard(ChessmanColor color) { String boardStr = ""; if (color == ChessmanColor.black) { boardStr = " | H | G | F | E | D | C | B | A |".ToLower() + Environment.NewLine; for (int row = 7; row >= 0; row--) { boardStr += $"{8 - row} |"; for (int col = 7; col >= 0; col--) { boardStr += $" {boardState[row, col].ToString()} |"; } boardStr += Environment.NewLine; } } else if (color == ChessmanColor.white) { boardStr = " | A | B | C | D | E | F | G | H |".ToLower() + Environment.NewLine; for (int row = 0; row < 8; row++) { boardStr += $"{8 - row} |"; for (int col = 0; col < 8; col++) { boardStr += $" {boardState[row, col].ToString()} |"; } boardStr += Environment.NewLine; } } return(boardStr); }
public Rook(BoardSpace initPos, ChessmanColor color) { score = AIWeights.rookScore; position = initPos; this.color = color; whiteImage = Properties.Resources.WhiteRook; blackImage = Properties.Resources.BlackRook; }
public Bishop(BoardSpace initPos, ChessmanColor color) { score = AIWeights.bishopScore; position = initPos; this.color = color; whiteImage = Properties.Resources.WhiteBishop; blackImage = Properties.Resources.BlackBishop; }
public Pawn(BoardSpace initPos, ChessmanColor color) { score = AIWeights.pawnScore; position = initPos; this.color = color; whiteImage = Properties.Resources.WhitePawn; blackImage = Properties.Resources.BlackPawn; }
public Knight(BoardSpace initPos, ChessmanColor color) { score = AIWeights.knightScore; position = initPos; this.color = color; whiteImage = Properties.Resources.WhiteKnight; blackImage = Properties.Resources.BlackKnight; }
public King(BoardSpace initPos, ChessmanColor color) { score = AIWeights.queenScore; position = initPos; this.color = color; whiteImage = Properties.Resources.WhiteKing; blackImage = Properties.Resources.BlackKing; }
public static Move getBestMoveForBoard(Board gameBoard, ChessmanColor playerColor) { Move bestMove = null; List <Move> moveList = gameBoard.getAllAvailableMovesForPlayer(playerColor); Random rand = new Random(); moveList.Sort(); // Sort by highest score of piece killed int highestScore = moveList[0].score; List <Move> moveChoiceList = new List <Move>(); if (moveList.Count > 0) { if (gameBoard.isKingInCheck(playerColor)) { // Check if the King Has Valid Moves without Sacrafice foreach (Move mv in moveList) { if (mv.piece.GetType() == typeof(King)) { moveChoiceList.Add(mv); } } if (moveChoiceList.Count == 0) { // Check if you can kill All Attackers // No Valid King moves Sacrafice the Lowest Scoring Piece } } else { moveChoiceList = moveList.Where(c => c.score == highestScore).ToList(); } if (moveChoiceList.Count > 0) { bestMove = moveChoiceList[rand.Next(moveChoiceList.Count)]; } else { // No Valid Moves Stalemate } } return(bestMove); }
public List <Move> getAllAvailableMovesForPlayer(ChessmanColor color) { List <Move> moveList = new List <Move>(); for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (boardState[row, col].piece != null && boardState[row, col].piece.color == color) { moveList.AddRange(boardState[row, col].piece.getAvailableMoves(this)); } } } return(moveList); }
private void clockStateUpdated(Game sender, ChessmanColor color, int time) { if (this.InvokeRequired) { ClockUpdateDelegate d = new ClockUpdateDelegate(clockStateUpdated); this.Invoke(d, new object[] { sender, color, time }); } else { TimeSpan span = TimeSpan.FromMilliseconds(time); String timeStr = $"{((span.Hours != 0) ? $"{span.Hours.ToString("D2")}:" : "")}{((span.Minutes != 0 || span.Hours != 0 ) ? $"{(span.Minutes.ToString("D2"))}:" : "")}{((span.Seconds != 0 || (span.Minutes != 0 || span.Hours != 0)) ? $"{span.Seconds.ToString("D2")}" : "")}"; if (span.TotalMilliseconds == 0) { timeStr = "00:00:00"; } if (color == ChessmanColor.white) { if (sender.color == ChessmanColor.white) { playerClockTimeLbl.Text = timeStr; } else { oppClockTimeLbl.Text = timeStr; } } else { if (sender.color == ChessmanColor.black) { playerClockTimeLbl.Text = timeStr; } else { oppClockTimeLbl.Text = timeStr; } } } }
private Chessman GetOrCreateChessman(ChessmanColor color) { string key = color == ChessmanColor.Black ? BlackChessmanKey : WhiteChessmanKey; if (_chessman.ContainsKey(key)) { return(_chessman[key] as Chessman); } else { Chessman chessman; if (color == ChessmanColor.Black) { chessman = new BlackChessman(); } else { chessman = new WhiteChessman(); } _chessman.Add(key, chessman); return(chessman); } }
public Game(JObject json, String authToken) { aiContext = new AI(this); if (json != null) { Debug.WriteLine($"Game = {json.ToString()}"); clockUpdateTimer.Interval = tickInterval; clockUpdateTimer.Elapsed += clockTimerTick; fullId = (String)json["fullId"]; gameId = (String)json["gameId"]; color = (((String)json["color"]).ToLower() == "white") ? ChessmanColor.white : ChessmanColor.black; opponentName = (String)((JObject)json["opponent"])["username"]; opponentID = (String)((JObject)json["opponent"])["id"]; uciParser = new UCIParserContext(this); this.authToken = authToken; // generate Starting Board try { String fenStr = ((String)json["fen"]).ToString(); //gameBoard = new Board(fenStr); gameBoard = new Board(); } catch { gameBoard = new Board(); } if (json.ContainsKey("lastMove") && ((String)json["lastMove"]).Trim() != "") { lastMove = new Move((String)json["lastMove"], gameBoard, postMove: true); lastMove = new Move((String)json["lastMove"], gameBoard, postMove: true); } } }
public static List <Move> getMovesForBishop(Board boardState, ChessmanColor color, BoardSpace position) { List <Move> validMoveList = new List <Move>(); //Starting At Inital Position moves the 4 directions until the board is gone or a piece is reached char col = Convert.ToChar(position.position.Item1 + 1); int row = position.position.Item2 + 1; for (; row <= 8 && col <= 'H'; row++, col++) { // increasing Diagonal BoardSpace moveSpace = boardState.getSpace(col, row); if (moveSpace != null) { if (moveSpace.piece == null) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, 0)); } else if (moveSpace.piece.color != color) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, moveSpace.piece.score)); break; } else { break; } } } col = Convert.ToChar(position.position.Item1 - 1); row = position.position.Item2 - 1; for (; row >= 1 && col >= 'A'; row--, col--) { // increasing Diagonal BoardSpace moveSpace = boardState.getSpace(col, row); if (moveSpace != null) { if (moveSpace.piece == null) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, 0)); } else if (moveSpace.piece.color != color) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, moveSpace.piece.score)); break; } else { break; } } } col = Convert.ToChar(position.position.Item1 + 1); row = position.position.Item2 - 1; for (; row >= 1 && col <= 'H'; row--, col++) { // increasing Diagonal BoardSpace moveSpace = boardState.getSpace(col, row); if (moveSpace != null) { if (moveSpace.piece == null) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, 0)); } else if (moveSpace.piece.color != color) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, moveSpace.piece.score)); break; } else { break; } } } col = Convert.ToChar(position.position.Item1 - 1); row = position.position.Item2 + 1; for (; row <= 8 && col >= 'A'; row++, col--) { // increasing Diagonal BoardSpace moveSpace = boardState.getSpace(col, row); if (moveSpace != null) { if (moveSpace.piece == null) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, 0)); } else if (moveSpace.piece.color != color) { validMoveList.Add(new Move(position.piece, position, moveSpace, boardState, moveSpace.piece.score)); break; } else { break; } } } // Amend Scores for Pieces that Are now attacking this piece if (boardState.isKingInCheck(color)) { List <Move> afterCheckMoveList = getCheckBlockingMoves(boardState, validMoveList, color); validMoveList.Clear(); validMoveList.AddRange(afterCheckMoveList); } return(validMoveList); }
public bool isKingInCheck(ChessmanColor color) { return((color == ChessmanColor.white) ? attacksOnWhiteKing.Count > 0 : attacksOnBlackKing.Count > 0); }
public List <Move> getAttackingMovesOnKing(ChessmanColor color) { return((color == ChessmanColor.white) ? attacksOnWhiteKing : attacksOnBlackKing); }
public static List <Move> getCheckBlockingMoves(Board boardState, List <Move> possibleMoves, ChessmanColor color) { List <Move> validMoveList = new List <Move>(); List <Move> checkingMoves = boardState.getAttackingMovesOnKing(color); foreach (Move mv in checkingMoves) { foreach (Move pm in possibleMoves) { if (mv.toSpace == pm.toSpace) // can Sacrafice Life for King { validMoveList.Add(mv); } } } // Also Add in Moves that can Kill All Attackers if (checkingMoves.Count == 1) { // TODO Handle Killing an attacker also blocking other attackers. // Only handling single attackers for now. foreach (Move mv in checkingMoves) { foreach (Move pm in possibleMoves) { if (mv.fromSpace == pm.toSpace) // can Kill Lone Attacker on King { validMoveList.Add(mv); } } } } return(checkingMoves); }
public static ChessmanColor getOpponentColor(ChessmanColor playerColor) { return((playerColor == ChessmanColor.white) ? ChessmanColor.black : ChessmanColor.white); }
private void gameStateStreamHandler() { client.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {authToken}"); client.OpenReadCompleted += (sender, e) => { StreamReader reader = new StreamReader(e.Result); while (!reader.EndOfStream) { String tmp = reader.ReadLine(); if (tmp != "") { Console.WriteLine(tmp); JObject json = JObject.Parse(tmp); String msgType = (!json.ContainsKey("type")) ? null : $"{(String)json["type"]}"; try { if (msgType == "gameState") { this.uciParser.executeUCIOperation($"position startpos moves {(String)json["moves"]}"); int moveCount = ((String)json["moves"]).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count(); playerTurn = (moveCount % 2 == 0) ? ChessmanColor.white : ChessmanColor.black; if (moveCount > 0) { lastMove = new Move(((String)json["moves"]).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[moveCount - 1], gameBoard, postMove: true); } whiteClockTime = int.Parse((String)(json["wtime"])); blackClockTime = int.Parse((String)(json["btime"])); if (clockStateUpdated != null) { clockStateUpdated(this, ChessmanColor.white, whiteClockTime); clockStateUpdated(this, ChessmanColor.black, blackClockTime); } if (json.ContainsKey("status")) { GameStatus sts = GameStatus.unknown; if (Enum.TryParse(((String)json["status"]), true, out sts)) { gameStatus = sts; } else { gameStatus = GameStatus.unknown; } } if (json.ContainsKey("winner")) { winner = (((String)json["winner"]) == "white") ? ChessmanColor.white : ChessmanColor.black; handleGameOver(); } } else if (msgType == "gameFull") { // Is Inital State Message whiteClockTime = int.Parse((String)(((JObject)(json["state"]))["wtime"])); blackClockTime = int.Parse((String)(((JObject)(json["state"]))["btime"])); int moveCount = ((String)(((JObject)(json["state"]))["moves"])).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count(); if (moveCount > 0) { // Update Game Board Initial State this.uciParser.executeUCIOperation($"position startpos moves { ((String)(((JObject)(json["state"]))["moves"]))}"); lastMove = new Move(((String)(((JObject)(json["state"]))["moves"])).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[moveCount - 1], gameBoard, postMove: true); } playerTurn = (moveCount % 2 == 0) ? ChessmanColor.white : ChessmanColor.black; if (clockStateUpdated != null) { clockStateUpdated(this, ChessmanColor.white, whiteClockTime); clockStateUpdated(this, ChessmanColor.black, blackClockTime); } if (json.ContainsKey("status")) { GameStatus sts = GameStatus.unknown; if (Enum.TryParse(((String)(((JObject)(json["state"]))["status"])), true, out sts)) { gameStatus = sts; } else { gameStatus = GameStatus.unknown; } } if (json.ContainsKey("winner")) { winner = (((String)json["winner"]) == "white") ? ChessmanColor.white : ChessmanColor.black; handleGameOver(); } } clockUpdateTimer.Start(); clockUpdateTimer.Enabled = true; } catch { } // Fire Event for UI to refresh Display if (BoardUpdated != null) { BoardUpdated.Invoke(); } } } reader.Close(); }; client.OpenReadAsync(new Uri(Helper.apiBaseEndpoint + $"/bot/game/stream/{fullId}")); }