//checks in all 4 directions to see if piece at (xFrom, yFrom) can move in that direction //if so, creates a board in that state and adds it to the list public static List <Board> GetMovesForPiece(Board state, int xFrom, int yFrom) { var movesFound = new List <Board>(); if (MoveIsPossible(state, xFrom, yFrom, xFrom + 1, yFrom + 1)) { sbyte[,] layout = state.CloneBoardState(); if (yFrom + 1 == 7)//back row reached, make piece into a king { layout[xFrom + 1, yFrom + 1] = Board.BlackKing; } else { layout[xFrom + 1, yFrom + 1] = layout[xFrom, yFrom]; } layout[xFrom, yFrom] = Board.Empty; movesFound.Add(new Board(layout)); } if (MoveIsPossible(state, xFrom, yFrom, xFrom - 1, yFrom + 1)) { sbyte[,] layout = state.CloneBoardState(); if (yFrom + 1 == 7)//back row reached, make piece into a king { layout[xFrom - 1, yFrom + 1] = Board.BlackKing; } else { layout[xFrom - 1, yFrom + 1] = layout[xFrom, yFrom]; } layout[xFrom, yFrom] = Board.Empty; movesFound.Add(new Board(layout)); } if (MoveIsPossible(state, xFrom, yFrom, xFrom - 1, yFrom - 1)) { sbyte[,] layout = state.CloneBoardState(); layout[xFrom - 1, yFrom - 1] = layout[xFrom, yFrom]; layout[xFrom, yFrom] = Board.Empty; movesFound.Add(new Board(layout)); } if (MoveIsPossible(state, xFrom, yFrom, xFrom + 1, yFrom - 1)) { sbyte[,] layout = state.CloneBoardState(); layout[xFrom + 1, yFrom - 1] = layout[xFrom, yFrom]; layout[xFrom, yFrom] = Board.Empty; movesFound.Add(new Board(layout)); } return(movesFound); }
//Moves piece at (xFrom, yFrom) to (xTo, yTo) and returns a board representing the new state public static Board ExecuteMove(Board state, int xFrom, int yFrom, int xTo, int yTo) { if (xTo < 0 || xTo >= 8 || yTo < 0 || yTo >= 8 || xFrom < 0 || xFrom >= 8 || yTo < 0 || yTo >= 8) { throw new InvalidOperationException("ExecuteMove method called with out-of-bounds coordinates"); } sbyte[,] layout = state.CloneBoardState(); layout[xTo, yTo] = layout[xFrom, yFrom]; //Move piece to new space layout[xFrom, yFrom] = Board.Empty; //Origin space is empty if (Math.Abs(xFrom - xTo) == 2 || Math.Abs(yFrom - yTo) == 2) //piece was captured, make this space empty too { layout[(xFrom + xTo) / 2, (yFrom + yTo) / 2] = Board.Empty; } Board result = new Board(layout); return(result); }