-
Notifications
You must be signed in to change notification settings - Fork 0
/
PgnUtil.cs
1267 lines (1208 loc) · 55.1 KB
/
PgnUtil.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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace SrcChess {
/// <summary>
/// Utility class to help handling PGN files
/// </summary>
public class PgnUtil {
[Flags]
private enum PGNAmbiguity {
NotFound = 0,
Found = 1,
ColMustBeSpecify = 2,
RowMustBeSpecify = 4
}
/// <summary>Information use to filter a PGN file</summary>
public class FilterClause {
/// <summary>All ELO included if true</summary>
public bool m_bAllRanges;
/// <summary>Includes unrated games if true</summary>
public bool m_bIncludesUnrated;
/// <summary>If not all EOL included, hash of all ELO which must be included. Each value represent a range (value, value+99)</summary>
public Dictionary<int, int> m_hashRanges;
/// <summary>All players included if true</summary>
public bool m_bAllPlayers;
/// <summary>Hash of all players to include if not all included</summary>
public Dictionary<string,string> m_hashPlayerList;
/// <summary>Includes all ending if true</summary>
public bool m_bAllEnding;
/// <summary>true to include game winned by white player</summary>
public bool m_bEndingWhiteWinning;
/// <summary>true to include game winned by black player</summary>
public bool m_bEndingBlackWinning;
/// <summary>true to include draws game </summary>
public bool m_bEndingDraws;
}
/// <summary>Item used to fill the description listbox so we can find the original index in the list after a sort</summary>
public class PGNGameDescItem : IComparable<PGNGameDescItem> {
private string m_strDesc;
private int m_iIndex;
//*********************************************************
//
/// <summary>
/// Class constructor
/// </summary>
/// <param name="strDesc"> Item description</param>
/// <param name="iIndex"> Item index</param>
//
//*********************************************************
public PGNGameDescItem(string strDesc, int iIndex) {
m_strDesc = strDesc;
m_iIndex = iIndex;
}
//*********************************************************
//
/// <summary>
/// Description of the item
/// </summary>
//
//*********************************************************
public string Description {
get {
return(m_strDesc);
}
}
//*********************************************************
//
/// <summary>
/// Index of the item
/// </summary>
//
//*********************************************************
public int Index {
get {
return(m_iIndex);
}
}
//*********************************************************
//
/// <summary>
/// IComparable interface
/// </summary>
/// <param name="other"> Item to compare with</param>
/// <returns>
/// -1, 0, 1
/// </returns>
//
//*********************************************************
public int CompareTo(PGNGameDescItem other) {
return(String.Compare(m_strDesc, other.m_strDesc));
}
//*********************************************************
//
/// <summary>
/// Return the description
/// </summary>
/// <returns>
/// Description
/// </returns>
//
//*********************************************************
public override string ToString() {
return(m_strDesc);
}
}
private string m_strPushedLine = null;
private int m_iCurLine = 0;
//*********************************************************
//
/// <summary>
/// Open an file for reading
/// </summary>
/// <param name="strInpFileName"> File name to open</param>
/// <returns>
/// Stream or null if unable to open the file.
/// </returns>
//
//*********************************************************
public Stream OpenInpFile(string strInpFileName) {
Stream streamInp;
try {
streamInp = File.OpenRead(strInpFileName);
} catch(System.Exception) {
MessageBox.Show("Unable to open the file - " + strInpFileName);
streamInp = null;
}
return(streamInp);
}
//*********************************************************
//
/// <summary>
/// Creates a new file
/// </summary>
/// <param name="strOutFileName"> Name of the file to create</param>
/// <returns>
/// Stream or null if unable to create the file.
/// </returns>
//
//*********************************************************
public Stream CreateOutFile(string strOutFileName) {
Stream streamOut;
try {
streamOut = File.Create(strOutFileName);
} catch(System.Exception) {
MessageBox.Show("Unable to create the file - " + strOutFileName);
streamOut = null;
}
return(streamOut);
}
//*********************************************************
//
/// <summary>
/// Gets the next non emoty line. Support one line pushed ahead
/// </summary>
/// <param name="reader"> Text reader</param>
/// <returns>
/// Line or null if EOF
/// </returns>
//
//*********************************************************
private string GetNextNonEmptyLine(TextReader reader) {
string strRetVal;
if (m_strPushedLine != null) {
strRetVal = m_strPushedLine;
m_strPushedLine = null;
} else {
strRetVal = reader.ReadLine();
m_iCurLine++;
while (strRetVal == String.Empty) {
strRetVal = reader.ReadLine();
m_iCurLine++;
}
}
return(strRetVal);
}
//*********************************************************
//
/// <summary>
/// Extract the ELO value of the string
/// </summary>
/// <param name="str"> Input string</param>
/// <returns>
/// ELO value or -1 if not found
/// </returns>
//
//*********************************************************
private int GetELOValue(string str) {
int iRetVal;
int iIndex;
iIndex = str.IndexOf('"');
if (iIndex < 1) {
iRetVal = -1;
} else {
iRetVal = Int32.Parse(str.Substring(0, iIndex));
}
return(iRetVal);
}
//*********************************************************
//
/// <summary>
/// Get the next PGN game from the file.
/// </summary>
/// <param name="reader"> Text reader</param>
/// <param name="iGameStartPos"> Return the beginning of the game in the string array</param>
/// <param name="iWhiteELO"> White player ELO</param>
/// <param name="iBlackELO"> Black player ELO</param>
/// <returns>
/// Array of string describing the game or null if EOF
/// </returns>
//
//*********************************************************
private List<String> GetPGNGame(TextReader reader, out int iGameStartPos, out int iWhiteELO, out int iBlackELO) {
List<string> arrRetVal;
string strLine;
iGameStartPos = -1;
iWhiteELO = -1;
iBlackELO = -1;
arrRetVal = new List<string>(32);
strLine = GetNextNonEmptyLine(reader);
while (strLine != null && strLine[0] == '[') {
arrRetVal.Add(strLine);
if (strLine.Length > 10 && strLine[6] == 'E') {
if (String.Compare(strLine, 0, "[BlackElo \"", 0, 11) == 0) {
iBlackELO = GetELOValue(strLine.Substring(11));
} else if (String.Compare(strLine, 0, "[WhiteElo \"", 0, 11) == 0) {
iWhiteELO = GetELOValue(strLine.Substring(11));
}
}
strLine = GetNextNonEmptyLine(reader);
}
if (strLine != null) {
iGameStartPos = arrRetVal.Count;
arrRetVal.Add(strLine);
strLine = GetNextNonEmptyLine(reader);
while (strLine != null && strLine[0] != '[') {
arrRetVal.Add(strLine);
strLine = GetNextNonEmptyLine(reader);
}
if (strLine != null) {
m_strPushedLine = strLine;
}
}
if (arrRetVal.Count == 0) {
arrRetVal = null;
}
return(arrRetVal);
}
//*********************************************************
//
/// <summary>
/// Get the next PGN game from the file.
/// </summary>
/// <param name="reader"> Text reader</param>
/// <param name="iGameStartPos"> Return the beginning of the game in the string array</param>
/// <returns>
/// Array of string describing the game or null if EOF
/// </returns>
//
//*********************************************************
private List<String> GetPGNGame(TextReader reader, out int iGameStartPos) {
int iWhiteELO;
int iBlackELO;
return(GetPGNGame(reader, out iGameStartPos, out iWhiteELO, out iBlackELO));
}
//*********************************************************
//
/// <summary>
/// Write a PGN game in the specified output stream
/// </summary>
/// <param name="writer"> Text writer</param>
/// <param name="arrGame"> Array of string representing the PGN file</param>
/// <param name="iGameStartPos"> Beginning of the game in the string array</param>
//
//*********************************************************
private void WritePGN(TextWriter writer, List<string> arrGame, int iGameStartPos) {
for (int iIndex = 0; iIndex < iGameStartPos; iIndex++) {
writer.WriteLine(arrGame[iIndex]);
}
writer.WriteLine("");
for (int iIndex = iGameStartPos; iIndex < arrGame.Count; iIndex++) {
writer.WriteLine(arrGame[iIndex]);
}
writer.WriteLine("");
}
//*********************************************************
//
/// <summary>
/// Gets the information about a PGN game
/// </summary>
/// <param name="arrGame"> Array of string representing the PGN file</param>
/// <param name="iGameStartPos"> Beginning of the game in the string array</param>
/// <param name="strWhitePlayer"> Name of the white player</param>
/// <param name="strBlackPlayer"> Name of the black player</param>
/// <param name="strGameResult"> Result of the game</param>
/// <param name="strGameDate"> Date of the game</param>
/// <param name="iWhiteELO"> White player ELO</param>
/// <param name="iBlackELO"> Black player ELO</param>
//
//*********************************************************
private void GetPGNGameInfo(List<string> arrGame,
int iGameStartPos,
out string strWhitePlayer,
out string strBlackPlayer,
out string strGameResult,
out string strGameDate,
out int iWhiteELO,
out int iBlackELO) {
string str;
strWhitePlayer = null;
strBlackPlayer = null;
strGameResult = null;
strGameDate = null;
iWhiteELO = -1;
iBlackELO = -1;
for (int iIndex = 0; iIndex < iGameStartPos; iIndex++) {
str = arrGame[iIndex];
if (String.Compare(str, 0, "[Date \"", 0, 7, false) == 0) {
strGameDate = ExtractValue(str);
} else if (String.Compare(str, 0, "[BlackElo \"", 0, 11, false) == 0) {
str = ExtractValue(str);
if (!Int32.TryParse(str, out iBlackELO)) {
iBlackELO = -1;
}
} else if (String.Compare(str, 0, "[WhiteElo \"", 0, 11, false) == 0) {
str = ExtractValue(str);
if (!Int32.TryParse(str, out iWhiteELO)) {
iWhiteELO = -1;
}
} else if (String.Compare(str, 0, "[Black \"", 0, 8, false) == 0) {
strBlackPlayer = ExtractValue(str);
} else if (String.Compare(str, 0, "[White \"", 0, 8, false) == 0) {
strWhitePlayer = ExtractValue(str);
} else if (String.Compare(str, 0, "[Result \"", 0, 9, false) == 0) {
strGameResult = ExtractValue(str);
}
}
}
//*********************************************************
//
/// <summary>
/// Gets the information about a PGN game
/// </summary>
/// <param name="arrGame"> Array of string representing the PGN file</param>
/// <param name="iGameStartPos"> Beginning of the game in the string array</param>
/// <param name="iWhiteELO"> White player ELO</param>
/// <param name="iBlackELO"> Black player ELO</param>
//
//*********************************************************
private void GetPGNGameInfo(List<string> arrGame,
int iGameStartPos,
out int iWhiteELO,
out int iBlackELO) {
string strWhitePlayer;
string strBlackPlayer;
string strGameResult;
string strGameDate;
GetPGNGameInfo(arrGame,
iGameStartPos,
out strWhitePlayer,
out strBlackPlayer,
out strGameResult,
out strGameDate,
out iWhiteELO,
out iBlackELO);
}
//*********************************************************
//
/// <summary>
/// Scan the PGN stream to retrieve some informations
/// </summary>
/// <param name="streamInp"> Stream containing the PGN file</param>
/// <param name="hashPlayerList"> Hash list which will be filled with the players list</param>
/// <param name="iMinELO"> Minimum ELO found in the games</param>
/// <param name="iMaxELO"> Maximum ELO found in the games</param>
/// <returns>
/// Number of games found in the stream or -1 if error.
/// </returns>
//
//*********************************************************
private int ScanPGN(Stream streamInp, Dictionary<String, String> hashPlayerList, ref int iMinELO, ref int iMaxELO) {
int iRetVal;
int iWhiteELO;
int iBlackELO;
string strWhitePlayer;
string strBlackPlayer;
string strGameResult;
string strGameDate;
List<String> arrPGNGame;
int iGameStartPos;
int iAvgELO;
TextReader reader;
streamInp.Seek(0, SeekOrigin.Begin);
reader = new StreamReader(streamInp);
m_iCurLine = 0;
m_strPushedLine = null;
iRetVal = 0;
try {
arrPGNGame = GetPGNGame(reader, out iGameStartPos);
while (arrPGNGame != null) {
GetPGNGameInfo(arrPGNGame,
iGameStartPos,
out strWhitePlayer,
out strBlackPlayer,
out strGameResult,
out strGameDate,
out iWhiteELO,
out iBlackELO);
if (hashPlayerList != null) {
if (strWhitePlayer != null && !hashPlayerList.ContainsKey(strWhitePlayer)) {
hashPlayerList.Add(strWhitePlayer, null);
}
if (strBlackPlayer != null && !hashPlayerList.ContainsKey(strBlackPlayer)) {
hashPlayerList.Add(strBlackPlayer, null);
}
}
if (iWhiteELO != -1 && iBlackELO != -1) {
iAvgELO = (iWhiteELO + iBlackELO) / 2;
if (iAvgELO > iMaxELO) {
iMaxELO = iAvgELO;
}
if (iAvgELO < iMinELO) {
iMinELO = iAvgELO;
}
}
iRetVal++;
arrPGNGame = GetPGNGame(reader, out iGameStartPos, out iWhiteELO, out iBlackELO);
}
} catch(System.Exception exc) {
MessageBox.Show("Error around the line " + m_iCurLine.ToString() + " while parsing the PGN file.\r\n" + exc.Message);
iRetVal = -1;
}
return(iRetVal);
}
//*********************************************************
//
/// <summary>
/// Checks if the specified game must be retained accordingly to the specified filter
/// </summary>
/// <param name="arrGame"> Array of string representing the PGN file</param>
/// <param name="iGameStartPos"> Beginning of the game in the string array</param>
/// <param name="iAvgELO"> Game average ELO</param>
/// <param name="filterClause"> Filter clause</param>
/// <returns>
/// true if must be retained
/// </returns>
//
//*********************************************************
private bool IsRetained(List<String> arrGame, int iGameStartPos, int iAvgELO, FilterClause filterClause) {
bool bRetVal = true;
string strWhitePlayer;
string strBlackPlayer;
string strGameResult;
string strGameDate;
int iDummy;
if (iAvgELO == -1) {
bRetVal = filterClause.m_bIncludesUnrated;
} else if (filterClause.m_bAllRanges) {
bRetVal = true;
} else {
iAvgELO = iAvgELO / 100 * 100;
bRetVal = filterClause.m_hashRanges.ContainsKey(iAvgELO);
}
if (bRetVal) {
if (!filterClause.m_bAllPlayers || !filterClause.m_bAllEnding) {
GetPGNGameInfo(arrGame,
iGameStartPos,
out strWhitePlayer,
out strBlackPlayer,
out strGameResult,
out strGameDate,
out iDummy,
out iDummy);
if (!filterClause.m_bAllPlayers) {
if (!filterClause.m_hashPlayerList.ContainsKey(strBlackPlayer) &&
!filterClause.m_hashPlayerList.ContainsKey(strWhitePlayer)) {
bRetVal = false;
}
}
if (bRetVal && !filterClause.m_bAllEnding) {
if (strGameResult == "1-0") {
bRetVal = filterClause.m_bEndingWhiteWinning;
} else if (strGameResult == "0-1") {
bRetVal = filterClause.m_bEndingBlackWinning;
} else if (strGameResult == "1/2-1/2") {
bRetVal = filterClause.m_bEndingDraws;
} else {
bRetVal = false;
}
}
}
}
return(bRetVal);
}
//*********************************************************
//
/// <summary>
/// Filter the content of the PGN file in the input stream to fill the output stream
/// </summary>
/// <param name="streamInp"> Inout stream</param>
/// <param name="streamOut"> Output stream. If null, just run to determine the result count.</param>
/// <param name="filterClause"> Filter clause</param>
/// <returns>
/// Number of resulting games.
/// </returns>
//
//*********************************************************
public int FilterPGN(Stream streamInp, Stream streamOut, FilterClause filterClause) {
int iRetVal;
TextReader reader;
TextWriter writer;
List<string> arrPGNGame;
int iGameCount;
int iWhiteELO;
int iBlackELO;
int iGameStartPos;
int iAvgElo;
streamInp.Seek(0, SeekOrigin.Begin);
if (streamOut != null) {
streamOut.Seek(0, SeekOrigin.Begin);
}
reader = new StreamReader(streamInp);
writer = (streamOut == null) ? null : new StreamWriter(streamOut);
iGameCount = 0;
iRetVal = 0;
m_iCurLine = 0;
m_strPushedLine = null;
try {
arrPGNGame = GetPGNGame(reader, out iGameStartPos, out iWhiteELO, out iBlackELO);
while (arrPGNGame != null) {
iAvgElo = (iWhiteELO != -1 && iBlackELO != -1) ? (iWhiteELO + iBlackELO) / 2 : -1;
if (IsRetained(arrPGNGame, iGameStartPos, iAvgElo, filterClause)) {
if (writer != null) {
WritePGN(writer, arrPGNGame, iGameStartPos);
}
iRetVal++;
}
iGameCount++;
arrPGNGame = GetPGNGame(reader, out iGameStartPos, out iWhiteELO, out iBlackELO);
}
} catch(System.Exception exc) {
MessageBox.Show("Error around the line " + m_iCurLine.ToString() + " while parsing the PGN file.\r\n" + exc.Message);
iRetVal = 0;
}
if (writer != null) {
writer.Flush();
}
return(iRetVal);
}
//*********************************************************
//
/// <summary>
/// Extract the value from a PGN tag
/// </summary>
/// <param name="strTag"> Tag</param>
/// <returns>
/// Value or '???' if unable to decode.
/// </returns>
//
//*********************************************************
private string ExtractValue(string strTag) {
string strRetVal = "???";
int iStart;
int iEnd;
iStart = strTag.IndexOf('"');
if (iStart != -1) {
iEnd = strTag.LastIndexOf('"');
if (iEnd != -1) {
strRetVal = strTag.Substring(iStart + 1, iEnd - iStart - 1);
}
}
return(strRetVal);
}
//*********************************************************
//
/// <summary>
/// Build a description for the specified game.
/// </summary>
/// <param name="arrGame"> Array of string representing the PGN file</param>
/// <param name="iGameStartPos"> Beginning of the game in the string array</param>
/// <returns>
/// Description
/// </returns>
//
//*********************************************************
public string GetPGNGameDesc(List<string> arrGame, int iGameStartPos) {
string strRetVal;
int iWhiteELO;
int iBlackELO;
string strWhitePlayer;
string strBlackPlayer;
string strGameResult;
string strGameDate;
GetPGNGameInfo(arrGame,
iGameStartPos,
out strWhitePlayer,
out strBlackPlayer,
out strGameResult,
out strGameDate,
out iWhiteELO,
out iBlackELO);
strRetVal = ((strWhitePlayer == null) ? "???" : strWhitePlayer) +
" against " +
((strBlackPlayer == null) ? "???" : strBlackPlayer) +
" (" +
((iBlackELO == -1) ? "???" : iBlackELO.ToString()) +
" / " +
((iWhiteELO == -1) ? "???" : iWhiteELO.ToString()) +
") played on " +
((strGameDate == null) ? "???" : strGameDate) +
". Result is " +
((strGameResult == null) ? "???" : strGameResult);
return(strRetVal);
}
//*********************************************************
//
/// <summary>
/// Creates a new PGN file as a subset of an existing one.
/// </summary>
//
//*********************************************************
public void CreatePGNSubset() {
OpenFileDialog openDlg;
SaveFileDialog saveDlg;
Stream streamInp;
Stream streamOut;
Dictionary<string, string> hashPlayer;
String[] arrPlayer;
int iMinELO;
int iMaxELO;
int iCount;
frmPGNFilter frm;
PgnUtil.FilterClause filterClause;
using(openDlg = new OpenFileDialog()) {
openDlg.AddExtension = true;
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
openDlg.DefaultExt = "pgn";
openDlg.Filter = "Chess PGN Files (*.pgn)|*.pgn";
openDlg.Multiselect = false;
openDlg.Title = "Open Source PGN File";
if (openDlg.ShowDialog() == DialogResult.OK) {
streamInp = OpenInpFile(openDlg.FileName);
if (streamInp != null) {
using(streamInp) {
hashPlayer = new Dictionary<string,string>(4096);
iMinELO = Int32.MaxValue;
iMaxELO = Int32.MinValue;
iCount = ScanPGN(streamInp, hashPlayer, ref iMinELO, ref iMaxELO);
if (iCount == 0) {
MessageBox.Show("No games found in the file.");
} else if (iCount != -1) {
arrPlayer = new string[hashPlayer.Keys.Count];
hashPlayer.Keys.CopyTo(arrPlayer, 0);
Array.Sort(arrPlayer);
using (frm = new frmPGNFilter(this, streamInp, iMinELO, iMaxELO, arrPlayer, openDlg.FileName, iCount)) {
if (frm.ShowDialog() == DialogResult.OK) {
filterClause = frm.FilteringClause;
using(saveDlg = new SaveFileDialog()) {
saveDlg.AddExtension = true;
saveDlg.CheckPathExists = true;
saveDlg.DefaultExt = "pgn";
saveDlg.Filter = "Chess PGN Files (*.pgn)|*.pgn";
saveDlg.OverwritePrompt = true;
saveDlg.Title = "PGN File to Create";
if (saveDlg.ShowDialog() == DialogResult.OK) {
streamOut = CreateOutFile(saveDlg.FileName);
if (streamOut != null) {
using(streamOut) {
iCount = FilterPGN(streamInp, streamOut, filterClause);
MessageBox.Show("The file '" + saveDlg.FileName + "' has been created with " + iCount.ToString() + " game(s)");
}
}
}
}
}
}
}
}
}
}
}
}
//*********************************************************
//
/// <summary>
/// Fill a listbox with the description of the games include in a PGN stream
/// </summary>
/// <param name="streamInp"> Stream containing the PGN file</param>
/// <param name="listBox"> Listbox control</param>
/// <returns>
/// Number of games found in the stream or -1 if error.
/// </returns>
//
//*********************************************************
public int FillListBoxWithDesc(Stream streamInp, ListBox listBox) {
int iRetVal;
List<String> arrPGNGame;
int iGameStartPos;
int iDummy;
TextReader reader;
string strDesc;
streamInp.Seek(0, SeekOrigin.Begin);
reader = new StreamReader(streamInp);
m_iCurLine = 0;
m_strPushedLine = null;
iRetVal = 0;
listBox.SuspendLayout();
try {
arrPGNGame = GetPGNGame(reader, out iGameStartPos);
while (arrPGNGame != null) {
GetPGNGameInfo(arrPGNGame,
iGameStartPos,
out iDummy,
out iDummy);
strDesc = (iRetVal + 1).ToString().PadLeft(5, '0') + " - " + GetPGNGameDesc(arrPGNGame, iGameStartPos);
listBox.Items.Add(new PGNGameDescItem(strDesc, iRetVal));
iRetVal++;
arrPGNGame = GetPGNGame(reader, out iGameStartPos, out iDummy, out iDummy);
}
} catch(System.Exception exc) {
MessageBox.Show("Error around the line " + m_iCurLine.ToString() + " while parsing the PGN file.\r\n" + exc.Message);
iRetVal = -1;
}
listBox.ResumeLayout();
return(iRetVal);
}
//*********************************************************
//
/// <summary>
/// Get the Nth game
/// </summary>
/// <param name="streamInp"> Stream containing the PGN file</param>
/// <param name="iIndex"> Game index (0-max)</param>
/// <returns>
/// Game or null if error
/// </returns>
//
//*********************************************************
public string GetNGame(Stream streamInp, int iIndex) {
StringBuilder strBuilder;
List<String> arrPGNGame;
int iGameStartPos;
TextReader reader;
streamInp.Seek(0, SeekOrigin.Begin);
reader = new StreamReader(streamInp);
m_iCurLine = 0;
m_strPushedLine = null;
try {
arrPGNGame = GetPGNGame(reader, out iGameStartPos);
while (arrPGNGame != null && iIndex != 0) {
arrPGNGame = GetPGNGame(reader, out iGameStartPos);
iIndex--;
}
if (arrPGNGame == null) {
strBuilder = null;
} else {
strBuilder = new StringBuilder(8192);
for (int i = 0; i < iGameStartPos; i++) {
strBuilder.AppendLine(arrPGNGame[i]);
}
strBuilder.AppendLine();
for (int i = iGameStartPos; i < arrPGNGame.Count; i++) {
strBuilder.AppendLine(arrPGNGame[i]);
}
}
} catch(System.Exception exc) {
MessageBox.Show("Error around the line " + m_iCurLine.ToString() + " while parsing the PGN file.\r\n" + exc.Message);
strBuilder = null;
}
return((strBuilder == null) ? null : strBuilder.ToString());
}
//*********************************************************
//
/// <summary>
/// Gets Square Id from the PGN representation
/// </summary>
/// <param name="strMove"> PGN square representation.</param>
/// <returns>
/// square id (0-63)
/// PGN representation
/// </returns>
//
//*********************************************************
public static int GetSquareIDFromPGN(string strMove) {
int iRetVal;
Char cChr1;
Char cChr2;
if (strMove.Length != 2) {
iRetVal = -1;
} else {
cChr1 = strMove.ToLower()[0];
cChr2 = strMove[1];
if (cChr1 < 'a' || cChr1 > 'h' || cChr2 < '1' || cChr2 > '8') {
iRetVal = -1;
} else {
iRetVal = 7 - (cChr1 - 'a') + ((cChr2 - '0') << 3);
}
}
return(iRetVal);
}
//*********************************************************
//
/// <summary>
/// Gets the PGN representation of a square
/// </summary>
/// <param name="iPos"> Absolute position of the square.</param>
/// <returns>
/// PGN representation
/// </returns>
//
//*********************************************************
public static string GetPGNSquareID(int iPos) {
string strRetVal;
strRetVal = ((Char)('a' + 7 - (iPos & 7))).ToString() + ((Char)((iPos >> 3) + '1')).ToString();
return(strRetVal);
}
//*********************************************************
//
/// <summary>
/// Find all moves which end to the same position which can create ambiguity
/// </summary>
/// <param name="chessBoard"> Chessboard before the move has been done.</param>
/// <param name="move"> Move to convert</param>
/// <param name="eMovePlayer"> Player making the move</param>
/// <returns>
/// PGN move
/// </returns>
//
//*********************************************************
private static PGNAmbiguity FindMoveAmbiguity(ChessBoard chessBoard, ChessBoard.MovePosS move, ChessBoard.PlayerColorE eMovePlayer) {
PGNAmbiguity eRetVal = PGNAmbiguity.NotFound;
ChessBoard.PieceE ePieceMove;
List<ChessBoard.MovePosS> moveList;
moveList = chessBoard.EnumMoveList(eMovePlayer);
ePieceMove = chessBoard[move.StartPos];
foreach (ChessBoard.MovePosS moveTest in moveList) {
if (moveTest.EndPos == move.EndPos) {
if (moveTest.StartPos == move.StartPos) {
if (moveTest.Type == move.Type) {
eRetVal |= PGNAmbiguity.Found;
}
} else {
if (chessBoard[moveTest.StartPos] == ePieceMove) {
if ((moveTest.StartPos & 7) != (move.StartPos & 7)) {
eRetVal |= PGNAmbiguity.ColMustBeSpecify;
} else {
eRetVal |= PGNAmbiguity.RowMustBeSpecify;
}
}
}
}
}
return(eRetVal);
}
//*********************************************************
//
/// <summary>
/// Gets a PGN move from a MovePosS structure and a chessboard.
/// </summary>
/// <param name="chessBoard"> Chessboard before the move has been done.</param>
/// <param name="move"> Move to convert</param>
/// <param name="bIncludeEnding"> true to include ending</param>
/// <returns>
/// PGN move
/// </returns>
//
//*********************************************************
public static string GetPGNMoveFromMove(ChessBoard chessBoard, ChessBoard.MovePosS move, bool bIncludeEnding) {
string strRetVal;
string strStartPos;
ChessBoard.PieceE ePiece;
PGNAmbiguity eAmbiguity;
ChessBoard.PlayerColorE ePlayerToMove;
if (move.Type == ChessBoard.MoveTypeE.Castle) {
strRetVal = (move.EndPos == 1 || move.EndPos == 57) ? "O-O" : "O-O-O";
} else {
ePiece = chessBoard[move.StartPos] & ChessBoard.PieceE.PieceMask;
ePlayerToMove = chessBoard.NextMoveColor;
eAmbiguity = FindMoveAmbiguity(chessBoard, move, ePlayerToMove);
switch(ePiece) {
case ChessBoard.PieceE.King:
strRetVal = "K";
break;
case ChessBoard.PieceE.Queen:
strRetVal = "Q";
break;
case ChessBoard.PieceE.Rook:
strRetVal = "R";
break;
case ChessBoard.PieceE.Bishop:
strRetVal = "B";
break;
case ChessBoard.PieceE.Knight:
strRetVal = "N";
break;
case ChessBoard.PieceE.Pawn:
strRetVal = "";
break;
default:
strRetVal = "";
break;
}
strStartPos = GetPGNSquareID(move.StartPos);
if ((eAmbiguity & PGNAmbiguity.ColMustBeSpecify) == PGNAmbiguity.ColMustBeSpecify) {
strRetVal += strStartPos[0];
}
if ((eAmbiguity & PGNAmbiguity.RowMustBeSpecify) == PGNAmbiguity.RowMustBeSpecify) {
strRetVal += strStartPos[1];
}
if ((move.Type & ChessBoard.MoveTypeE.PieceEaten) == ChessBoard.MoveTypeE.PieceEaten) {
if (ePiece == ChessBoard.PieceE.Pawn &&
(eAmbiguity & PGNAmbiguity.ColMustBeSpecify) == (PGNAmbiguity)0 &&
(eAmbiguity & PGNAmbiguity.RowMustBeSpecify) == (PGNAmbiguity)0) {
strRetVal += strStartPos[0];
}
strRetVal += 'x';
}
strRetVal += GetPGNSquareID(move.EndPos);
switch(move.Type & ChessBoard.MoveTypeE.MoveTypeMask) {
case ChessBoard.MoveTypeE.PawnPromotionToQueen:
strRetVal += "=Q";
break;
case ChessBoard.MoveTypeE.PawnPromotionToRook:
strRetVal += "=R";
break;
case ChessBoard.MoveTypeE.PawnPromotionToBishop:
strRetVal += "=B";
break;
case ChessBoard.MoveTypeE.PawnPromotionToKnight:
strRetVal += "=N";
break;
case ChessBoard.MoveTypeE.PawnPromotionToPawn:
strRetVal += "=P";
break;
default:
break;
}
}
chessBoard.DoMoveNoLog(move);
switch(chessBoard.CheckNextMove()) {
case ChessBoard.MoveResultE.NoRepeat:
break;