/// <summary>Handles the Click event of the btnAdd control. Allows the user to add a new item.</summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void btnAdd_Click(object sender, RoutedEventArgs e) { var ibw = new InputBoxWindow("Enter the name for the new conference:"); if (ibw.ShowDialog() == true) { var name = InputBoxWindow.UserInput.Replace(':', '-'); if (MainWindow.Conferences.Any(conference => conference.Name == name)) { MessageBox.Show("There's already a conference with the name " + name + "."); return; } var usedIDs = new List<int>(); MainWindow.Conferences.ForEach(conference => usedIDs.Add(conference.ID)); var i = 0; while (usedIDs.Contains(i)) { i++; } MainWindow.Conferences.Add(new Conference { ID = i, Name = name }); var db = new SQLiteDatabase(MainWindow.CurrentDB); db.Insert("Conferences", new Dictionary<string, string> { { "ID", i.ToString() }, { "Name", name } }); lstData.ItemsSource = null; lstData.ItemsSource = MainWindow.Conferences; var confToEdit = new Conference(); foreach (Conference item in lstData.Items) { if (item.Name == name) { confToEdit = item; break; } } showEditConferenceWindow(confToEdit); } }
private async void btnSetMyLeadersCriteria_Click(object sender, RoutedEventArgs e) { var ibw = new InputBoxWindow( "Enter percentage (0-100) of team's games played the player must have " + "participated in (-1 not to use this criterion)", SQLiteIO.GetSetting("MyLeadersGPPct", "-1")); if (ibw.ShowDialog() == true) { SQLiteIO.SetSetting("MyLeadersGPPct", InputBoxWindow.UserInput); } ibw = new InputBoxWindow( "Enter minimum amount of minutes per game played by the player (-1 not to use this criterion)", SQLiteIO.GetSetting("MyLeadersMPG", "-1")); if (ibw.ShowDialog() == true) { SQLiteIO.SetSetting("MyLeadersMPG", InputBoxWindow.UserInput); } MainWindow.LoadMyLeadersCriteria(); await preparePlayerStats(); }
/// <summary> /// Handles the Click event of the btnChangeName control. Allows the user to update the team's displayName for the current /// season. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void btnChangeName_Click(object sender, RoutedEventArgs e) { if (cmbTeam.SelectedIndex == -1) { return; } if (MainWindow.Tf.IsBetween) { MessageBox.Show( "Please switch to a season timeframe before trying to change the name of a team.", App.AppName, MessageBoxButton.OK, MessageBoxImage.Information); return; } var newname = ""; try { while (true) { var ibw = new InputBoxWindow("Please enter the new name for the team", _tst[_curTeam].DisplayName); if (ibw.ShowDialog() != true) { return; } newname = InputBoxWindow.UserInput; if (_tst.Any(pair => pair.Value.DisplayName == newname)) { MessageBox.Show("A team already exists with that name."); } else { break; } } } catch { return; } var dict = new Dictionary<string, string> { { "DisplayName", newname } }; _db.Update(MainWindow.TeamsT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.PlTeamsT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.OppT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.PlOppT, dict, "Name LIKE \"" + _curTeam + "\""); var teamid = _curTeam; _tst[teamid].DisplayName = newname; _tstOpp[teamid].DisplayName = newname; MainWindow.TST = _tst; MainWindow.TSTOpp = _tstOpp; populateTeamsCombo(); cmbTeam.SelectedItem = newname; }
private void btnTimeLeftSet_Click(object sender, RoutedEventArgs e) { var ibw = new InputBoxWindow("Enter the time left:", SQLiteIO.GetSetting("LastTimeLeftSet", "0:00"), "NBA Stats Tracker"); if (ibw.ShowDialog() == false) { return; } var timeLeft = _timeLeft; try { timeLeft = ConvertTimeStringToDouble(InputBoxWindow.UserInput); } catch { return; } _timeLeft = timeLeft; updateTimeLeftIndication(_timeLeft); SQLiteIO.SetSetting("LastTimeLeftSet", InputBoxWindow.UserInput); }
/// <summary> /// Handles the Click event of the btnChangeName control. /// Allows the user to update the team's displayName for the current season. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void btnChangeName_Click(object sender, RoutedEventArgs e) { try { var ibw = new InputBoxWindow("Please enter the new name for the team", _tst[_curTeam].DisplayName); ibw.ShowDialog(); } catch { return; } string newname = InputBoxWindow.UserInput; var dict = new Dictionary<string, string> {{"DisplayName", newname}}; _db.Update(MainWindow.TeamsT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.PlTeamsT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.OppT, dict, "Name LIKE \"" + _curTeam + "\""); _db.Update(MainWindow.PlOppT, dict, "Name LIKE \"" + _curTeam + "\""); int teamid = _curTeam; _tst[teamid].DisplayName = newname; _tstOpp[teamid].DisplayName = newname; MainWindow.TST = _tst; MainWindow.TSTOpp = _tstOpp; populateTeamsCombo(); cmbTeam.SelectedItem = newname; }
private void btnShotClockSet_Click(object sender, RoutedEventArgs e) { var ibw = new InputBoxWindow( "Enter the shot clock left:", SQLiteIO.GetSetting("LastShotClockSet", "0.0"), "NBA Stats Tracker"); if (ibw.ShowDialog() == false) { return; } var shotClock = _shotClock; try { shotClock = ConvertTimeStringToDouble(InputBoxWindow.UserInput); } catch { return; } _shotClock = shotClock; updateShotClockIndication(_shotClock); SQLiteIO.SetSetting("LastShotClockSet", InputBoxWindow.UserInput); }
private void mnuMiscEditPeriods_Click(object sender, RoutedEventArgs e) { if (SQLiteIO.IsTSTEmpty()) { return; } while (true) { var ibw = new InputBoxWindow( "Insert the number of periods (e.g. quarters, halves, etc.) in a game (e.g. 4):", NumberOfPeriods.ToString()); if (ibw.ShowDialog() == true) { try { var input = Convert.ToInt32(InputBoxWindow.UserInput); if (input > 0) { NumberOfPeriods = input; break; } } catch (Exception) { return; } } } SQLiteIO.SetSetting("NumberOfPeriods", NumberOfPeriods); UpdateStatus("Number of Periods saved. Database updated."); }
private void mnuMiscEditShotClockDuration_Click(object sender, RoutedEventArgs e) { if (SQLiteIO.IsTSTEmpty()) { return; } while (true) { var ibw = new InputBoxWindow("Insert the shot clock duration (e.g. 24):", ShotClockDuration.ToString()); if (ibw.ShowDialog() == true) { try { var input = Convert.ToInt32(InputBoxWindow.UserInput); if (input > 0) { ShotClockDuration = input; break; } } catch (Exception) { return; } } } SQLiteIO.SetSetting("Shot Clock Duration", ShotClockDuration); UpdateStatus("Shot Clock Duration saved. Database updated."); }
/// <summary> /// Handles the Click event of the mnuMiscEditGameLength control. Allows the user to change the default game length in minutes /// used in statistical calculations and in the Box Score window. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void mnuMiscEditGameLength_Click(object sender, RoutedEventArgs e) { if (SQLiteIO.IsTSTEmpty()) { return; } var ibw = new InputBoxWindow( "Insert the length of each game in minutes, without overtime (e.g. 48):", GameLength.ToString()); if (ibw.ShowDialog() == true) { try { GameLength = Convert.ToInt32(InputBoxWindow.UserInput); } catch (Exception) { return; } } SQLiteIO.SetSetting("Game Length", GameLength); UpdateStatus("Game Length saved. Database updated."); }
/// <summary> /// Handles the Click event of the mnuMiscEditSeasonLength control. Allows the user to edit the season length used in statistical /// calculations. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void mnuMiscEditSeasonLength_Click(object sender, RoutedEventArgs e) { if (SQLiteIO.IsTSTEmpty()) { return; } var ibw = new InputBoxWindow("Insert the length of the season in games (etc. 82):", SeasonLength.ToString()); if (ibw.ShowDialog() == true) { try { SeasonLength = Convert.ToInt32(InputBoxWindow.UserInput); } catch (Exception) { return; } } SQLiteIO.SetSetting("Season Length", SeasonLength); UpdateStatus("Season Length saved. Database updated."); }
/// <summary> /// Handles the Click event of the btnDownloadBoxScore control. Allows the user to download and import a box score from /// Basketball-Reference.com. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void btnDownloadBoxScore_Click(object sender, RoutedEventArgs e) { var ibw = new InputBoxWindow("Enter the full URL of the box score you want to download"); if (ibw.ShowDialog() == true) { try { var result = BR.ImportBoxScore(InputBoxWindow.UserInput); if (result == -1) { MessageBox.Show( "The Box Score was saved, but some required players were missing.\nMake sure you're using an up-to-date downloaded database." + "\n\nThe database wasn't saved in case you want to reload it and try again."); } else { SQLiteIO.SaveSeasonToDatabase(); UpdateStatus("Box score downloaded and season saved!"); } } catch (Exception ex) { MessageBox.Show("Couldn't download & import box score.\n\nError: " + ex.Message); } } }
/// <summary>Handles the Click event of the mnuMiscRenameCurrentSeason control. Renames the current season.</summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void mnuMiscRenameCurrentSeason_Click(object sender, RoutedEventArgs e) { var curName = GetSeasonName(CurSeason); var ibw = new InputBoxWindow("Enter the new name for the current season", curName); ibw.ShowDialog(); if (!String.IsNullOrWhiteSpace(InputBoxWindow.UserInput)) { setSeasonName(CurSeason, InputBoxWindow.UserInput); cmbSeasonNum.SelectedValue = CurSeason; } }
/// <summary>Handles the Click event of the mnuMiscStartNewSeason control. Allows the user to add a new season to the database.</summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private async void mnuMiscStartNewSeason_Click(object sender, RoutedEventArgs e) { if (!SQLiteIO.IsTSTEmpty()) { var r = MessageBox.Show( "Are you sure you want to do this? This is an irreversible action.\nStats and box Scores will be retained, and you'll be able to use all the tool's features on them.", "NBA Stats Tracker", MessageBoxButton.YesNo, MessageBoxImage.Question); if (r == MessageBoxResult.Yes) { SQLiteIO.SaveSeasonToDatabase(); CurSeason = SQLiteIO.GetMaxSeason(CurrentDB); var ibw = new InputBoxWindow("Enter a name for the new season", (CurSeason + 1).ToString()); ibw.ShowDialog(); var seasonName = String.IsNullOrWhiteSpace(InputBoxWindow.UserInput) ? (CurSeason + 1).ToString() : InputBoxWindow.UserInput; var q = "alter table Teams rename to TeamsS" + CurSeason; DB.ExecuteNonQuery(q); q = "alter table PlayoffTeams rename to PlayoffTeamsS" + CurSeason; DB.ExecuteNonQuery(q); q = "alter table Opponents rename to OpponentsS" + CurSeason; DB.ExecuteNonQuery(q); q = "alter table PlayoffOpponents rename to PlayoffOpponentsS" + CurSeason; DB.ExecuteNonQuery(q); q = "alter table Players rename to PlayersS" + CurSeason; DB.ExecuteNonQuery(q); q = "alter table PlayoffPlayers rename to PlayoffPlayersS" + CurSeason; DB.ExecuteNonQuery(q); CurSeason++; SQLiteIO.PrepareNewDB(DB, CurSeason, CurSeason, true); DB.Insert("SeasonNames", new Dictionary<string, string> { { "ID", CurSeason.ToString() }, { "Name", seasonName } }); SeasonList.Add(new KeyValuePair<int, string>(CurSeason, seasonName)); foreach (var key in TST.Keys.ToList()) { var ts = TST[key]; for (var i = 0; i < ts.Totals.Length; i++) { ts.Totals[i] = 0; ts.PlTotals[i] = 0; } ts.Record[0] = 0; ts.Record[1] = 0; ts.PlRecord[0] = 0; ts.PlRecord[1] = 0; ts.CalcAvg(); TST[key] = ts; } foreach (var key in TSTOpp.Keys.ToList()) { var ts = TSTOpp[key]; for (var i = 0; i < ts.Totals.Length; i++) { ts.Totals[i] = 0; ts.PlTotals[i] = 0; } ts.Record[0] = 0; ts.Record[1] = 0; ts.PlRecord[0] = 0; ts.PlRecord[1] = 0; ts.CalcAvg(); TSTOpp[key] = ts; } foreach (var ps in PST) { for (var i = 0; i < ps.Value.Totals.Length; i++) { ps.Value.Totals[i] = 0; ps.Value.PlTotals[i] = 0; } ps.Value.IsAllStar = false; ps.Value.IsNBAChampion = false; if (ps.Value.Contract.Option == PlayerContractOption.Team2Yr) { ps.Value.Contract.Option = PlayerContractOption.Team; } else if (ps.Value.Contract.Option == PlayerContractOption.Team || ps.Value.Contract.Option == PlayerContractOption.Player) { ps.Value.Contract.Option = PlayerContractOption.None; } try { ps.Value.Contract.ContractSalaryPerYear.RemoveAt(0); } catch (ArgumentOutOfRangeException) { } ps.Value.CalcAvg(); } populateSeasonCombo(); SQLiteIO.SaveSeasonToDatabase(CurrentDB, TST, TSTOpp, PST, CurSeason, CurSeason); ChangeSeason(CurSeason); Tf = new Timeframe(CurSeason); IsEnabled = false; await UpdateAllData(); UpdateStatus("New season started. Database saved."); IsEnabled = true; } } }
public static void ImportOld(Dictionary<int, PlayerStats> pst, Dictionary<int, TeamStats> tst, string folder) { if (tst.Count != 30) { MessageBox.Show("Can't import previous player stats to a database that doesn't have 30 teams. Please import " + "your NBA 2K save once to this database to populate it properly before trying to import previous " + "player stats."); MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-2); return; } var list = new List<string> {"1 season ago"}; for (int i = 2; i <= 20; i++) { list.Add(i + " seasons ago"); } int startAt; var ccw = new ComboChoiceWindow("Add player stats staring from...", list); if (ccw.ShowDialog() != true) { MainWindow.MWInstance.mainGrid.Visibility = Visibility.Visible; return; } startAt = Convert.ToInt32(ComboChoiceWindow.UserChoice.Split(' ')[0]); var ibw = new InputBoxWindow( "Enter the current season (e.g. 2011-2012 by default in NBA 2K12, 2012 for a season" + " taking place only in that year, etc.):", "2011-2012"); if (ibw.ShowDialog() != true) { MainWindow.MWInstance.mainGrid.Visibility = Visibility.Visible; return; } int year; bool twoPartSeasonDesc = InputBoxWindow.UserInput.Contains("-"); try { year = Convert.ToInt32(twoPartSeasonDesc ? InputBoxWindow.UserInput.Split('-')[0] : InputBoxWindow.UserInput); } catch { MessageBox.Show("The year you entered (" + InputBoxWindow.UserInput + ") was not in a valid format.\nValid formats are:\n\t2012\n\t2011-2012"); MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-2); return; } var seasonNames = new Dictionary<int, string>(); for (int i = startAt; i <= 20; i++) { seasonNames.Add(i, twoPartSeasonDesc ? string.Format("{0}-{1}", year - i, (year - i + 1)) : (year - i).ToString()); } List<Dictionary<string, string>> teams; List<Dictionary<string, string>> players; List<Dictionary<string, string>> teamStats; List<Dictionary<string, string>> playerStats; if (populateREDitorDictionaryLists(folder, out teams, out players, out teamStats, out playerStats) == -1) { MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-1); return; } var legalTTypes = new List<string> {"0", "4"}; List<Dictionary<string, string>> validTeams = teams.FindAll(delegate(Dictionary<string, string> team) { if (legalTTypes.IndexOf(team["TType"]) != -1) { return true; } return false; }); List<Dictionary<string, string>> activeTeams = validTeams.FindAll(delegate(Dictionary<string, string> team) { if (team["StatCurS"] != "-1") { return true; } return false; }); if (activeTeams.Count < 30) { var dlw = new DualListWindow(validTeams, activeTeams); if (dlw.ShowDialog() == false) { MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-1); return; } activeTeams = new List<Dictionary<string, string>>(MainWindow.SelectedTeams); if (MainWindow.SelectedTeamsChanged) { CreateSettingsFile(activeTeams, folder); } } var activeTeamsIDs = new List<int>(); var rosters = new Dictionary<int, List<int>>(); foreach (var team in activeTeams) { int id = -1; string name = team["Name"]; if (tst.All(pair => pair.Value.Name != name)) { for (int i = 0; i < 30; i++) { if (!tst.ContainsKey(i)) { id = i; break; } } } else { id = tst.Single(pair => pair.Value.Name == name).Key; } activeTeamsIDs.Add(Convert.ToInt32(team["ID"])); rosters[id] = new List<int> { Convert.ToInt32(team["Ros_PG"]), Convert.ToInt32(team["Ros_SG"]), Convert.ToInt32(team["Ros_SF"]), Convert.ToInt32(team["Ros_PF"]), Convert.ToInt32(team["Ros_C"]) }; for (int i = 6; i <= 12; i++) { int cur = Convert.ToInt32(team["Ros_S" + i.ToString()]); if (cur != -1) { rosters[id].Add(cur); } else { break; } } for (int i = 13; i <= 20; i++) { int cur = Convert.ToInt32(team["Ros_R" + i.ToString()]); if (cur != -1) { rosters[id].Add(cur); } else { break; } } } List<Dictionary<string, string>> validPlayers = players.FindAll(delegate(Dictionary<string, string> player) { if (player["PlType"] == "4" || player["PlType"] == "5" || player["PlType"] == "6") { if ((player["IsFA"] == "0" && player["TeamID1"] != "-1") || (player["IsFA"] == "1")) { return true; } } return false; }); var pw = new ProgressWindow("Please wait as player career stats are being imported..."); pw.Show(); var bw = new BackgroundWorker {WorkerReportsProgress = true}; bw.DoWork += delegate { int count = validPlayers.Count; var ppsList = new List<PastPlayerStats>(); for (int i = 0; i < count; i++) { int percentProgress = i*100/count; if (percentProgress%5 == 0) { bw.ReportProgress(percentProgress); } Dictionary<string, string> player = validPlayers[i]; int playerID = Convert.ToInt32(player["ID"]); string lastName = player["Last_Name"]; string firstName = player["First_Name"]; int pTeam; var curTeam = new TeamStats(); try { pTeam = rosters.Single(r => r.Value.Contains(playerID)).Key; curTeam = tst[pTeam]; } catch (InvalidOperationException) { pTeam = -1; } if (!activeTeamsIDs.Contains(pTeam) && player["IsFA"] != "1") { if (pst.ContainsKey(playerID) && pst[playerID].LastName == lastName && pst[playerID].FirstName == firstName) { pst[playerID].IsActive = false; pst[playerID].TeamF = -1; pst[playerID].IsHidden = true; } continue; } if (pst.ContainsKey(playerID) && (pst[playerID].LastName != lastName || pst[playerID].FirstName != firstName)) { List<KeyValuePair<int, PlayerStats>> candidates = pst.Where( pair => pair.Value.LastName == lastName && pair.Value.FirstName == firstName && pair.Value.IsHidden == false).ToList(); if (candidates.Count > 0) { bool found = false; List<KeyValuePair<int, PlayerStats>> c2 = candidates.Where(pair => tst.ContainsKey(pair.Value.TeamF)).ToList(); if (c2.Count() == 1) { playerID = c2.First().Value.ID; found = true; } else { List<KeyValuePair<int, PlayerStats>> c4 = candidates.Where(pair => pair.Value.YearOfBirth.ToString() == player["BirthYear"]).ToList(); if (c4.Count == 1) { playerID = c4.First().Value.ID; found = true; } else { if (pTeam != -1) { List<KeyValuePair<int, PlayerStats>> c3 = candidates.Where(pair => pair.Value.TeamF == curTeam.ID).ToList(); if (c3.Count == 1) { playerID = c3.First().Value.ID; found = true; } } } } if (!found) { var choices = new List<string>(); foreach (var pair in candidates) { string choice = String.Format("{0}: {1} {2} (Born {3}", pair.Value.ID, pair.Value.FirstName, pair.Value.LastName, pair.Value.YearOfBirth); if (pair.Value.IsActive) { choice += String.Format(", plays in {0}", pair.Value.TeamF); } else { choice += ", free agent"; } choice += ")"; choices.Add(choice); } string message = String.Format("{0}: {1} {2} (Born {3}", player["ID"], player["First_Name"], player["Last_Name"], player["BirthYear"]); if (pTeam != -1) { message += String.Format(", plays in {0}", curTeam.DisplayName); } else { message += ", free agent"; } message += ")"; ccw = new ComboChoiceWindow(message, choices); if (ccw.ShowDialog() != true) { continue; } else { playerID = Convert.ToInt32(ComboChoiceWindow.UserChoice.Split(':')[0]); } } } else { continue; } } else if (!pst.ContainsKey(playerID)) { continue; } PlayerStats curPlayer = pst[playerID]; string qr = "SELECT * FROM PastPlayerStats WHERE PlayerID = " + playerID + " ORDER BY \"SOrder\""; DataTable dt = MainWindow.DB.GetDataTable(qr); dt.Rows.Cast<DataRow>().ToList().ForEach(dr => ppsList.Add(new PastPlayerStats(dr))); for (int j = startAt; j <= 20; j++) { string statEntryID = player["StatY" + j]; if (statEntryID == "-1") { break; } Dictionary<string, string> plStats = playerStats.Single(d => d["ID"] == statEntryID); var prevStats = new PastPlayerStats(); string teamID2 = plStats["TeamID2"]; string teamID1 = plStats["TeamID1"]; if (teamID2 == "-1") { if (teamID1 != "-1") { prevStats.TeamFName = teams.Single(team => team["ID"] == teamID1)["Name"]; } } else { prevStats.TeamFName = teams.Single(team => team["ID"] == teamID2)["Name"]; if (teamID1 != "-1") { prevStats.TeamSName = teams.Single(team => team["ID"] == teamID1)["Name"]; } } prevStats.GP = Convert.ToUInt16(plStats["GamesP"]); prevStats.GS = Convert.ToUInt16(plStats["GamesS"]); prevStats.MINS = Convert.ToUInt16(plStats["Minutes"]); prevStats.PTS = Convert.ToUInt16(plStats["Points"]); prevStats.DREB = Convert.ToUInt16(plStats["DRebs"]); prevStats.OREB = Convert.ToUInt16(plStats["ORebs"]); prevStats.AST = Convert.ToUInt16(plStats["Assists"]); prevStats.STL = Convert.ToUInt16(plStats["Steals"]); prevStats.BLK = Convert.ToUInt16(plStats["Blocks"]); prevStats.TOS = Convert.ToUInt16(plStats["TOs"]); prevStats.FOUL = Convert.ToUInt16(plStats["Fouls"]); prevStats.FGM = Convert.ToUInt16(plStats["FGMade"]); prevStats.FGA = Convert.ToUInt16(plStats["FGAtt"]); prevStats.TPM = Convert.ToUInt16(plStats["3PTMade"]); prevStats.TPA = Convert.ToUInt16(plStats["3PTAtt"]); prevStats.FTM = Convert.ToUInt16(plStats["FTMade"]); prevStats.FTA = Convert.ToUInt16(plStats["FTAtt"]); prevStats.PlayerID = playerID; prevStats.SeasonName = seasonNames[j]; prevStats.IsPlayoff = false; prevStats.Order = 20 - j; prevStats.EndEdit(); ppsList.Add(prevStats); } } bw.ReportProgress(99, "Please wait while the player career stats are being saved..."); SQLiteIO.SavePastPlayerStatsToDatabase(MainWindow.DB, ppsList); }; bw.RunWorkerCompleted += delegate { pw.CanClose = true; pw.Close(); MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(0); }; bw.ProgressChanged += delegate(object sender, ProgressChangedEventArgs args) { pw.SetProgressBarValue(args.ProgressPercentage); if (args.UserState != null) { pw.SetMessage(args.UserState.ToString()); } }; bw.RunWorkerAsync(); }
public static async Task ImportOldPlayerCareerStats( Dictionary<int, PlayerStats> pst, Dictionary<int, TeamStats> tst, string folder) { if (tst.Count != 30) { MessageBox.Show( "Can't import previous player stats to a database that doesn't have 30 teams. Please import " + "your NBA 2K save once to this database to populate it properly before trying to import previous " + "player stats."); MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-2); return; } List<Dictionary<string, string>> teams; List<Dictionary<string, string>> players; List<Dictionary<string, string>> teamStats; List<Dictionary<string, string>> playerStats; NBA2KVersion nba2KVersion; if (populateREDitorDictionaryLists(folder, out teams, out players, out teamStats, out playerStats, out nba2KVersion) == -1) { MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-1); return; } var list = new List<string> { "1 season ago" }; for (var i = 2; i <= 20; i++) { list.Add(i + " seasons ago"); } var ccw = new ComboChoiceWindow("Add player stats starting from...", list); if (ccw.ShowDialog() != true) { MainWindow.MWInstance.mainGrid.Visibility = Visibility.Visible; return; } var startAt = Convert.ToInt32(ComboChoiceWindow.UserChoice.Split(' ')[0]); var seasonNames = new Dictionary<int, string>(); if (nba2KVersion == NBA2KVersion.NBA2K12) { while (true) { var ibw = new InputBoxWindow( "Enter the season that describes the first season in this database (e.g. 2011-2012 by default in NBA 2K12, 2010-2011 if you " + "imported last year's stats first, 2012 for a season taking place only in that year, etc.):", "2011-2012"); if (ibw.ShowDialog() != true) { MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-2); return; } int year; var twoPartSeasonDesc = InputBoxWindow.UserInput.Contains("-"); try { year = Convert.ToInt32(twoPartSeasonDesc ? InputBoxWindow.UserInput.Split('-')[0] : InputBoxWindow.UserInput); } catch { MessageBox.Show( "The year you entered (" + InputBoxWindow.UserInput + ") was not in a valid format.\nValid formats are:\n\t2012\n\t2011-2012"); continue; } for (var i = startAt; i <= 20; i++) { seasonNames.Add( i, twoPartSeasonDesc ? string.Format("{0}-{1}", year - i, (year - i + 1)) : (year - i).ToString()); } break; } } initializeLegalTeamTypes(nba2KVersion); var validTeams = teams.FindAll( delegate(Dictionary<string, string> team) { if (legalTTypes.IndexOf(team["TType"]) != -1) { return true; } return false; }); var activeTeams = validTeams.FindAll( delegate(Dictionary<string, string> team) { if (team["StatCurS"] != "-1") { return true; } return false; }); if (activeTeams.Count < 30) { var dlw = new DualListWindow(validTeams, activeTeams); if (dlw.ShowDialog() == false) { MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(-1); return; } activeTeams = new List<Dictionary<string, string>>(MainWindow.SelectedTeams); if (MainWindow.SelectedTeamsChanged) { createSettingsFile(activeTeams, folder); } } var activeTeamsIDs = new List<int>(); var rosters = new Dictionary<int, List<int>>(); foreach (var team in activeTeams) { var id = -1; var name = team["Name"]; if (tst.All(pair => pair.Value.Name != name)) { for (var i = 0; i < 30; i++) { if (!tst.ContainsKey(i)) { id = i; break; } } } else { id = tst.Single(pair => pair.Value.Name == name).Key; } activeTeamsIDs.Add(Convert.ToInt32(team["ID"])); rosters[id] = new List<int> { Convert.ToInt32(team["Ros_PG"]), Convert.ToInt32(team["Ros_SG"]), Convert.ToInt32(team["Ros_SF"]), Convert.ToInt32(team["Ros_PF"]), Convert.ToInt32(team["Ros_C"]) }; for (var i = 6; i <= 12; i++) { var cur = Convert.ToInt32(team["Ros_S" + i.ToString()]); if (cur != -1) { rosters[id].Add(cur); } else { break; } } for (var i = 13; i <= 20; i++) { var cur = Convert.ToInt32(team["Ros_R" + i.ToString()]); if (cur != -1) { rosters[id].Add(cur); } else { break; } } } var validPlayers = players.FindAll(player => isValidPlayer(player, nba2KVersion)); var endAt = nba2KVersion >= NBA2KVersion.NBA2K13 ? 19 : 20; var pw = new ProgressWindow("Please wait as player career stats are being imported..."); pw.Show(); await Task.Run( () => { var count = validPlayers.Count; var ppsList = new List<PastPlayerStats>(); for (var i = 0; i < count; i++) { var percentProgress = i * 100 / count; if (percentProgress % 5 == 0) { Tools.AppInvoke(() => pw.SetProgressBarValue(percentProgress)); } var player = validPlayers[i]; var playerID = Convert.ToInt32(player["ID"]); var lastName = player["Last_Name"]; var firstName = player["First_Name"]; int pTeam; var curTeam = new TeamStats(); try { pTeam = rosters.Single(r => r.Value.Contains(playerID)).Key; curTeam = tst[pTeam]; } catch (InvalidOperationException) { pTeam = -1; } if (!activeTeamsIDs.Contains(pTeam) && player["IsFA"] != "1") { if (pst.ContainsKey(playerID) && pst[playerID].LastName == lastName && pst[playerID].FirstName == firstName) { pst[playerID].IsSigned = false; pst[playerID].TeamF = -1; pst[playerID].IsHidden = true; } continue; } #region Match Player if (pst.ContainsKey(playerID) && (pst[playerID].LastName != lastName || pst[playerID].FirstName != firstName)) { var candidates = pst.Where( pair => pair.Value.LastName == lastName && pair.Value.FirstName == firstName && pair.Value.IsHidden == false).ToList(); if (candidates.Count > 0) { var found = false; var c2 = candidates.Where(pair => tst.ContainsKey(pair.Value.TeamF)).ToList(); if (c2.Count() == 1) { playerID = c2.First().Value.ID; found = true; } else { var c4 = candidates.Where(pair => pair.Value.YearOfBirth.ToString() == player["BirthYear"]).ToList(); if (c4.Count == 1) { playerID = c4.First().Value.ID; found = true; } else { if (pTeam != -1) { var c3 = candidates.Where(pair => pair.Value.TeamF == curTeam.ID).ToList(); if (c3.Count == 1) { playerID = c3.First().Value.ID; found = true; } } } } if (!found) { var choices = new List<string>(); foreach (var pair in candidates) { var choice = String.Format( "{0}: {1} {2} (Born {3}", pair.Value.ID, pair.Value.FirstName, pair.Value.LastName, pair.Value.YearOfBirth); if (pair.Value.IsSigned) { choice += String.Format(", plays in {0}", pair.Value.TeamF); } else { choice += ", free agent"; } choice += ")"; choices.Add(choice); } var message = String.Format( "{0}: {1} {2} (Born {3}", player["ID"], player["First_Name"], player["Last_Name"], player["BirthYear"]); if (pTeam != -1) { message += String.Format(", plays in {0}", curTeam.DisplayName); } else { message += ", free agent"; } message += ")"; ccw = new ComboChoiceWindow(message, choices); if (ccw.ShowDialog() != true) { continue; } else { playerID = Convert.ToInt32(ComboChoiceWindow.UserChoice.Split(':')[0]); } } } else { continue; } } else if (!pst.ContainsKey(playerID)) { continue; } #endregion Match Player var qr = "SELECT * FROM PastPlayerStats WHERE PlayerID = " + playerID + " ORDER BY \"SOrder\""; var dt = MainWindow.DB.GetDataTable(qr); dt.Rows.Cast<DataRow>().ToList().ForEach(dr => ppsList.Add(new PastPlayerStats(dr))); for (var j = startAt; j < endAt; j++) { var statEntryID = player["StatY" + j]; if (statEntryID == "-1") { continue; } var stats = playerStats.Single(d => d["ID"] == statEntryID); var prevStats = new PastPlayerStats(); var teamID2 = stats["TeamID2"]; var teamID1 = stats["TeamID1"]; if (teamID2 == "-1") { if (teamID1 != "-1") { prevStats.TeamFName = teams.Single(team => team["ID"] == teamID1)["Name"]; } } else { prevStats.TeamFName = teams.Single(team => team["ID"] == teamID2)["Name"]; if (teamID1 != "-1") { prevStats.TeamSName = teams.Single(team => team["ID"] == teamID1)["Name"]; } } prevStats.GP = Convert.ToUInt16(stats["GamesP"]); prevStats.GS = Convert.ToUInt16(stats["GamesS"]); prevStats.MINS = Convert.ToUInt16(stats["Minutes"]); prevStats.PTS = Convert.ToUInt16(stats["Points"]); prevStats.DREB = Convert.ToUInt16(stats["DRebs"]); prevStats.OREB = Convert.ToUInt16(stats["ORebs"]); prevStats.AST = Convert.ToUInt16(stats["Assists"]); prevStats.STL = Convert.ToUInt16(stats["Steals"]); prevStats.BLK = Convert.ToUInt16(stats["Blocks"]); prevStats.TOS = Convert.ToUInt16(stats["TOs"]); prevStats.FOUL = Convert.ToUInt16(stats["Fouls"]); prevStats.FGM = Convert.ToUInt16(stats["FGMade"]); prevStats.FGA = Convert.ToUInt16(stats["FGAtt"]); try { prevStats.TPM = Convert.ToUInt16(stats["3PTMade"]); prevStats.TPA = Convert.ToUInt16(stats["3PTAtt"]); } catch (KeyNotFoundException) { prevStats.TPM = Convert.ToUInt16(stats["TPTMade"]); prevStats.TPA = Convert.ToUInt16(stats["TPTAtt"]); } prevStats.FTM = Convert.ToUInt16(stats["FTMade"]); prevStats.FTA = Convert.ToUInt16(stats["FTAtt"]); prevStats.PlayerID = playerID; var yearF = 0; if (nba2KVersion != NBA2KVersion.NBA2K12) { yearF = Convert.ToInt32(stats["Year"]); } prevStats.SeasonName = nba2KVersion == NBA2KVersion.NBA2K12 ? seasonNames[j] : String.Format("{0}-{1}", yearF - 1, yearF); prevStats.IsPlayoff = false; prevStats.Order = nba2KVersion == NBA2KVersion.NBA2K12 ? 20 - j : yearF; prevStats.EndEdit(); ppsList.Add(prevStats); } } Tools.AppInvoke( () => { pw.SetProgressBarValue(99); pw.SetMessage("Please wait while the player career stats are being saved..."); }); SQLiteIO.SavePastPlayerStatsToDatabase(MainWindow.DB, ppsList); }); pw.CanClose = true; pw.Close(); MainWindow.MWInstance.OnImportOldPlayerStatsCompleted(0); }