/// <summary> /// Writes a board (pure piece positions). /// </summary> /// <param name="writer">The file writer.</param> /// <param name="pieces">The list of pieces to write.</param> private void WriteBoard(StreamWriter writer, FriendlyPiecesList pieces) { writer.WriteLine(PersistenceConstants.BoardSection); for (var y = 0; y < 8; y++) { for (var x = 0; x < 8; x++) { var field = pieces.FirstOrDefault(p => p.Position == new Position(x + 1, 8 - y)); if (field == null) { writer.Write(PersistenceConstants.EmptyBoardField); } else { writer.Write(ColorConverter.GetSymbol(field.Color)); writer.Write(PieceConverter.GetSymbol(field.Type)); } writer.Write(" "); } writer.WriteLine(); } }
/// <summary> /// Loads <see cref="FriendlyBoard"/> object from the specified file. /// </summary> /// <param name="path">The path to file.</param> /// <exception cref="InvalidSectionValueException">Thrown when loaded section name has invalid value.</exception> /// <returns><see cref="FriendlyBoard"/> object loaded from the file.</returns> public FriendlyBoard Read(string path) { FriendlyPiecesList pieces = null; FriendlyCastling castling = null; FriendlyEnPassant enPassant = null; using (var reader = new StreamReader(path)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); if (line == null) { throw new InvalidSectionValueException(); } var lineAfterTrim = line.Trim(); if (lineAfterTrim.Length == 0) { continue; } switch (lineAfterTrim) { case PersistenceConstants.BoardSection: { pieces = ReadBoard(reader); break; } case PersistenceConstants.CastlingSection: { castling = ReadCastling(reader); break; } case PersistenceConstants.EnPassantSection: { enPassant = ReadEnPassant(reader); break; } default: { throw new InvalidSectionValueException(); } } } } return(new FriendlyBoard(pieces, castling, enPassant)); }
/// <summary> /// Reads a board (pure piece positions). /// </summary> /// <param name="reader">The file reader.</param> /// <exception cref="InvalidBoardValueException">Thrown when a loaded board state cannot be converted properly.</exception> /// <returns>The container object with the list of pieces.</returns> private FriendlyPiecesList ReadBoard(StreamReader reader) { var pieces = new FriendlyPiecesList(); for (var y = 0; y < 8; y++) { var line = reader.ReadLine(); if (line == null) { throw new InvalidBoardValueException(); } var lineAfterTrim = line.Trim(); var splitLine = lineAfterTrim.Split(' '); if (splitLine.Length != 8) { throw new InvalidBoardValueException(); } for (var x = 0; x < 8; x++) { if (splitLine[x] == PersistenceConstants.EmptyBoardField) { continue; } var position = new Position(x + 1, 8 - y); var color = ColorConverter.GetColor(splitLine[x][0]); var piece = PieceConverter.GetPiece(splitLine[x][1]); pieces.Add(new FriendlyPiece(position, piece, color)); } } return(pieces); }