public Bitmap FindPieces(GameBoard gameBoard) { Bitmap board = BoardFinderViewModel.GetInstance().FindBoard(); // Hash the board and see if we've already processed this string boardHash = ImageUtils.ComputeImageHash(board); if (boardHash == this.LastBoardHash) { return(board); } this.LastBoardHash = boardHash; Bitmap parsedPieces = ImageUtils.PolarizeBlackWhite(ImageUtils.DiffBitmaps(BoardFinderViewModel.Board, ImageUtils.Clone(board))); if (parsedPieces == null) { this.BoardImage = null; return(parsedPieces); } this.BoardImage = ImageUtils.BitmapToBitmapImage(parsedPieces); int squareSize = BoardFinderViewModel.Board.Size.Width / GameBoard.SquareCount; for (int col = 0; col < GameBoard.SquareCount; col++) { for (int row = 0; row < GameBoard.SquareCount; row++) { Bitmap square = ImageUtils.Copy(parsedPieces, new Rectangle(row * squareSize, col * squareSize, squareSize, squareSize)); Bitmap bestMatch; string imageHash = ImageUtils.ComputeImageHash(square); if (this.ImageHashes.ContainsKey(imageHash)) { bestMatch = this.ImageHashes[imageHash]; } else { bestMatch = ImageUtils.BestTemplateMatch(new Bitmap[] { square }, this.AllPieces); this.ImageHashes.Add(imageHash, bestMatch); } if (bestMatch == this.WhitePawn) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Pawn, GamePiece.PieceColor.White); } else if (bestMatch == this.WhiteKnight) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Knight, GamePiece.PieceColor.White); } else if (bestMatch == this.WhiteBishop) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Bishop, GamePiece.PieceColor.White); } else if (bestMatch == this.WhiteRook) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Rook, GamePiece.PieceColor.White); } else if (bestMatch == this.WhiteQueen) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Queen, GamePiece.PieceColor.White); } else if (bestMatch == this.WhiteKing) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.King, GamePiece.PieceColor.White); } else if (bestMatch == this.BlackPawn) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Pawn, GamePiece.PieceColor.Black); } else if (bestMatch == this.BlackKnight) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Knight, GamePiece.PieceColor.Black); } else if (bestMatch == this.BlackBishop) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Bishop, GamePiece.PieceColor.Black); } else if (bestMatch == this.BlackRook) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Rook, GamePiece.PieceColor.Black); } else if (bestMatch == this.BlackQueen) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.Queen, GamePiece.PieceColor.Black); } else if (bestMatch == this.BlackKing) { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.King, GamePiece.PieceColor.Black); } else { gameBoard.UpdateSquare(row, col, GamePiece.PieceName.None, GamePiece.PieceColor.Empty); } } } this.BoardText = gameBoard.ToString(); return(board); }