forked from Zhetadelta/Blaseball-Livestream-Watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm1.cs
905 lines (783 loc) · 34 KB
/
Form1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Security.Permissions;
using System.Diagnostics;
using System.Drawing.Text;
using SocketIOClient;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
namespace Blaseball_Livestream
{
public partial class Form1 : Form
{
Client formClient;
AutoResetEvent waitHandle = new AutoResetEvent(false);
bool fileLoaded = false;
List<SaveGame> loadedFile = null;
public SelectedGame selectedGame = new SelectedGame();
public SelectedSeason selectedSeason = new SelectedSeason();
//TaskCompletionSource<bool> taskCompletionSource = null;
public Form1()
{
InitializeComponent();
}
String[] hitPhrases = { "Single", "Double", "Triple", "home run", "grand slam" };
private async void Form1_Load(object sender, EventArgs e)
{
formClient = new Client();
Thread.Sleep(1000);
List<Team> allTeams = await formClient.GetAllTeams();
while (allTeams == null)
{
Thread.Sleep(1000);
allTeams = await formClient.GetAllTeams();
}
allTeams.Sort();
foreach (Team t in allTeams)
{
listBox1.Items.Add(t);
}
listBox1.SetSelected(0, true);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void mainButtonLeft_Click(object sender, EventArgs e)
{
if (fileLoaded && listBox1.SelectedItem != null) { LoadPastGames(); }
}
private async void mainButtonR_Click(object sender, EventArgs e)
{
//taskCompletionSource?.TrySetResult(true);
ResetBox();
Team selected = listBox1.SelectedItem as Team;
Game liveGame = null;
List<Game> games = null;
while (true)
{
try
{
games = await formClient.GetSingleGamesUpdate();
break;
}
catch
{
Debug.WriteLine("Server error on getting list of games!");
}
}
foreach (Game game in games)
{
if (selected.fullName == game.awayTeamName || selected.fullName == game.homeTeamName)
{
liveGame = game;
}
}
if (liveGame == null) { Debug.WriteLine("Game from that team not found!"); return; }
SaveGame liveSaveGame = new SaveGame();
RunGame(liveGame, liveSaveGame);
}
private async void RunGame(Game gameArg, SaveGame liveSaveGame)
{
Uri uri = new Uri("https://blaseball.com");
SocketIO socket = new SocketIO(uri);
Game lastGameState = gameArg;
// Under construction; uncomment to try it out
//GameEventParser parser = new GameEventParser();
//parser.StartNewGame(gameArg);
socket.On("gameDataUpdate", (data) =>
{
List<ServerData> serverDataList = JsonConvert.DeserializeObject<List<ServerData>>(data.ToString());
foreach(Game game in serverDataList[0].schedule)
{
if(game._id == lastGameState._id && game.lastUpdate != lastGameState.lastUpdate)
{
UpdateGame(lastGameState, game, liveSaveGame);
// Under construction
//var result = parser.ParseGameUpdate(game);
//Console.WriteLine(result);
lastGameState = game;
}
}
});
while (true)
{
try
{
await socket.ConnectAsync();
break;
}
catch
{
Debug.WriteLine("Server error on connecting socket!");
}
}
//Initialize box score with current game state
liveGameTable.Visible = true;
string[] titleList = { "Bottom", " of ", (gameArg.inning + 1).ToString() };
if (gameArg.topOfInning) { titleList[0] = "Top"; }
liveGameTitle.Text = string.Concat(titleList);
if (gameArg.gameComplete)
{
liveGameTitle.Text = "Final";
SetVis(true, InningToLabel(8, true));
SetVis(true, InningToLabel(8, false));
}
liveGameAwayName.Text = gameArg.awayTeamNickname;
liveGameHomeName.Text = gameArg.homeTeamNickname;
int shift = 0;
if (gameArg.inning >= 9 ) { SlideInnings(gameArg.inning); shift = gameArg.inning - 8; } //makes space for extra innings
topR.Text = gameArg.awayScore.ToString();
botR.Text = gameArg.homeScore.ToString();
Label initScore = InningToLabel(gameArg.inning - shift, true);
Label initScoreBot = InningToLabel(gameArg.inning - shift, false);
initScore.Text = gameArg.awayScore.ToString();
initScore.Visible = true;
initScoreBot.Text = gameArg.homeScore.ToString();
if (!gameArg.topOfInning & gameArg.inning == 0) { initScoreBot.Visible = true; }
//copy info from game in progress to saveable state
liveSaveGame.awayScore = gameArg.awayScore;
liveSaveGame.homeScore = gameArg.homeScore;
liveSaveGame.homeTeamNickname = gameArg.homeTeamNickname;
liveSaveGame.awayTeamNickname = gameArg.awayTeamNickname;
liveSaveGame._id = gameArg._id;
//taskCompletionSource = new TaskCompletionSource<bool>();
//await taskCompletionSource.Task;
//await socket.DisconnectAsync();
}
//Threadsafe text setting for labels
delegate void SetTextCallback(string text, Label label);
private void SetText(string text, Label label)
{
if (label.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
label.Invoke(d, new object[] { text, label });
}
else
{
label.Text = text;
}
}
private void SetTitle(bool topOfInning, int inningNum)
{
string[] titleList = { "Bottom", " of ", (inningNum + 1).ToString() };
if (topOfInning) { titleList[0] = "Top"; }
SetText(string.Concat(titleList), liveGameTitle);
}
//Threadsafe visibility setting for labesl
delegate void SetVisCallback(bool vis, Control label);
private void SetVis(bool vis, Control label)
{
if (label.InvokeRequired)
{
SetVisCallback d = new SetVisCallback(SetVis);
label.Invoke(d, new object[] { vis, label });
}
else
{
label.Visible = vis;
}
}
private void UpdateGame(Game oldState, Game newState, SaveGame saveGame)
{
int shift = 0;
if(newState.inning >= 9 && newState.inning != oldState.inning) { SlideInnings(newState.inning); shift = newState.inning - 8; } //changes inning 9 to latest inning
//Check for hits, add to save game counter
Label hitLabel = null;
foreach(string hitPhrase in hitPhrases)
{
if (newState.lastUpdate.Contains(hitPhrase))
{
hitLabel = botH;
if (newState.topOfInning)
{
saveGame.awayHits += 1;
hitLabel = topH;
}
else { saveGame.homeHits += 1; }
}
}
if(hitLabel != null)
{
SetText((Convert.ToInt16(hitLabel.Text) + 1).ToString(), hitLabel);
}
//Check for runs
if(newState.homeScore != oldState.homeScore)
{
SetText(newState.homeScore.ToString(), botR);
//botR.Text = newState.homeScore.ToString();
Label halfInningLabel = InningToLabel(newState.inning - shift, false);
SetVis(true, halfInningLabel);
//halfInningLabel.Visible = true;
SetText((Convert.ToInt16(halfInningLabel.Text)+newState.homeScore-oldState.homeScore).ToString(), halfInningLabel);
saveGame.homeScore = newState.homeScore;
}
if (newState.awayScore != oldState.awayScore)
{
SetText(newState.awayScore.ToString(), topR);
//topR.Text = newState.awayScore.ToString();
Label halfInningLabel = InningToLabel(newState.inning - shift, true);
SetVis(true, halfInningLabel);
SetText((Convert.ToInt16(halfInningLabel.Text) + newState.awayScore - oldState.awayScore).ToString(), halfInningLabel);
saveGame.awayScore = newState.awayScore;
}
//Display zero if inning changeover with no runs
if(newState.topOfInning != oldState.topOfInning)
{
int inning = newState.inning;
if (newState.topOfInning && newState.inning <= 8) { inning -= 1; }
Label labelCheck = InningToLabel(inning, !newState.topOfInning);
SetTitle(newState.topOfInning, newState.inning);
SetVis(true, labelCheck);
}
//Change title and add zeros for end of game
if (newState.gameComplete)
{
SetText("Final", liveGameTitle);
SetVis(true, InningToLabel(8, true));
SetVis(true, InningToLabel(8, false));
//Run game save routine
SaveGameToFile(saveGame);
}
}
private void SlideInnings(int extraInnings) //makes space for extra innings
{
Label[] labels = { InningToLabel(8, true), InningToLabel(8, false), label9 };
SetText("0", labels[0]);
SetText("0", labels[1]);
SetText((extraInnings+1).ToString(), labels[2]);
}
private Label InningToLabel(int inning, bool topOfInning)
{
string front = "bot";
if (topOfInning) { front = "top"; }
inning += 1;
if(inning >= 10) { inning = 9; }
return this.Controls.Find(string.Concat(front, inning.ToString()), true).FirstOrDefault() as Label;
}
private void SaveGameToFile(SaveGame saveGame)
{
}
private void UpdateWatchedGame(List<SaveGame> games, Game gameUpdate)
{
SaveGame thisGame = null;
SaveGame newGame = new SaveGame();
foreach (SaveGame game in games)
{
if(game._id == gameUpdate._id)
{
thisGame = game;
}
}
if(thisGame == null) //if game not found, initialize with same ID
{
newGame._id = gameUpdate._id;
newGame.inningsList = new List<Inning>();
newGame.inningsList.Add(new Inning());
newGame.inningsList[0].number = gameUpdate.inning + 1;
newGame.topOfInning = true;
newGame.homeTeamNickname = gameUpdate.homeTeamNickname;
newGame.awayTeamNickname = gameUpdate.awayTeamNickname;
games.Add(newGame);
thisGame = newGame;
}
if(thisGame.lastUpdate == gameUpdate.lastUpdate) { return; } //Leave, nothing to do
Inning thisInning;
thisGame.inningsList.Sort();
thisInning = thisGame.inningsList.Last();
if (thisGame.topOfInning != gameUpdate.topOfInning)
{
if (gameUpdate.topOfInning)
{
thisInning = new Inning();
thisInning.number = gameUpdate.inning + 1;
thisGame.inningsList.Add(thisInning);
}
}
//check for hits, add to game total
foreach(string hitPhrase in hitPhrases)
{
if (gameUpdate.lastUpdate.Contains(hitPhrase))
{
if (gameUpdate.topOfInning) { thisGame.awayHits += 1; }
else thisGame.homeHits += 1;
}
}
//check for runs, add to game and inning total
int homeScoreDiff = gameUpdate.homeScore - thisGame.homeScore;
int awayScoreDiff = gameUpdate.awayScore - thisGame.awayScore;
if (homeScoreDiff > 0)
{
thisGame.homeScore = gameUpdate.homeScore;
thisInning.homeScore += homeScoreDiff;
}
else if (awayScoreDiff > 0)
{
thisGame.awayScore = gameUpdate.awayScore;
thisInning.awayScore += awayScoreDiff;
}
thisGame.topOfInning = gameUpdate.topOfInning;
thisGame.lastUpdate = gameUpdate.lastUpdate;
}
private async void SaveAllGamesToFile(SaveFileDialog fileDialog)
{
List<SaveGame> currentWatchedGames = new List<SaveGame>();
Uri uri = new Uri("https://blaseball.com");
SocketIO socket = new SocketIO(uri);
bool roundStarted = false;
bool allCompleted = false;
socket.On("gameDataUpdate", (data) =>
{
List<ServerData> serverDataList = JsonConvert.DeserializeObject<List<ServerData>>(data.ToString());
List<Game> games = serverDataList[0].schedule;
bool activeGame = !roundStarted;
bool indicatorFlipped = false;
foreach (Game game in serverDataList[0].schedule)
{
if (!game.gameComplete && !roundStarted) { roundStarted = true; } //mark round as started, start watching for all games completed
if (roundStarted && !activeGame) { activeGame = !game.gameComplete; } //if round has started and no active game found yet, set flag if this game is active
if(!game.gameComplete && roundStarted) //if this game is currently active and round as started, record thing
{
bool found = false;
foreach(SaveGame checkGame in currentWatchedGames)
{
if (game._id == checkGame._id)
{
found = true;
checkGame.UpdateSaveGame(game);
}
}
if (!found)
{
currentWatchedGames.Add(new SaveGame(game));
}
}
}
allCompleted = !activeGame;
if(!indicatorFlipped && roundStarted) { SetText("Recording...", recordIndicator); indicatorFlipped = true; }
if (allCompleted)
{
foreach(SaveGame saveGame in currentWatchedGames)
{
saveGame.gameComplete = true;
}
waitHandle.Set();
}
});
await socket.ConnectAsync();
waitHandle.WaitOne();
LoadFileToAppend(fileDialog.FileName, currentWatchedGames);
JsonSerializer serializer = new JsonSerializer();
using (Stream fileStreamBytes =
fileDialog.OpenFile())
{
using (StreamWriter fileStream =
new StreamWriter(fileStreamBytes))
{
serializer.Serialize(fileStream, currentWatchedGames);
}
}
SetVis(false, recordIndicator);
MessageBox.Show("All games completed!");
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(StartWatching);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
private void StartWatching()
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "Save New File";
fileDialog.DefaultExt = "prestige";
fileDialog.Filter = "Visualizer files (*.prestige)|*.prestige|All files(*.*)|*.*";
fileDialog.OverwritePrompt = true;
fileDialog.AddExtension = true;
fileDialog.ShowDialog();
if (fileDialog.FileName == "") { return; } //if no file selected, abort
SetVis(true, recordIndicator);
SetText("Waiting to record...", recordIndicator);
SaveAllGamesToFile(fileDialog);
}
private void button2_Click(object sender, EventArgs e)
{
fileLoaded = false;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Recorded Games File";
fileDialog.CheckFileExists = true;
fileDialog.DefaultExt = ".prestige";
fileDialog.Filter = "Visualizer files (*.prestige)|*.prestige|All files(*.*)|*.*";
fileDialog.ShowDialog();
bool loadedNow = false;
try
{
using (StreamReader file = File.OpenText(fileDialog.FileName))
{
JsonSerializer serializer = new JsonSerializer();
loadedFile = (List<SaveGame>)serializer.Deserialize(file, typeof(List<SaveGame>));
loadedNow = true;
}
}
catch
{
MessageBox.Show("File could not be loaded!");
return;
}
if (!loadedNow)
{
MessageBox.Show("File could not be loaded!");
return;
}
SetVis(true, loadedIndicator);
fileLoaded = true;
}
private void ResetBox()
{
IEnumerable<int> inningNums = Enumerable.Range(0, 9);
foreach (int num in inningNums)
{
Label top = InningToLabel(num, true);
Label bot = InningToLabel(num, false);
SetVis(false, top);
SetVis(false, bot);
SetText("0", top);
SetText("0", bot);
}
SetText("0", topR);
SetText("0", botR);
SetText("0", topH);
SetText("0", botH);
}
private void LoadPastGames()
{
ResetBox();
if (!fileLoaded) { MessageBox.Show("No file loaded!"); return; }
List<SaveGame> thisTeamGames = new List<SaveGame>();
SaveGame thisGame;
Team selectedTeam = listBox1.SelectedItem as Team;
foreach (SaveGame game in loadedFile)
{
if (selectedTeam.nickname == game.awayTeamNickname || selectedTeam.nickname == game.homeTeamNickname)
{
thisTeamGames.Add(game);
}
}
if (thisTeamGames == null) { MessageBox.Show("Team not found in file!"); return; } //notify and leave if no game found
if(thisTeamGames.Count == 1) { thisGame = thisTeamGames[0]; }
else
{
Day_Selector selector = new Day_Selector(thisTeamGames, selectedGame);
selector.ShowDialog();
thisGame = selectedGame.selectedGame;
selector.Dispose();
}
//set team names
SetVis(true, liveGameTable);
SetText(thisGame.awayTeamNickname, liveGameAwayName);
SetText(thisGame.homeTeamNickname, liveGameHomeName);
SetText(thisGame.awayScore.ToString(), topR);
SetText(thisGame.homeScore.ToString(), botR);
SetText(string.Concat("S ",(thisGame.season+1).ToString(),", Day ",(thisGame.day+1).ToString()), liveGameTitle);
thisGame.inningsList.Sort();
if(thisGame.inningsList.Last().number > 8) //handle final inning, in case of extra innings
{
SetText(thisGame.inningsList.Last().awayScore.ToString(), top9);
SetText(thisGame.inningsList.Last().homeScore.ToString(), bot9);
SetText(thisGame.inningsList.Last().number.ToString(), label9);
SetVis(true, top9);
SetVis(true, bot9);
}
foreach (Inning inning in thisGame.inningsList) //handle rest of innings as normal
{
if (inning.number <= 8)
{
Label topLabel = InningToLabel(inning.number - 1, true);
Label botLabel = InningToLabel(inning.number - 1, false);
SetVis(true, topLabel);
SetVis(true, botLabel);
SetText(inning.awayScore.ToString(), topLabel);
SetText(inning.homeScore.ToString(), botLabel);
}
}
//load hit numbers
SetText(thisGame.awayHits.ToString(), topH);
SetText(thisGame.homeHits.ToString(), botH);
}
private void button3_Click_1(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "SIBR Archive File";
fileDialog.CheckFileExists = true;
fileDialog.DefaultExt = ".json";
fileDialog.Filter = "Json files (*.json)|*.json|All files(*.*)|*.*";
fileDialog.ShowDialog();
string update;
List<SaveGame> currentGames = new List<SaveGame>();
try
{
bool exit = false;
StreamReader file = new StreamReader(fileDialog.OpenFile());
while ((update = file.ReadLine()) != null && !exit)
{
List<Game> sched = JsonConvert.DeserializeObject<ServerData>(update).schedule;
foreach (Game game in sched)
{
bool found = false;
foreach (SaveGame saveGame in currentGames)
{
if (game._id == saveGame._id)
{
found = true;
saveGame.UpdateSaveGame(game);
}
}
if (!found)
{
SaveGame newGame = new SaveGame(game);
currentGames.Add(newGame);
}
}
}
}
catch
{
MessageBox.Show("File could not be loaded!");
return;
}
SaveFileDialog savefileDialog = new SaveFileDialog();
savefileDialog.Title = "Save New File";
savefileDialog.DefaultExt = "prestige";
savefileDialog.Filter = "Visualizer files (*.prestige)|*.prestige|All files(*.*)|*.*";
savefileDialog.OverwritePrompt = false;
savefileDialog.AddExtension = true;
savefileDialog.ShowDialog();
LoadFileToAppend(savefileDialog.FileName, currentGames);
using (StreamWriter saveFile = File.CreateText(savefileDialog.FileName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(saveFile, currentGames);
}
}
public void LoadFileToAppend(string fileName, List<SaveGame> toAppend)
{
List<SaveGame> oldFile = null;
if (File.Exists(fileName))
{
try
{
using (StreamReader file = File.OpenText(fileName))
{
JsonSerializer serializer = new JsonSerializer();
oldFile = (List<SaveGame>)serializer.Deserialize(file, typeof(List<SaveGame>));
}
foreach (SaveGame newGame in oldFile)
{
bool add = true;
foreach (SaveGame oldGame in toAppend)
{
if (newGame._id == oldGame._id) { add = false; } //if game already exists, no dupes
}
if (add)
{
toAppend.Add(newGame);
}
}
}
catch
{
MessageBox.Show("File not valid! Overwriting...");
}
}
foreach (SaveGame game in toAppend) { game.CleanSave(); }
}
private void button4_Click(object sender, EventArgs e)
{
if (!fileLoaded) { return; } //do nothing without a file
Dictionary<string, Batter> teamBatters = new Dictionary<string, Batter>();
Dictionary<string, Pitcher> teamPitchers = new Dictionary<string, Pitcher>();
Dictionary<string, float> teamStats = new Dictionary<string, float>()
{
{"Hits", 0},
{"Runs", 0},
{"RISP", 0},
{"Runs On Two Outs", 0},
{"Hits On Two Outs", 0},
{"Caught Stealing", 0},
{"Stolen Bases", 0}
};
Team selectedTeam = listBox1.SelectedItem as Team;
Form2 selector = new Form2(loadedFile, selectedSeason);
selector.ShowDialog();
int count = CollectStats(selectedTeam, selectedSeason.seasonDisplay.index, teamBatters, teamPitchers, teamStats);
string statRange = selectedSeason.seasonDisplay.ToString();
StatWindow statWindow = new StatWindow(selectedTeam, teamBatters, teamPitchers, teamStats, statRange, count);
statWindow.Show();
}
private int CollectStats(Team team, int seasonNumber, Dictionary<string, Batter> teamBatters, Dictionary<string, Pitcher> teamPitchers, Dictionary<string, float> teamStats)
{
int count = 0;
bool careAboutSeason = true;
bool postSeason = false;
if (seasonNumber == -1) { careAboutSeason = false; } //pass -1 to use all data
else if (seasonNumber % 10000 != 0)
{
postSeason = true;
seasonNumber = (seasonNumber - (seasonNumber % 10000)) / 10000;
}
else { seasonNumber = seasonNumber / 10000; }
foreach (SaveGame game in loadedFile)
{
bool useGame = false;
if (!careAboutSeason) { useGame = true; }
else if (game.season == seasonNumber && game.day < 99 && !postSeason) { useGame = true; }
else if (game.season == seasonNumber && game.day >= 99 && postSeason) { useGame = true; }
if (useGame)
{
if (game.awayTeamNickname == team.nickname)
{
foreach (KeyValuePair<string, Batter> batter in game.awayBatters)
{
Batter thisInstance = batter.Value;
bool found = teamBatters.ContainsKey(thisInstance._id);
if (!found)
{
teamBatters[thisInstance._id] = batter.Value;
}
teamBatters[thisInstance._id].Collate(thisInstance);
}
foreach (KeyValuePair<string, Pitcher> pitcher in game.awayPitchers)
{
Pitcher thisInstance = pitcher.Value;
bool found = teamPitchers.ContainsKey(thisInstance._id);
if (!found)
{
teamPitchers[thisInstance._id] = pitcher.Value;
}
teamPitchers[thisInstance._id].Collate(thisInstance);
teamPitchers[thisInstance._id].games += 1;
if (game.awayScore > game.homeScore) { teamPitchers[thisInstance._id].wins += 1; }
else { teamPitchers[thisInstance._id].losses += 1; }
}
teamStats["Hits"] += game.awayHits;
teamStats["Runs"] += game.awayScore;
teamStats["RISP"] += game.awayRISP;
teamStats["Runs On Two Outs"] += game.awayRunsOn2Out;
teamStats["Hits On Two Outs"] += game.awayHitsOn2Out;
teamStats["Caught Stealing"] += game.awayCaughtStealing;
teamStats["Stolen Bases"] += game.awaySteals;
count += 1;
}
else if (game.homeTeamNickname == team.nickname)
{
foreach (KeyValuePair<string, Batter> batter in game.homeBatters)
{
Batter thisInstance = batter.Value;
bool found = teamBatters.ContainsKey(thisInstance._id);
if (!found)
{
teamBatters[thisInstance._id] = batter.Value;
}
teamBatters[thisInstance._id].Collate(thisInstance);
}
foreach (KeyValuePair<string, Pitcher> pitcher in game.homePitchers)
{
Pitcher thisInstance = pitcher.Value;
bool found = teamPitchers.ContainsKey(thisInstance._id);
if (!found)
{
teamPitchers[thisInstance._id] = pitcher.Value;
}
teamPitchers[thisInstance._id].Collate(thisInstance);
teamPitchers[thisInstance._id].games += 1;
if (game.awayScore < game.homeScore) { teamPitchers[thisInstance._id].wins += 1; }
else { teamPitchers[thisInstance._id].losses += 1; }
}
teamStats["Hits"] += game.homeHits;
teamStats["Runs"] += game.homeScore;
teamStats["RISP"] += game.homeRISP;
teamStats["Runs On Two Outs"] += game.homeRunsOn2Out;
teamStats["Hits On Two Outs"] += game.homeHitsOn2Out;
teamStats["Caught Stealing"] += game.homeCaughtStealing;
teamStats["Stolen Bases"] += game.homeSteals;
count += 1;
}
}
}
return count;
}
private void liveGameTitle_Click(object sender, EventArgs e)
{
}
}
class Client
{
static HttpClient webClient = new HttpClient();
static Uri uri = new Uri("https://blaseball.com");
static SocketIO socket = new SocketIO(uri);
public async Task<Team> GetTeamFromName(string searchName) //returns a Team object from a short or long team name string
{
HttpResponseMessage response = await webClient.GetAsync("https://blaseball.com/database/allTeams");
//Debug.WriteLine(await response.Content.ReadAsStringAsync());
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
List<Team> allTeams = JsonConvert.DeserializeObject<List<Team>>(responseString);
//Debug.WriteLine(allTeams);
foreach(Team t in allTeams)
{
//Debug.WriteLine(t.fullName);
//Debug.WriteLine(t.nickname);
if(t.nickname == searchName || t.fullName == searchName)
{
return t;
}
}
}
return null;
}
public async Task<List<Team>> GetAllTeams() //returns a list of all teams
{
HttpResponseMessage response = await webClient.GetAsync("https://blaseball.com/database/allTeams");
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<List<Team>>(await response.Content.ReadAsStringAsync());
}
return null;
}
public async Task<List<Game>> GetSingleGamesUpdate() //returns a single list of Games
{
List<ServerData> serverDataList = null;
socket.On("gameDataUpdate", (data) =>
{
serverDataList = JsonConvert.DeserializeObject<List<ServerData>>(data.ToString());
});
await socket.ConnectAsync();
while(serverDataList == null) { Thread.Sleep(100); }
return serverDataList[0].schedule;
}
}
public class ServerData
{
public List<Game> schedule { get; set; }
}
public class SelectedGame
{
public SaveGame selectedGame { get; set; } = null;
}
public class SelectedSeason
{
public SeasonDisplay seasonDisplay { get; set; } = null;
}
}