-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInputParser.cs
1004 lines (929 loc) · 36.4 KB
/
InputParser.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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace NFL2K5Tool
{
public class InputParser
{
private Regex mTeamRegex = new Regex("Team\\s*=\\s*([0-9a-zA-Z]+)");
private Regex mWeekRegex = new Regex("(?i)Week(?-i) ([1-9][0-7]?)");
private Regex mGameRegex = new Regex("([0-9a-z]+)\\s+at\\s+([0-9a-zA-Z]+)");
private Regex mYearRegex = new Regex("YEAR\\s*=\\s*([0-9]+)");
private ParsingStates mCurrentState = ParsingStates.PlayerModification;
private InputParserTeamTracker mTracker = new InputParserTeamTracker();
private List<string> mScheduleList;
/// <summary>
/// true to use existing names; false to replace the names.
/// </summary>
public bool UseExistingNames { get; set; }
public InputParser(GamesaveTool tool)
{
this.Tool = tool;
}
private GamesaveTool Tool { get; set; }
/// <summary>
/// Gets teh team corresponding to the text position
/// </summary>
public static string GetTeam(int textPosition, string data)
{
string team = "49ers";
Regex r = new Regex("TEAM\\s*=\\s*([a-zA-Z49]+)", RegexOptions.IgnoreCase);
MatchCollection mc = r.Matches(data);
Match theMatch = null;
foreach (Match m in mc)
{
if (m.Index > textPosition)
break;
theMatch = m;
}
if (theMatch != null)
{
team = theMatch.Groups[1].Value;
}
return team;
}
public static List<string> GetCoaches(string data)
{
Regex r = new Regex("^(Coach,.*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection mc = r.Matches(data);
List<String> retVal = null;
if (mc.Count > 0)
{
retVal = new List<string>();
foreach (Match m in mc)
{
retVal.Add(m.Groups[1].Value);
}
}
return retVal;
}
/// <summary>
/// returns the line that linePosition falls on in data
/// </summary>
public static string GetLine(int textPosition, string data)
{
string ret = null;
if (textPosition < data.Length)
{
int i = 0;
int lineStart = 0;
int posLen = 0;
for (i = textPosition; i > 0; i--)
{
if (data[i] == '\n')
{
lineStart = i + 1;
break;
}
}
i = lineStart;
if (i < data.Length)
{
char current = data[i];
while (i < data.Length - 1 && current != '\n')
{
posLen++;
i++;
current = data[i];
}
ret = data.Substring(lineStart, posLen);
}
}
return ret;
}
/// <summary>
/// returns the n'th line after the textPosition in 'data'. returns null if end of input reached before number of lines is reached.
/// </summary>
public static string GetLineAfter(int textPosition, int linesAfter, string data)
{
int ne = 0;
int i;
for (i = textPosition; i < data.Length; i++)
{
if (data[i] == '\n')
ne++;
if (ne == linesAfter)
{
i++;
break;
}
}
if (i < data.Length)
return GetLine(i, data);
return null;
}
/// <summary>
/// Process the text in the given file, applying it to the gamesave data.
/// </summary>
/// <param name="fileName"></param>
/// <returns> empty string on success, a non empty string on failure.</returns>
public void ProcessFile(string fileName)
{
try
{
StreamReader sr = new StreamReader(fileName);
string contents = sr.ReadToEnd();
sr.Close();
ProcessText(contents);
}
catch (Exception e)
{
StaticUtils.AddError(String.Format("Error processing file '{0}'. {1}", fileName, e.Message));
}
}
public void ReadFromStdin()
{
string line = "";
int lineNumber = 0;
Console.WriteLine("Reading from standard in...");
try
{
while ((line = Console.ReadLine()) != null)
{
lineNumber++;
ProcessLine(line);
}
ApplySchedule();
}
catch (Exception e)
{
StaticUtils.AddError(
string.Format(
"Error Processing line {0}:'{1}'.\n{2}\n{3}",
lineNumber, line, e.Message, e.StackTrace));
}
}
public void ProcessText(string text)
{
sDelim = CharCount(text, ';') > CharCount(text, ',') ? sSemiColon : sComma;
char[] chars = "\n\r".ToCharArray();
string[] lines = text.Split(chars);
ProcessLines(lines);
}
public void ProcessLines(string[] lines)
{
Tool.GetKey(true, true);
int i = 0;
try
{
for (i = 0; i < lines.Length; i++)
{
ProcessLine(lines[i]);
}
ApplySchedule();
}
catch (Exception e)
{
StringBuilder sb = new StringBuilder(150);
sb.Append("Error! ");
if (i < lines.Length)
sb.Append(string.Format("line #{0}:\t'{1}'", i, lines[i]));
sb.Append(e.Message);
sb.Append("\n");
sb.Append(e.StackTrace);
sb.Append("\n\nOperation aborted at this point. Data not applied.");
StringInputDlg.ShowError(sb.ToString());
}
}
public string GetLookupPlayers()
{
string retVal = null;
if (mLookupedPlayers != null)
{
retVal = mLookupedPlayers.ToString();
}
return retVal;
}
private Match mTeamMatch = Match.Empty;
private StringBuilder mLookupedPlayers = null;
protected virtual bool ProcessLine(string line)
{
bool retVal = true;
line = line.Trim();
if (line.EndsWith(","))
line = line.Substring(0, line.Length - 1);
if (line.StartsWith("#") || line.Length < 1)
{
}
else if (line.StartsWith("KEY=", StringComparison.InvariantCultureIgnoreCase))
{
Tool.SetKey(line.Substring(4));
}
else if (line.StartsWith("CoachKEY=", StringComparison.InvariantCultureIgnoreCase))
{
Tool.CoachKey = line.Substring(9);
}
else if (line.StartsWith("SET"))
{
ApplySet(line);
}
else if (line.IndexOf("LookupAndModify", StringComparison.InvariantCultureIgnoreCase) > -1)
{
Console.WriteLine("LookupAndModifyMode");
mCurrentState = ParsingStates.PlayerLookupAndApply;
}
else if ((mTeamMatch = mTeamRegex.Match(line)) != Match.Empty)
{
//Console.WriteLine("'{0}' ", line);
mCurrentState = ParsingStates.PlayerModification;
string team = mTeamMatch.Groups[1].ToString();
bool ret = SetCurrentTeam(team);
if (!ret)
{
StaticUtils.AddError(string.Format("ERROR with line '{0}'.", line));
StaticUtils.AddError(string.Format("Team input must be in the form 'TEAM = team '"));
return false;
}
}
else if (mWeekRegex.Match(line) != Match.Empty) //line.StartsWith("WEEK"))
{
mCurrentState = ParsingStates.Schedule;
if (mScheduleList == null)
mScheduleList = new List<string>(300);
mScheduleList.Add(line);
}
else if (mYearRegex.Match(line) != Match.Empty)//line.StartsWith("YEAR"))
{
SetYear(line);
}
else if (line.StartsWith("KR1,") || line.StartsWith("KR2,") || line.StartsWith("PR,") || line.StartsWith("LS,"))
{
SetSpecialTeamPlayer(line);
}
else if (line.Equals("AutoUpdateDepthChart"))
{
Tool.AutoUpdateDepthChart();
}
else if (line.Equals("AutoUpdatePBP"))
{
Tool.AutoUpdatePBP();
}
else if (line.Equals("AutoUpdatePhoto"))
{
Tool.AutoUpdatePhoto();
}
else if (line.StartsWith("Coach,", StringComparison.InvariantCultureIgnoreCase))
{
SetCoachData(line);
}
else if (line.StartsWith("LookupPlayer"))
{
mCurrentState = ParsingStates.PlayerLookup;
mLookupedPlayers = new StringBuilder(1000);
}
else if (line.StartsWith("ApplyFormula"))
{
ApplyFormula(line);
}
else
{
switch (mCurrentState)
{
case ParsingStates.PlayerModification:
retVal = InsertPlayer(line);
break;
case ParsingStates.PlayerLookup:
mLookupedPlayers.Append(LookupPlayer(line));
mLookupedPlayers.Append("\n");
break;
case ParsingStates.Schedule:
mScheduleList.Add(line.ToLower());
break;
case ParsingStates.PlayerLookupAndApply:
retVal = LookupPlayerAndApply(line);
break;
}
}
return retVal;
}
// (<formula>,<targetAttribute>, <targetValue>, [positions],<mode>)
/// <summary>
/// Expects input like
/// ApplyFormula('true','RightGlove','None', [QB])
/// ApplyFormula('RightGlove <> None','RightGlove','None', [QB])
/// ApplyFormula('Speed > 0','RightGlove','None', [QB])
/// ApplyFormula('Speed > 80','RightGlove','None', [QB])
/// ApplyFormula('Speed > 80','Stamina','95', [QB], Percent)
/// </summary>
/// <param name="line"></param>
private void ApplyFormula(string line)
{
int index = line.IndexOf("(") + 1;
int endPos = line.IndexOf(']') + 1;
if (index != 0 && endPos != 0 )
{
FormulaMode fm = FormulaMode.Normal;
string argString = line.Substring(index).Replace(")", ""); // get rid of last paren too.
string[] args = argString.Split(new char[] { ',' });
// need 6 args
string formula = args[0].Trim("' ".ToCharArray());
string attr = args[1].Trim("' ".ToCharArray());
string val = args[2].Trim("' ".ToCharArray());
List<string> positions = GetFormulaPositions(line);
if (line.ToLower().Contains("add"))
fm = FormulaMode.Percent;
else if (line.ToLower().Contains("increment"))
fm = FormulaMode.Add;
string results =
Tool.ApplyFormula(formula, attr, val, positions, fm, true);
string message = "";
if (results == null)
message = String.Format("Warning. No players selected by formula:\n\t\"{0}\"", line);
else if (results.StartsWith("Exception!"))
message = "Error, Check formula\n"+ results;
else
message = "#Affected Players\n" + results;
Console.WriteLine(message);
}
}
private List<string> GetFormulaPositions(string line)
{
List<string> retVal = new List<string>();
int index1 = line.IndexOf("[")+1;
int index2 = line.IndexOf("]", index1 + 1) +1;
if (index1 > 0 && index2 > 0)
{
string ps = line.Substring(index1, index2 - index1).Replace("]","");
string[] positions = ps.Split(new char[] {','});
foreach (string pos in positions)
{
retVal.Add(pos.Trim());
}
}
return retVal;
}
private string GetSingleQuoteString(string line, int index)
{
string retVal = null;
int index1 = line.IndexOf("'", index); // first single-quote
int index2 = line.IndexOf("'", index1+1);
if (index1 >= index && index2 > index)
{
retVal = line.Substring(index1, index2 - index1);
}
return retVal;
}
private bool LookupPlayerAndApply(string line)
{
bool retVal = false;
List<string> attributes = ParsePlayerLine(line);
// find first name position (-1); last name position (-2)
int firstNameIndex = -1;
int lastNameIndex = -1;
int positionIndex = -1;
for (int i = 0; i < Tool.Order.Length; i++)
{
if (Tool.Order[i] == -1)
firstNameIndex = i;
else if (Tool.Order[i] == -2)
lastNameIndex = i;
else if (Tool.Order[i] == (int) PlayerOffsets.Position)
positionIndex = i;
if (firstNameIndex > -1 && lastNameIndex > -1 && positionIndex > -1)
break;
}
if (firstNameIndex > -1 && lastNameIndex > -1)
{
string pos = null;
if( positionIndex > -1)
pos = attributes[positionIndex];
string firstName = attributes[firstNameIndex];
string lastName = attributes[lastNameIndex];
List<int> playersToApplyTo = Tool.FindPlayer(pos, firstName, lastName);
if (playersToApplyTo.Count > 0)
retVal = SetPlayerData(playersToApplyTo[0], line, false);
}
else
{
StaticUtils.AddError("In 'LookupAndModify' mode, you must specify fname and lname in the 'Key' for proper lookup:" + line);
}
return retVal;
}
/// <summary>
/// Looks up a player
/// </summary>
/// <param name="line">The line containing the player, must start with Pos,fname,lname</param>
/// <param name="builder">The StringBuilder to put the result into</param>
/// <returns>The player's data (according to current key) or the line passed in if not in the gamesave.</returns>
public string LookupPlayer(string line)
{
List<string> attributes = ParsePlayerLine(line);
string retVal = "#NotFound: "+line;
// find first name position (-1); last name position (-2)
int firstNameIndex = -1;
int lastNameIndex = -1;
int positionIndex = -1;
for (int i = 0; i < Tool.Order.Length; i++)
{
if (Tool.Order[i] == -1)
firstNameIndex = i;
else if (Tool.Order[i] == -2)
lastNameIndex = i;
else if (Tool.Order[i] == (int)PlayerOffsets.Position)
positionIndex = i;
if (firstNameIndex > -1 && lastNameIndex > -1 && positionIndex > -1)
break;
}
string pos = attributes[positionIndex];
string firstName = attributes[firstNameIndex];
string lastName = attributes[lastNameIndex];
StringBuilder builder = new StringBuilder();
List<int> playerIndexes = Tool.FindPlayer(pos, firstName, lastName);
for (int i = 0; i < playerIndexes.Count; i++)
{
builder.Append(Tool.GetPlayerData(playerIndexes[i], true, true));
builder.Append("\n");
}
if (builder.Length > 0)
{
builder.Remove(builder.Length - 1, 1);// remove last '\n'
retVal = builder.ToString();
}
return retVal;
}
private void SetCoachData(string line)
{
//"Coach,Team,fname,lname,Body,Photo";
string[] keyParts = Tool.CoachKey.Split(",".ToCharArray());
List<string> parts = ParseCoachLine(line);
int teamIndex = Tool.GetTeamIndex(parts[1]);
string[] enumNames = Enum.GetNames(typeof(CoachOffsets));
CoachOffsets current = CoachOffsets.Body;
try
{
for (int i = 2; i < keyParts.Length; i++)
{
if (i == parts.Count) break; // stop processing if we're out of parts
switch (keyParts[i].ToLower())
{
case "firstname":
case "fname":
Tool.SetCoachAttribute(teamIndex, CoachOffsets.FirstName, parts[i]);
break;
case "lastname":
case "lname":
Tool.SetCoachAttribute(teamIndex, CoachOffsets.LastName, parts[i]);
break;
default:
current = (CoachOffsets)Enum.Parse(typeof(CoachOffsets), keyParts[i], true);
Tool.SetCoachAttribute(teamIndex, current, parts[i]);
break;
}
}
}
catch (Exception)
{
StaticUtils.AddError(string.Format("Error setting data for line:\r\n{0}\r\n\r\nPerhaps check '{1}' attribute.", line, current.ToString()));
}
}
// Expecting a line like "KR1,CB2"
private void SetSpecialTeamPlayer(string line)
{
string[] parts = line.Split(",".ToCharArray());
if (parts.Length == 2)
{
try
{
SpecialTeamer guy = (SpecialTeamer)Enum.Parse(typeof(SpecialTeamer), parts[0]);
Positions pos = (Positions)Enum.Parse(typeof(Positions), parts[1].Substring(0, parts[1].Length - 1));
int depth = 1;
Int32.TryParse(parts[1].Substring(parts[1].Length - 1), out depth);
Tool.SetSpecialTeamPosition(mTracker.Team, guy, pos, depth);
}
catch
{
StaticUtils.AddError(string.Format("Team:{0} Error adding special team player {1}", mTracker.Team, line));
}
}
else if (parts.Length == 3)
{
try
{
SpecialTeamer guy = (SpecialTeamer)Enum.Parse(typeof(SpecialTeamer), parts[0]);
Tool.SetSpecialTeamPosition(mTracker.Team, guy, parts[1], parts[2]);
}
catch
{
StaticUtils.AddError(string.Format("Team:{0} Error adding special team player {1}", mTracker.Team, line));
}
}
}
private bool InsertPlayer(string line)
{
int playerIndex = GetPlayerIndex(line);
bool useExisting = this.UseExistingNames || (playerIndex >= GamesaveTool.FirstDraftClassPlayer);
return SetPlayerData(playerIndex, line, useExisting);
}
private int GetPlayerIndex(string line)
{
int retVal = -1;
List<int> playerIndexes = Tool.GetPlayerIndexesForTeam(mTracker.Team);
if (mTracker.PlayerCount < playerIndexes.Count)
{
retVal = playerIndexes[mTracker.PlayerCount++];
}
else
{
StaticUtils.AddError(String.Format("Error, team player limit reached. {0}; cannot add player: {1}",mTracker.Team, line));
}
return retVal;
}
private static char[] sComma = new char[] { ',' };
private static char[] sSemiColon = new char[] { ';' };
// will be set when starting to parse.
private static char[] sDelim;
/// <summary>
/// Parses a line of text into a list of strings.
/// </summary>
/// <param name="line">a comma deliminated string of attributes.</param>
/// <returns>a list of strings</returns>
public static List<string> ParsePlayerLine(string line)
{
if (sDelim == null)
{
sDelim = CharCount(line, ';') > CharCount(line, ',') ? sSemiColon : sComma;
}
List<string> retVal = null;
if (!String.IsNullOrEmpty(line))
{
retVal = new List<string>(line.Split(sDelim));
for (int i = 0; i < retVal.Count; i++)
{
// Fixup the issue with commas inside quoted strings.
// (This however only works for strings that have 1 comma inside)
if (retVal[i].EndsWith("\"") && i > 0 && retVal[i - 1].StartsWith("\""))
{
retVal[i - 1] += (sDelim[0] + retVal[i]);
retVal.RemoveAt(i);
}
else if (retVal[i].Length == 0) // remove empty strings
{
retVal.RemoveAt(i);
}
}
}
return retVal;
}
/// <summary>
/// Parses a line of text into a list of strings.
/// </summary>
/// <param name="line">a comma deliminated string of attributes.</param>
/// <returns>a list of strings</returns>
public static List<string> ParseCoachLine(string line)
{
if (sDelim == null)
{
sDelim = CharCount(line, ';') > CharCount(line, ',') ? sSemiColon : sComma;
}
List<string> retVal = new List<string>();
if (!String.IsNullOrEmpty(line))
{
int quoteCount = 0;
StringBuilder builder = new StringBuilder(line);
for (int i = 0; i < builder.Length; i++)
{
if (builder[i] == '"')
quoteCount++;
else if (quoteCount % 2 == 1 && builder[i] == sDelim[0])
builder[i] = '|';
}
retVal = new List<string>(builder.ToString().Split(sDelim));
for (int i = 0; i < retVal.Count; i++)
{
if (retVal[i].IndexOf('|') > -1)
retVal[i] = retVal[i].Replace('|', ',');
}
}
return retVal;
}
static int CharCount(string input, char thingToCount)
{
int retVal = 0;
for (int i = 0; i < input.Length; i++)
if (input[i] == thingToCount)
retVal++;
return retVal;
}
/// <summary>
/// Returns the index of the nth occurrence of the given character
/// </summary>
public static int NthIndex(string input, char thingToCount, int index)
{
int count = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == thingToCount)
{
count++;
if (count == index)
return i;
}
}
return -1;
}
/// <summary>
/// Sets a player's attributes
/// </summary>
/// <param name="player">The index of the player</param>
/// <param name="line">The data tp apply.</param>
public bool SetPlayerData(int player, string line, bool useExistingName)
{
return SetPlayerStuff1(player, line, useExistingName);
}
private void SetPlayerStuff2(int player, string line, bool useExistingName)
{
string attribute = "";
if (player > -1 && player < Tool.MaxPlayers)
{
string[] keyParts = Tool.GetKey(true, true).Replace("#", "").Split(",".ToCharArray());
string field = "";
List<string> attributes = ParsePlayerLine(line);
for (int i = 0; i < attributes.Count; i++)
{
field = keyParts[i];
attribute = attributes[i];
if (attribute != "?" && attribute != "_")
Tool.SetPlayerField(player, field, attribute);
}
}
}
// About 6 x faster than SetPlayerStuff2
private bool SetPlayerStuff1(int player, string line, bool useExistingName)
{
string attribute = "";
string playerName = "";
if (player > -1 && player < Tool.MaxPlayers)
{
int attr = -1;
List<string> attributes = ParsePlayerLine(line);
if ( useExistingName && !CheckPlayerNameExists( attributes, out playerName ))
{
StaticUtils.AddError("Could not find matching name in string database. player not added: "+ playerName);
return false;
}
for (int i = 0; i < attributes.Count; i++)
{
try
{
attr = Tool.Order[i];
attribute = attributes[i];
if (attr == -1)
{
// Name setting perhaps should be done at another, smarter level?
// How we gonna decide to use pointers or not?
if( !Tool.SetPlayerFirstName(player, attribute, useExistingName))
StaticUtils.AddError("Error setting FirstName >" + attribute + "< for '" + line + "' Can only use existing names for college players.");
}
else if (attr == -2)
{
// How we gonna decide to use pointers or not?
if( !Tool.SetPlayerLastName(player, attribute, useExistingName))
StaticUtils.AddError("Error setting LastName >" + attribute + "< for '" + line + "' Can only use existing names for college players.");
}
else if (attribute == "?" || attribute == "_")
{// do nothing
}
else if (attr >= (int)AppearanceAttributes.College)
{
if (attr != (int)AppearanceAttributes.College)
attribute = attribute.Replace(" ", ""); // strip spaces
Tool.SetPlayerAppearanceAttribute(player, (AppearanceAttributes)attr, attribute);
}
else
{
Tool.SetAttribute(player, (PlayerOffsets)attr, attribute);
}
}
catch (Exception)
{
string name = line.Substring(0, 15) + "...";
string desc = attr > 99 ? ((AppearanceAttributes)attr).ToString() : ((PlayerOffsets)attr).ToString();
StaticUtils.AddError("Error setting attribute '" + desc + "' to '" + attribute + "' for line:" + name );
}
}
}
return true;
}
public List<string> MissingNames = new List<string>();
private bool CheckPlayerNameExists(List<string> attributes, out string playerName)
{
int firstNameIndex = Array.IndexOf(Tool.Order, -1);
int lastNameIndex = Array.IndexOf(Tool.Order, -2);
string firstName = attributes[firstNameIndex];
string lastName = attributes[lastNameIndex];
bool firstNameExists = Tool.CheckNameExists(firstName);
bool lastNameExists = Tool.CheckNameExists(lastName);
bool retVal = firstNameExists && lastNameExists;
if (!retVal)
{
playerName = String.Format("{0} {1} firstNameExists={2} lastNameExists={3}",
firstName, lastName, firstNameExists, lastNameExists);
if (!firstNameExists)
MissingNames.Add(firstName);
else
MissingNames.Add(lastName);
}
else
playerName = "";
return retVal;
}
private bool SetCurrentTeam(string team)
{
if (Tool.GetTeamIndex(team) < 0)
{//error condition
StaticUtils.AddError(string.Format("Team '{0}' is Invalid.", team));
return false;
}
else
{
mTracker.Team = team;
mTracker.Reset();
if (team == "DraftClass")
UseExistingNames = true;
else
UseExistingNames = false;
}
return true;
}
private void SetYear(string line)
{
Match m = mYearRegex.Match(line);
string year = m.Groups[1].ToString();
if (year.Length < 1)
{
StaticUtils.AddError(string.Format("'{0}' is not valid.", line));
}
else
{
Tool.SetYear(year);
//Console.WriteLine("Year set to '{0}'", year);
}
}
private void ApplySchedule()
{
if (mScheduleList != null && mScheduleList.Count > 0)
{
Tool.ApplySchedule(mScheduleList);
mScheduleList = null;
}
}
/*// <summary>
/// get all necessary player names.
/// Put them in the Save file.
/// </summary>
/// <returns>a list of NameObjects we can use to reference when inserting players, sorted by name.</returns>
private static List<NameObject> SetupNames(GamesaveTool tool, string[] lines, string key)
{
List<string> neededNames = NameHelper.GetNeededNames(lines, key);
List<NameObject> allNamesInSave = NameHelper.GetAllNames(tool);
List<NameObject> unNeededNames = new List<NameObject>(200);
Dictionary<string, NameObject> nameMap = new Dictionary<string, NameObject>(3000);
NameObjectComparer noc = new NameObjectComparer(NameObjectCompareMode.Name);
allNamesInSave.Sort(noc);
NameObject tmp = new NameObject();
NameObject reference = null;
int index = -1;
//populate unneeded names
for (int i = 0; i < allNamesInSave.Count; i++)
{
index = neededNames.BinarySearch(allNamesInSave[i].Name);
if (index < 0)
unNeededNames.Add(allNamesInSave[i]);
}
// populate name map
return null;
}*/
#region SetBytes logic
private Regex simpleSetRegex;
private void ApplySet(string line)
{
if (simpleSetRegex == null)
simpleSetRegex = new Regex("SET\\s*\\(\\s*(0x[0-9a-fA-F]+)\\s*,\\s*(0x[0-9a-fA-F]+)\\s*\\)");
if (simpleSetRegex.Match(line) != Match.Empty)
{
ApplySimpleSet(line);
}
else if (line.IndexOf("PromptUser", StringComparison.OrdinalIgnoreCase) > -1)
{
string simpleSetLine = StringInputDlg.PromptForSetUserInput(line);
if (!string.IsNullOrEmpty(simpleSetLine))
{
ApplySet(simpleSetLine);
}
}
else
{
StaticUtils.AddError(string.Format("ERROR with line \"{0}\"", line));
}
}
protected void ApplySimpleSet(string line)
{
if (simpleSetRegex == null)
simpleSetRegex = new Regex("SET\\s*\\(\\s*(0x[0-9a-fA-F]+)\\s*,\\s*(0x[0-9a-fA-F]+)\\s*\\)");
Match m = simpleSetRegex.Match(line);
if (m == Match.Empty)
{
StaticUtils.AddError(string.Format("SET function not used properly. incorrect syntax>'{0}'", line));
return;
}
string loc = m.Groups[1].ToString().ToLower();
string val = m.Groups[2].ToString().ToLower();
loc = loc.Substring(2);
val = val.Substring(2);
if (val.Length % 2 != 0)
val = "0" + val;
try
{
int location = Int32.Parse(loc, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] bytes = GetHexBytes(val);
if (location + bytes.Length > Tool.GameSaveData.Length)
{
StaticUtils.AddError(string.Format("ApplySet:> Error with line {0}. Data falls off the end of rom.\n", line));
}
else if (location < 0)
{
StaticUtils.AddError(string.Format("ApplySet:> Error with line {0}. location is negative.\n", line));
}
else
{
for (int i = 0; i < bytes.Length; i++)
{
Tool.SetByte(location + i, bytes[i]);
}
}
}
catch (Exception e)
{
StaticUtils.AddError(string.Format("ApplySet:> Error with line {0}.\n{1}", line, e.Message));
}
}
protected byte[] GetHexBytes(string input)
{
if (input == null)
return null;
byte[] ret = new byte[input.Length / 2];
string b = "";
int tmp = 0;
int j = 0;
for (int i = 0; i < input.Length; i += 2)
{
b = input.Substring(i, 2);
tmp = Int32.Parse(b, System.Globalization.NumberStyles.AllowHexSpecifier);
ret[j++] = (byte)tmp;
}
return ret;
}
#endregion
}
public enum ParsingStates
{
PlayerModification,
PlayerLookupAndApply,
PlayerLookup,
Schedule
}
/// <summary>
/// class used to help keep track of number of players being input.
/// </summary>
public class InputParserTeamTracker
{
public int CBs = 0;
public int DEs = 0;
public int DTs = 0;
public int FBs = 0;
public int Gs = 0;
public int RBs = 0;
public int OLBs = 0;
public int ILBs = 0;
public int Ps = 0;
public int QBs = 0;
public int SSs = 0;
public int Ts = 0;
public int TEs = 0;
public int WRs = 0;
public int Cs = 0;
public int PlayerCount = 0;
public string Team = "";
public void Reset()
{
CBs = 0;
DEs = 0;
DTs = 0;
FBs = 0;
Gs = 0;
RBs = 0;
OLBs = 0;
ILBs = 0;
Ps = 0;
QBs = 0;
SSs = 0;
Ts = 0;
TEs = 0;
WRs = 0;
Cs = 0;