public List <ChessGame> getChessGames() { List <ChessGame> listToReturn = new List <ChessGame>(); string[] lines = System.IO.File.ReadAllLines(filePath); ChessGame currentGame = new ChessGame(); for (int i = 0; i < lines.Length; i++) { if (lines[i].StartsWith("1.")) { StringBuilder moves = new StringBuilder(); for (int j = i; j < lines.Length; j++) { moves.Append(lines[j]); i++; if (lines[j].EndsWith("1/2-1/2") || lines[j].EndsWith("1-0") || lines[j].EndsWith("0-1")) { moves.Append(lines[j]); break; } } currentGame.Moves = moves.ToString(); listToReturn.Add(currentGame); currentGame = new ChessGame(); } else if (lines[i].StartsWith("[Site ")) { string data = lines[i].Substring(5, lines[i].Length - 5); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.Site = data; } else if (lines[i].StartsWith("[Round ")) { string data = lines[i].Substring(6, lines[i].Length - 6); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.Round = data; } else if (lines[i].StartsWith("[WhiteElo ")) { string data = lines[i].Substring(9, lines[i].Length - 9); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.WhiteElo = Int32.Parse(data); } else if (lines[i].StartsWith("[BlackElo ")) { string data = lines[i].Substring(9, lines[i].Length - 9); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.BlackElo = Int32.Parse(data); } else if (lines[i].StartsWith("[White ")) { string data = lines[i].Substring(6, lines[i].Length - 6); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.White = data; } else if (lines[i].StartsWith("[Black ")) { string data = lines[i].Substring(6, lines[i].Length - 6); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.Black = data; } else if (lines[i].StartsWith("[Result ")) { string data = lines[i].Substring(7, lines[i].Length - 7); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); if (data == "1-0") { currentGame.Result = 'W'; } else if (data == "0-1") { currentGame.Result = 'B'; } else { currentGame.Result = 'D'; } } else if (lines[i].StartsWith("[EventDate ")) { string data = lines[i].Substring(10, lines[i].Length - 10); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.EventDate = data; } else if (lines[i].StartsWith("[Event ")) { string data = lines[i].Substring(6, lines[i].Length - 6); char[] trimChars = new char[3] { ' ', '"', ']' }; data = data.Trim(trimChars); currentGame.Event = data; } } return(listToReturn); }
// ReSharper disable once InconsistentNaming public static Dictionary <string, ChessEvent> .ValueCollection ParseEventsFromPGN(string fileName) { // Maps event names to their instances. var eventsMap = new Dictionary <string, ChessEvent>(); var file = new StreamReader(fileName); string line; while ((line = file.ReadLine()) != null) { if (line.StartsWith("[Event ")) { // Read all tags into metadata string. var metadataBuilder = new StringBuilder(line).AppendLine(); while (!string.IsNullOrWhiteSpace(line = file.ReadLine())) { metadataBuilder.AppendLine(line); } var metadata = metadataBuilder.ToString(); // Parse metadata. var eventName = EventNameRegex.Match(metadata).Groups[1].Value; var siteName = EventSiteNameRegex.Match(metadata).Groups[1].Value; var eventDate = EventDateRegex.Match(metadata).Groups[1].Value; var blackPlayerName = BlackPlayerRegex.Match(metadata).Groups[1].Value; var whitePlayerName = WhitePlayerRegex.Match(metadata).Groups[1].Value; var blackPlayerElo = int.Parse(BlackPlayerEloRegex.Match(metadata).Groups[1].Value); var whitePlayerElo = int.Parse(WhitePlayerEloRegex.Match(metadata).Groups[1].Value); var result = ResultRegex.Match(metadata).Groups[1].Value; // Find or create event. eventsMap.TryGetValue(eventName, out var chessEvent); if (chessEvent == null) { chessEvent = new ChessEvent { Name = eventName, Site = siteName, Date = eventDate }; eventsMap[eventName] = chessEvent; } // Create and assign game. var game = new ChessGame { Event = chessEvent }; game.setResult(result); chessEvent.Games.Add(game); // Read and set game moves. var gameMovesBuilder = new StringBuilder(); while (!string.IsNullOrWhiteSpace(line = file.ReadLine())) { gameMovesBuilder.Append(line); } game.Moves = gameMovesBuilder.ToString(); // Update and assign players. var blackPlayer = chessEvent.getOrCreatePlayer(blackPlayerName); blackPlayer.ELO = blackPlayer.ELO < blackPlayerElo ? blackPlayerElo : blackPlayer.ELO; game.BlackPlayer = blackPlayer; blackPlayer.Games.Add(game); var whitePlayer = chessEvent.getOrCreatePlayer(whitePlayerName); whitePlayer.ELO = whitePlayer.ELO < whitePlayerElo ? whitePlayerElo : whitePlayer.ELO; game.WhitePlayer = whitePlayer; whitePlayer.Games.Add(game); } } return(eventsMap.Values); }
/// <summary> /// Helper method that takes an array of game data and converts it to ChessGame objects /// </summary> /// <returns> List of ChessGame's obtained from PGN file </returns> private static List <ChessGame> GameBuilder(string[] readText) { List <ChessGame> rtnGames = new List <ChessGame>(); ChessGame tmpGame = new ChessGame(); Player tmpWhitePlayer = new Player(); Player tmpBlackPlayer = new Player(); int count = 0; bool firstSpace = false; foreach (string s in readText) { // Event if (Regex.Match(s, @"\bEvent\b", RegexOptions.IgnoreCase).Success) { // Used to indicate a new game - insert old game tmpGame.Event = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // Site else if (s.Contains("Site")) { tmpGame.Site = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // Round else if (s.Contains("Round")) { tmpGame.Round = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // ECO else if (s.Contains("ECO")) { tmpGame.ECO = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // WhitePlayer else if (Regex.Match(s, @"\bWhite\b", RegexOptions.IgnoreCase).Success) { tmpWhitePlayer.Name = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // BlackPlayer else if (Regex.Match(s, @"\bBlack\b", RegexOptions.IgnoreCase).Success) { tmpBlackPlayer.Name = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } // White Elo else if (s.Contains("WhiteElo")) { tmpWhitePlayer.Elo = Int32.Parse(Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", "")); } // Black Elo else if (s.Contains("BlackElo")) { tmpBlackPlayer.Elo = Int32.Parse(Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", "")); } // Result else if (s.Contains("Result")) { string gameResult = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); if (gameResult == "1/2-1/2") { tmpGame.Result = "D"; } else if (gameResult == "0-1") { tmpGame.Result = "B"; } else if (gameResult == "1-0") { tmpGame.Result = "W"; } } // EventDate else if (s.Contains("EventDate")) { string tmp = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); if (tmp.Contains("?")) { tmpGame.EventDate = "0000-00-00"; } else { tmp = tmp.Replace('.', '-'); tmpGame.EventDate = tmp; } } // EventDate else if (s.Contains("Date")) { string tmp = Regex.Match(s, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); if (tmp.Contains("?")) { tmpGame.Date = "0000-00-00"; } else { tmp = tmp.Replace('.', '-'); tmpGame.Date = tmp; } } // Moves else { if (s != "") { tmpGame.Moves += s; } else { if (!firstSpace) { firstSpace = true; } else { tmpGame.WhitePlayer = tmpWhitePlayer; tmpGame.BlackPlayer = tmpBlackPlayer; rtnGames.Add(tmpGame); tmpGame = new ChessGame(); tmpWhitePlayer = new Player(); tmpBlackPlayer = new Player(); firstSpace = false; } } } count++; } return(rtnGames); }
public static List <ChessGame> read(string filename) { var chessGames = new List <ChessGame>(); ChessGame chessGame = null; string[] lines = System.IO.File.ReadAllLines(filename); // Regex for tags Regex rx = new Regex(@"\[(?<tag>\w+).+""(?<value>.+)""]", RegexOptions.Compiled | RegexOptions.IgnoreCase); bool inMovesSection = false; foreach (string line in lines) { // Check line for tag MatchCollection matches = rx.Matches(line); string tag = ""; string value = ""; // If it contains a tag, then store the name and value if (matches.Count == 1) { GroupCollection groups = matches[0].Groups; tag = groups["tag"].Value; value = groups["value"].Value; } else // Otherwise we are beginning a moves sections or at the end of input { if (line.Length == 0) { inMovesSection = !inMovesSection; } else if (line.Length > 0 && inMovesSection) { if (chessGame.Moves == null) { chessGame.Moves = ""; } chessGame.Moves += line + "\r\n"; } } switch (tag) { case "Event": if (chessGame != null) { chessGames.Add(chessGame); } chessGame = new ChessGame(); chessGame.Event = value; break; case "Site": chessGame.Site = value; break; case "EventDate": chessGame.EventDate = value; break; case "Round": chessGame.Round = value; break; case "White": chessGame.White = value; break; case "Black": chessGame.Black = value; break; case "WhiteElo": chessGame.WhiteElo = uint.Parse(value); break; case "BlackElo": chessGame.BlackElo = uint.Parse(value); break; case "Result": switch (value) { case "1-0": chessGame.Result = 'W'; break; case "0-1": chessGame.Result = 'B'; break; case "1/2-1/2": chessGame.Result = 'D'; break; } break; default: break; } } if (chessGame != null) { chessGames.Add(chessGame); } return(chessGames); }
public List <ChessGame> ReadFromFile(string PGNfilename) { bool moveFlag = false; // Check if moves is being read ChessGame games = new ChessGame(); string[] readText = File.ReadAllLines(PGNfilename); // extract info from PGN files // Read line by line and check for tags foreach (var s in readText) { if (s.StartsWith("[Event")) { if (s.StartsWith("[EventDate")) { string[] temp = s.Split('\"'); games.EventDate = temp[1]; } else { string[] temp = s.Split('\"'); games.Event = temp[1]; } } else if (s.StartsWith("[Site")) { string[] temp = s.Split('\"'); games.Site = temp[1]; } else if (s.StartsWith("[White")) { if (s.StartsWith("[WhiteElo")) { string[] temp = s.Split('\"'); games.WhiteElo = temp[1]; } else { string[] temp = s.Split('\"'); games.White = temp[1]; } } else if (s.StartsWith("[Black")) { if (s.StartsWith("[BlackElo")) { string[] temp = s.Split('\"'); games.BlackElo = temp[1]; } else { string[] temp = s.Split('\"'); games.Black = temp[1]; } } else if (s.StartsWith("[Result")) { string[] temp = s.Split('\"'); if (temp[1].Equals("1-0")) { games.Result = "W"; } else if (temp[1].Equals("0-1")) { games.Result = "B"; } else if (temp[1].Equals("1/2-1/2")) { games.Result = "D"; } } else if (s.StartsWith("[Date")) { string[] temp = s.Split('\"'); games.Date = temp[1]; } else if (s.StartsWith("[Round")) { string[] temp = s.Split('\"'); games.Round = temp[1]; } else if (s.StartsWith("[ECO")) { string[] temp = s.Split('\"'); games.ECO = temp[1]; } // Start reading moves else if (s.StartsWith("1.") && moveFlag == false) { moveFlag = true; } // Read moves if (moveFlag) { // Keep storing moves until a new line is reached if (!string.IsNullOrEmpty(s)) { games.Moves += s; } // New line has reached, time to add the ChessGame to the list and create a new ChessGame to be added else { gamesList.Add(games); games = new ChessGame(); moveFlag = false; } } } return(new List <ChessGame>(gamesList)); }
/// <summary> /// Reads a text file containing one or more PGN format chess games /// and extracts the Event, Site, Date, player names, result, and moves /// of each game. /// </summary> /// <param name="filename">The full path to the file containing PGN data</param> /// <returns>A list of ChessGame, one for each in the input file</returns> public static List <ChessGame> ReadFromFile(string filename) { string[] fileContents = System.IO.File.ReadAllLines(filename); List <ChessGame> retval = new List <ChessGame>(); string _eventNombre = ""; string _site = ""; string _date = ""; string _whitePlayer = ""; string _blackPlayer = ""; char _result = 'b'; string _moves = ""; int spaces = 0; for (int i = 0; i < fileContents.Length; i++) { if (fileContents[i].StartsWith("[Event ")) { _eventNombre = parseString(fileContents[i]); } else if (fileContents[i].StartsWith("[Si")) { _site = parseString(fileContents[i]); } else if (fileContents[i].StartsWith("[Date ")) { _date = parseString(fileContents[i]); } else if (fileContents[i].StartsWith("[White ")) { _whitePlayer = parseString(fileContents[i]); } else if (fileContents[i].StartsWith("[Black ")) { _blackPlayer = parseString(fileContents[i]); } else if (fileContents[i].StartsWith("[Res")) { string parseQuotesFromResult = parseString(fileContents[i]); if (parseQuotesFromResult == "0-1") { _result = 'b'; } else if (parseQuotesFromResult == "1-0") { _result = 'w'; } else { _result = 'd'; } } else if (string.IsNullOrEmpty(fileContents[i])) { i++; int j = i; while ((!string.IsNullOrEmpty(fileContents[j]))) { _moves += fileContents[j]; j++; } spaces++; i = j; //create new game object ChessGame nextGame = new ChessGame(_eventNombre, _site, _date, _whitePlayer, _blackPlayer, _result, _moves); _moves = ""; //add game object to list of game objects retval.Add(nextGame); } } // TODO: Don't return an empty list return(retval); }
public List <ChessGame> ReadPGN(String path) { List <ChessGame> games = new List <ChessGame>(); if (File.Exists(path)) { String[] readText = File.ReadAllLines(path); int i = 0; while (i < readText.Length) { String each = readText[i]; ChessGame game = new ChessGame(); while (each.StartsWith("[")) { if (each.StartsWith("[EventDate")) { each = each.Substring(12, each.Length - 14); game.SetDate(each.Replace(".", "-")); i++; each = readText[i]; continue; } if (each.StartsWith("[Event")) { game.SetEventName(each.Substring(8, each.Length - 10)); i++; each = readText[i]; continue; } if (each.StartsWith("[Site")) { game.SetSite(each.Substring(7, each.Length - 9)); i++; each = readText[i]; continue; } if (each.StartsWith("[WhiteElo")) { game.SetWhiteElo(Convert.ToUInt32(each.Substring(11, each.Length - 13))); i++; each = readText[i]; continue; } if (each.StartsWith("[BlackElo")) { game.SetBlackElo(Convert.ToUInt32(each.Substring(11, each.Length - 13))); i++; each = readText[i]; continue; } if (each.StartsWith("[White")) { game.SetWhiteName(each.Substring(8, each.Length - 10)); i++; each = readText[i]; continue; } if (each.StartsWith("[Black")) { game.SetBlackName(each.Substring(8, each.Length - 10)); i++; each = readText[i]; continue; } if (each.StartsWith("[Result")) { String res = each.Substring(9, each.Length - 11); if (res.Equals("1-0")) { game.SetResult("W"); } else if (res.Equals("0-1")) { game.SetResult("B"); } else { game.SetResult("D"); } i++; each = readText[i]; continue; } else { i++; each = readText[i]; continue; } } String move = ""; i++; while (!String.IsNullOrEmpty(readText[i]) && i < readText.Length) { move = move + readText[i]; i++; } game.Setmoves(move); games.Add(game); i++; } } return(games); }
/// <summary> /// this method creates the list of games parsed from the PGN file /// </summary> /// <returns> returns a list of ChessGame instances </returns> public List <ChessGame> parse() { List <ChessGame> gamesList = new List <ChessGame>(); //opening the PGN file, reading it int othe tempGame ChessGame System.IO.StreamReader file = new System.IO.StreamReader(PGNFileName); string line; ChessGame tempGame = new ChessGame(); bool newgameFlag = false; while ((line = file.ReadLine()) != null) { if (newgameFlag) { tempGame = new ChessGame(); newgameFlag = false; } var field = getField(line); var value = getValue(line); switch (field) { case "Event": tempGame.Event = value; break; case "Site": tempGame.Site = value; break; case "GameDate": tempGame.GameDate = value; break; case "Round": tempGame.Round = value; break; case "WhitePlayerName": tempGame.WhitePlayerName = value; break; case "BlackPlayerName": tempGame.BlackPlayerName = value; break; case "Result": tempGame.Result = resultToChar(value);; break; case "EloWhite": tempGame.EloWhite = uint.Parse(value); break; case "EloBlack": tempGame.EloBlack = uint.Parse(value); break; case "EventDate": tempGame.EventDate = value; break; case "Moves": tempGame.Moves = line; // loop reads the following lines to add the rest of moves until find an empty new line while (!String.Equals((line = file.ReadLine()), "")) { tempGame.Moves += line; } // game is recorded in the list after moves are added and flag is set so a new temp game is created gamesList.Add(tempGame); newgameFlag = true; break; default: // for cases of spacing line, // the cases that we don't need the value // and other error lines we skip break; } } //throw new NotImplementedException(); return(gamesList); }
public List <ChessGame> parseFile(string filename) { List <ChessGame> Games = new List <ChessGame>(); try { using (StreamReader sr = new StreamReader(filename)) { string line; ChessGame currentGame = new ChessGame(); while ((line = sr.ReadLine()) != null) { if (Regex.Match(line, @"\bEvent\b", RegexOptions.IgnoreCase).Success) { currentGame.Event = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (line.Contains("Site")) { currentGame.Site = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (line.Contains("Round")) { currentGame.Round = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (Regex.Match(line, @"\bWhite\b", RegexOptions.IgnoreCase).Success) { currentGame.White = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (Regex.Match(line, @"\bBlack\b", RegexOptions.IgnoreCase).Success) { currentGame.Black = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (line.Contains("WhiteElo")) { currentGame.WhiteElo = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (line.Contains("BlackElo")) { currentGame.BlackElo = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } else if (line.Contains("Result")) { string result = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); if (result == "1/2-1/2") { currentGame.Result = 'D'; } else if (result == "1-0") { currentGame.Result = 'W'; } else if (result == "0-1") { currentGame.Result = 'B'; } } else if (line.Contains("EventDate")) { currentGame.EventDate = Regex.Match(line, "\"(.*?)]").ToString().Replace("\"", "").Replace("]", ""); } if (line == "") { string moves = ""; string gameLine; // Read until new line while ((gameLine = sr.ReadLine()) != "") { moves += gameLine; } currentGame.Moves = moves; Games.Add(currentGame); currentGame = new ChessGame(); } } } } catch (IOException) { Console.WriteLine("File cannot be read:"); } return(Games); }