forked from JBontes/Life32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u_InOut.pas
1826 lines (1677 loc) · 55.4 KB
/
u_InOut.pas
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
unit u_InOut;
// LIFE
// #N - Normal rules (Conway)
// #R - Rules
// #S - Speed
// #D - Description, comment
// #C - Description, comment
// #P - The block position
//
// MCL
// #GAME - The game type
// #RULE - Rules as a text string
// #N - Game of Life, Conway's rules
// #BOARD - Board size
// #WRAP - 'Wrap at edges' status
// #SPEED - animation speed
// #CCOLORS - Count of colors
// #PALETTE - color palette
// #COLORING - coloring method, 1/2
// #DIV - diversities
// #D - Description, comment
// #L - Data line
interface
uses
Windows, Classes, u_CADefs;
const
BORDER_EXTRAMARGIN = 600;
type
TSaveAs = (IO_OPTIMAL, IO_MCL, IO_RLE, IO_LIF105, IO_LIF106, IO_MLF);
type
TOpenParams = class
private { Private declarations }
published { Published declarations }
public { Public declarations }
fOpen: Boolean; // Open flag (False - insert/append/ to the open file)
fWarnNotFound: Boolean; // Issue a warning when the file could not befound
fStringsReady: Boolean; // Don't load the disk file, strings are already prepared
fOnlyPattern: Boolean; // Load only the pattern, ignore rules and settings
fApplyRules: Boolean; // Apply family and rules?
constructor Create;
procedure Reset;
end;
TInOut = class
private { Private declarations }
m_IOCells: array of TCells; // loaded cells
m_IOCellsCount: Integer; // count of loaded cells
m_Family: TFamily; // the game
m_sRules: String; // rules
m_Description: TStringList; // the CA file description
m_Speed: Integer; // game speed
m_BSizeX,m_BSizeY: Integer; // board size
m_Wrap: Integer; // wrapping state
m_CColors: Integer; // count of colors
m_Coloring: Integer; // coloring method
m_sPalette: String; // colors palette file name
m_dMclVsn: Double; // MCL file version
m_LineStrings: TStringList; // list of strings representing the file
m_SaveSpeed: Boolean; // save speed with pattern?
m_SaveBSize: Boolean; // save board size with pattern?
m_SaveWrap: Boolean; // save wrapping state with pattern?
m_SaveCColors: Boolean; // save count of colors with pattern?
m_SavePalNam: Boolean; // save color palette name with pattern?
m_SaveDiv: Boolean; // save diversities with pattern?
m_OnlySaveAs: Boolean; // when saving always use the Save as... dialog
m_OnlyTopRow1D: Boolean; // save only the top row of 1-D CA
// OPEN interface
function ReadFileToStrings(sFilNam: String; fWarnNotFound: Boolean): Boolean;
function DoOpenLifeFile: Boolean;
// Open MLF
function ReadFileMLF: Boolean;
// Open MCL
function ProcessOneMCLLine(bff: String; var iCol, iRow, iNum: Integer): Boolean;
function ReadFileMCL: Boolean;
// Open LIF105
function ProcessOneLIF105Line(bff: String; var iBlkX, iBlkY: Integer; var iRow: Integer): Boolean;
function ReadFileLIF105: Boolean;
// Open LIF106
function ProcessOneLIF106Line(bff: String): Boolean;
function ReadFileLIF106: Boolean;
// Open RLE
function ProcessOneRLELine(bff: String; var iCol, iRow, iNum: Integer; var fEndFlg, fXYFound: Boolean): Boolean;
function ReadFileRLE: Boolean;
// Save RLE
function FormatRLEItem(cnt: Integer; typ: String): String;
procedure UpdateRLEString(var sBff: String; sPfx: String; var cnt: Integer; typ: String);
// Open PLF
function ReadFilePLF(sFilNam: String): Boolean;
// Open SG
function GetSGVal(ch: Char): Byte;
function ReadFileSG: Boolean;
// Save
procedure MakeRLEStrings(rect: TRect; fFromBoard: Boolean);
procedure MakeLIF105Strings(rect: TRect; fFromBoard: Boolean);
procedure MakeLIF106Strings(rect: TRect; fFromBoard: Boolean);
procedure MakeMLFStrings(rect: TRect; fFromBoard: Boolean);
procedure MakeMCLStrings(rect: TRect; fFromBoard: Boolean);
published { Published declarations }
property SaveSpeed: Boolean read m_SaveSpeed write m_SaveSpeed;
property SaveBSize: Boolean read m_SaveBSize write m_SaveBSize; // save board size with pattern?
property SaveWrap: Boolean read m_SaveWrap write m_SaveWrap; // save wrapping state with pattern?
property SaveCColors: Boolean read m_SaveCColors write m_SaveCColors; // save count of colors with pattern?
property SavePalNam: Boolean read m_SavePalNam write m_SavePalNam; // save color palette name with pattern?
property SaveDiv: Boolean read m_SaveDiv write m_SaveDiv; // save diversities with pattern?
property OnlyTopRow1D: Boolean read m_OnlyTopRow1D write m_OnlyTopRow1D;
property OnlySaveAs: Boolean read m_OnlySaveAs write m_OnlySaveAs; // when saving always use the Save as... dialog
// OPEN interface
function OpenLifeFile(sFilNam: String; oprm: TOpenParams): Boolean;
function ReadFileRule(sFilNam: String; var iFamIdx: TFamily): String;
// SAVE interface
procedure SaveFile(var sFilNam: String; filTyp: TSaveAs);
// Clipboard interface
function PutRectOnClipboard(rect: TRect): Boolean;
function GetFromClipboard: Boolean;
function OpenFromClipboard: Boolean;
// Misc
procedure AddCell(iCol, iRow: Integer; bVal: Byte);
function MinRectangle: TRect;
function GetAllFilter: String;
public { Public declarations }
constructor Create;
end;
var
InOut: TInOut;
OpenParams: TOpenParams;
implementation
uses
SysUtils, Dialogs, Math, u_Main, u_Board, u_Undo, u_Rules, u_Description,
u_Selection, u_ColorPalette, u_ColorsBar, u_Diversities, uMWTools, uMWStrings,
Controls, Forms, Clipbrd;
//------------------------------------------------------------------------------
// Construction / destruction
constructor TOpenParams.Create;
begin
Reset;
end;
procedure TOpenParams.Reset;
begin
fOpen := True; // Open flag (False - insert/append/ to the open file)
fWarnNotFound := True; // Issue a warning when the file could not befound
fStringsReady := False; // Don't load the disk file, strings are already prepared
fOnlyPattern := False; // Load only the pattern, ignore rules and settings
fApplyRules := True; // Apply game and rules?
end;
constructor TInOut.Create;
begin
SetLength(m_IOCells, 0); // nothing loaded
m_IOCellsCount := 0;
m_Description := TStringList.Create; // the CA file description
m_LineStrings := TStringList.Create; // list of strings representing the file
OpenParams := TOpenParams.Create; // Open parameters
end;
//------------------------------------------------------------------------------
// Published methods
procedure TInOut.AddCell(iCol, iRow: Integer; bVal: Byte);
begin
Inc(m_IOCellsCount);
if m_IOCellsCount > High(m_IOCells) then SetLength(m_IOCells, m_IOCellsCount+500);
with m_IOCells[m_IOCellsCount] do
begin
col := iCol;
row := iRow;
val := bVal;
end;
end;
//------------------------------------------------------------------------------
// Calculate the selection minimal rectangle
function TInOut.MinRectangle: TRect;
var
rect: TRect;
i: Integer;
begin
rect.Left := Board.MaxCell.x;
rect.Right := Board.MinCell.x;
rect.Top := Board.MaxCell.y;
rect.Bottom := Board.MinCell.y;
for i := 1 to m_IOCellsCount do
with m_IOCells[i] do
begin
if rect.Left > col then rect.Left := col;
if rect.Right < col then rect.Right := col;
if rect.Bottom < row then rect.Bottom := row;
if rect.Top > row then rect.Top := row;
end;
MinRectangle := rect;
end;
//------------------------------------------------------------------------------
// Get the Run &n/to n cycle(s)... files filter
function TInOut.GetAllFilter: String;
begin
GetAllFilter := 'All CA files formats|*.mcl;*.life;*.lif;*.l;*.rle;*.plf;*.mlf' +
'|Life 1.05,1.06 files (*.LIF, *.LIFE)|*.life;*.lif' +
'|RLE files (*.RLE)|*.rle' +
'|dbLife files (*.L)|*.l' +
'|ProLife (*.PLF)|*.plf' +
'|MCell files (*.MCL, *.MLF)|*.mcl;*.mlf' +
'|All files (*.*)|*.*'
end;
///////////////////////////////////
// Opening
//
//------------------------------------------------------------------------------
// Interface function opening the given file
function TInOut.OpenLifeFile(sFilNam: String; oprm: TOpenParams): Boolean;
var
i: Integer;
ix, iy: Integer;
rect: TRect;
midPnt: TPoint; // pattern center point
dx, dy: Integer; // centering vector
Save_Cursor: TCursor;
fOpenOK: Boolean;
fStringsOK: Boolean;
fFileLoaded: Boolean; // file successfully processed?
begin
fOpenOK := False;
fFileLoaded := False;
SetLength(m_IOCells, 0); // nothing loaded
m_IOCellsCount := 0;
m_Description.Clear;
m_Family := FAMI_LIFE; // Life
m_sRules := '23/3'; // standard Conway's rules
m_Speed := -1; // game speed
m_BSizeX := -1; // board size
m_BSizeY := m_BSizeX;
m_Wrap := 0; // wrapping state
m_CColors := -1; // count of colors
m_Coloring := -1; // default
m_sPalette:= ''; // colors palette file name
m_dMclVsn := 0; // MCL file version
Save_Cursor := Screen.Cursor;
try
Screen.Cursor := crHourglass; // show hourglass cursor
sFilNam := Trim(sFilNam);
if oprm.fStringsReady then // strings were prepared outside
fStringsOK := True
else
fStringsOK := ReadFileToStrings(sFilNam, oprm.fWarnNotFound);
if fStringsOK then
begin
Diversities.m_Enabled := False; // they must be activated separately for each file
fFileLoaded := DoOpenLifeFile; // put found cells to the array of cells
end;
finally
if fFileLoaded or (m_IOCellsCount > 0) then // anything loaded?
begin
Undo.AddItem(UDOEVT_OPEN); // new file about to be opened, add universe to the Undo list
rect := MinRectangle; // get the bounding rectangle
if oprm.fOpen then // open a file in a new universe
begin
if not oprm.fOnlyPattern then // rules/parameters should be applied
begin
Board.PrepareNew(False, True); // prepare the board
if m_Wrap >= 0 then // wrapping at edges
Board.Wrap := IntToBool(m_Wrap);
if oprm.fApplyRules then // no rules - no count of states
begin
if m_CColors >= 2 then // count of colors
Board.StatesCount := m_CColors;
end;
if m_Coloring in [1,2] then // coloring method
Board.ColoringMethod := m_Coloring;
if m_Speed >= 0 then // game speed
frmMain.SetInterval(m_Speed);
if (m_BSizeX > 0) and (m_BSizeY > 0) then // board size specified
Board.BoardSize := Point(m_BSizeX, m_BSizeY)
else // pattern does not specify the size - check, if current fits
begin
ix := rect.Right-rect.Left + 1 + BORDER_EXTRAMARGIN; // add some margin
iy := rect.Bottom-rect.Top + 1 + BORDER_EXTRAMARGIN;
if Board.BoardSize.x > ix then // if board was bigger, leave it
ix := Board.BoardSize.x;
if Board.BoardSize.y > iy then
iy := Board.BoardSize.y;
Board.BoardSize := Point(ix, iy);
end;
if oprm.fApplyRules then
begin
Pgm.Family := m_Family; // remember: first the game, next rules!
Board.Rules := Trim(m_sRules);
end;
if Length(m_sPalette) > 0 then // colors palette file name
begin
CrrClo.LoadFromFile(m_sPalette);
frmColorBar.UpdateColors; // update the colors bar
frmMain.UpdatePaletteUI; // mark the active palette in menus
end;
// in case of MCell 1.0 increase the count of states
if m_dMclVsn = 1 then // QQ can one compare doubles in Pascal?
begin
if Pgm.Family <> FAMI_CYCL then // here it was proper...
Board.StatesCount := Board.StatesCount + 1;
if Pgm.Family = FAMI_WLIF then
RulesWLife.iClo := Board.StatesCount;
end;
frmMain.SetFileName(sFilNam, True); // file name
frmMain.LastDir := ExtractFilePath(sFilNam); // store the folder for next time
// add to history of opened files
frmMain.MRUFileList.AddItem(sFilNam);
frmMain.MRUFavFolders.AddItem(ExtractFilePath(sFilNam));
// add description
Description.Clear;
for i := 0 to m_Description.Count - 1 do
begin
Description.Add(m_Description[i]);
end;
end;
// center the pattern being loaded
midPnt.x := (rect.Left + rect.Right + 1) div 2;
midPnt.y := (rect.Top + rect.Bottom + 1) div 2;
dx := -midPnt.x;
if (Pgm.FamiType = FAMITYP_1D) then // 1-D
dy := Board.MinCell.y - rect.Top // always to the top row
else
dy := -midPnt.y;
for i := 1 to m_IOCellsCount do // append all cells
with m_IOCells[i] do
Board.SetCell(col+dx, row+dy, val); // set
if not oprm.fOnlyPattern then // rules/parameters should be applied
begin
// any fitting after loading?
case iOpnAct of
OPNACT_CTR: Board.PanCenterPattern(False); // center shape
OPNACT_FIT: Board.ZoomBestFit(False); // Best fit
end;
if Undo.ResetOnNew then Undo.ClearAll; // reinitialize Undo
fModified := False; // nothing modified so far
end;
frmMain.ShowFormCaption;
end
else // insert (append) without creating a new universe
begin
Selection.SelClear; // delete current selection
Selection.SelFrame := rect;
for i := 1 to m_IOCellsCount do // append all cells
with m_IOCells[i] do
Selection.AddCellAbs(col, row, val, False); // set
// place the file in the upper left corner
Selection.MoveFrameTo(Point(Board.OrgX + 5, Board.OrgY + 5), False);
frmMain.cmdModeMarkClick(Nil); // go to mark mode
end;
// we are ready to show what was loaded
Board.Redraw([DRAW_GRID, DRAW_CELLS]); // redraw the board
fOpenOK := True;
end
else // no cells loaded
begin
MessageDlg('File ' + Chr(10) + '[' + sFilNam + ']' + Chr(10) + ' could not be loaded :(', mtWarning, [mbOK], 0);
end;
SetLength(m_IOCells, 0); // clean up
m_IOCellsCount := 0;
Screen.Cursor := Save_Cursor // always restore to normal
end;
if fOpenOK then
begin
if oprm.fOpen then
frmMain.PlayResSound('SND_OPEN')
else
frmMain.PlayResSound('SND_DROP');
end;
frmMain.UpdatePttInfoHint;
OpenLifeFile := fOpenOK;
end;
//------------------------------------------------------------------------------
// Read the file to the list of strings
function TInOut.ReadFileToStrings(sFilNam: String; fWarnNotFound: Boolean): Boolean;
var
sExt: String; // file extension (type)
fOk: Boolean;
vFile: System.TextFile;
bff, tok: String;
iPos: Integer;
begin
fOk := False; // Let's be pesimistic (realistic?)
m_LineStrings.Clear; // prepare the list of strings
if FileExists(sFilNam) then
begin
sExt := AnsiUpperCase(ExtractFileExt(sFilNam));
if sExt = '.PLF' then // ProLife - binary file
begin
ReadFilePLF(SFilNam);
fOk := False; // a trick - in order no to perform DoOpenLifeFile()
end
else
begin
System.AssignFile(vFile, sFilNam);
Reset(vFile); // open the original file
ReadLn(vFile, bff); // get the first line
fOk := True; // ok
if Pos(Chr(10), bff) = 0 then // DOS file, read all lines
begin
m_LineStrings.Add(bff); // add the first line
while not Eof(vFile) do // traverse the whole file
begin
ReadLn(vFile, bff); // get the line and parse it
m_LineStrings.Add(bff);
end;
end
else // UNIX file, bff stores the whole file, break it to lines
begin
iPos := Pos(Chr(10), bff); // up to a newline
while iPos > 0 do
begin
tok := Copy(bff, 1, iPos - 1);
m_LineStrings.Add(tok);
bff := Copy(bff, iPos + 1, Length(bff) - iPos);
iPos := Pos(Chr(10), bff);
end;
end;
CloseFile(vFile);
end;
end
else
if fWarnNotFound then
MessageDlg('File ' + Chr(10) + '[' + sFilNam + ']' + Chr(10) + ' not found', mtWarning, [mbOK], 0);
ReadFileToStrings := fOk;
end;
//------------------------------------------------------------------------------
// Low-level function opening the file
function TInOut.DoOpenLifeFile: Boolean;
var
fOk: Boolean;
sBff, sFstLin: String;
i: Integer;
begin
fOk := False; // Let's be pesimistic (realistic?)
SetLength(m_IOCells, 0); // nothing loaded
m_IOCellsCount := 0;
// remove leading empty lines first
while (m_LineStrings.Count > 0) and (Length(m_LineStrings.Strings[0]) = 0) do
m_LineStrings.Delete(0);
if m_LineStrings.Count > 0 then // still any lines?
begin
// find the first non-comment line
i := 0;
sFstLin := '';
while i < m_LineStrings.Count do
begin
sBff := Trim(m_LineStrings[i]);
if (Length(sBff) = 0) or StrStartsWith(sBff, '#C') or StrStartsWith(sBff, '#D') then
begin
Inc(i); // comment found, go on searching
end
else
begin
sFstLin := sBff;
i := m_LineStrings.Count;
end;
end;
if StrStartsWith(sFstLin, '#MCLife ') then // '#MCLife 1.0'
fOk := ReadFileMCL // *.MCL
else if StrStartsWith(sFstLin, '#MCell ') then // '#MCell 2.0'
fOk := ReadFileMCL // *.MCL
else if StrStartsWith(sFstLin, '#Life 1.05') then
fOk := ReadFileLIF105 // *.LIF, *.LIFE
else if StrStartsWith(sFstLin, '#P ') then
fOk := ReadFileLIF105 // *.LIF, *.LIFE
else if StrStartsWith(sFstLin, '#Life 1.06') then
fOk := ReadFileLIF106 // *.LIF, *.LIFE
else if StrStartsWith(sFstLin, 'x =') then
fOk := ReadFileRLE // RLE: *.L
else if StrStartsWith(sFstLin, 'x=') then
fOk := ReadFileRLE // RLE: *.L
else if StrStartsWith(sFstLin, '//') then
fOk := ReadFileMLF // *.MLF
else if StrStartsWith(sFstLin, '#SG') then
fOk := ReadFileSG; // Semigraphics .*oO
if not fOk then // nothing read, RLE without the 'x =' at the beginning?
begin
for i := 0 to m_LineStrings.Count - 1 do
if StrStartsWith(m_LineStrings[i], 'x =') then
begin
fOk := ReadFileRLE; // RLE: *.L
break;
end;
end;
if not fOk then // nothing read, try LIF, it's most popular
fOk := ReadFileLIF105; // *.LIF, *.LIFE
if not fOk then // nothing read, try DOS *.lif
fOk := ReadFileLIF106; // *.LIF, *.LIFE
if not fOk then // nothing read, RLE?
fOk := ReadFileRLE; // RLE: *.L
if not fOk then // The last chance: incomplete MCL
fOk := ReadFileMCL; // *.MCL
end;
DoOpenLifeFile := fOk;
end;
//------------------------------------------------------------------------------
// Read the rule rom the pattern file
function TInOut.ReadFileRule(sFilNam: String; var iFamIdx: TFamily): String;
var
vFile: System.TextFile;
bff, tok, sRules: String;
i, iPos: Integer;
tmpStrings: TStringList; // list of strings representing the file
begin
sRules := '';
iFamIdx := FAMI_LIFE;
tmpStrings := TStringList.Create; // list of strings representing the file
tmpStrings.Clear; // prepare the list of strings
if FileExists(sFilNam) then
begin
System.AssignFile(vFile, sFilNam);
Reset(vFile); // open the original file
ReadLn(vFile, bff); // get the first line
if Pos(Chr(10), bff) = 0 then // DOS file, read all lines
begin
tmpStrings.Add(bff); // add the first line
while not Eof(vFile) do // traverse the whole file
begin
ReadLn(vFile, bff); // get the line
tmpStrings.Add(bff);
end;
end
else // UNIX file, bff stores the whole file, break it to lines
begin
iPos := Pos(Chr(10), bff); // up to a newline
while iPos > 0 do
begin
tok := Copy(bff, 1, iPos - 1);
tmpStrings.Add(tok);
bff := Copy(bff, iPos + 1, Length(bff) - iPos);
iPos := Pos(Chr(10), bff);
end;
end;
CloseFile(vFile);
for i := 0 to tmpStrings.Count - 1 do
begin
// #GAME - game type
// #N - Normal rules (Conway)
// #R - Rules string
// #RULE - Rules string
bff := tmpStrings[i];
if StrStartsWith(bff, '#GAME') then // game
begin
iFamIdx := Pgm.CheckStringFamily(bff);
end
else if StrStartsWith(bff, '#RULE') then // specific rules
begin
tok := Copy(bff, 6, Length(bff));
// long rule can be splitted into several lines
sRules := sRules + Trim(tok); // set rules
end
else if StrStartsWith(bff, '#N') then // standard rules
begin
sRules := '23/3'; // standard Conway's rules
end
else if StrStartsWith(bff, '#R') then // specific rules
begin
tok := Copy(bff, 3, Length(bff));
sRules := sRules + Trim(tok); // set rules
end
else if StrStartsWith(bff, 'x =') then // RLE rules
begin
iPos := Pos('rules', bff); // rules
if iPos > 0 then
begin
iPos := iPos + 5;
sRules := GetNextToken(bff, iPos, ' =');
end
else
begin
iPos := Pos('rule', bff);
if iPos > 0 then
begin
iPos := iPos + 4;
sRules := GetNextToken(bff, iPos, ' =');
end
end;
end
end;
end
else
begin
MessageDlg('File ' + Chr(10) + '[' + sFilNam + ']' + Chr(10) + ' not found', mtWarning, [mbOK], 0);
end;
ReadFileRule := Trim(sRules);
end;
//------------------------------------------------------------------------------
// MLF - my own old temporary format
function TInOut.ReadFileMLF: Boolean;
var
bff, tok: String;
i, iCol, iRow: Integer;
iPos: Integer;
begin
ReadFileMLF := False;
// analyze all lines
for i := 0 to m_LineStrings.Count - 1 do
begin
bff := m_LineStrings[i];
bff := Trim(bff);
if Length(bff) > 0 then
if Copy(bff, 1, 2) <> '//' then // it's not a comment
begin
iPos := Pos(',', bff);
if iPos > 1 then
begin
tok := Copy(bff, 1, iPos - 1); iRow := CvtStr2Int(tok);
tok := Copy(bff, iPos + 1, 100); iCol := CvtStr2Int(tok);
AddCell(iCol, iRow, 1);
ReadFileMLF := True; // any cell added
end;
end;
end;
end;
//------------------------------------------------------------------------------
// Convert one Semigraphics character to the cell value
function TInOut.GetSGVal(ch: Char): Byte;
var
bVal: Byte;
begin
case ch of
' ': bVal := 0;
'.': bVal := 0;
'*': bVal := 1;
'o': bVal := 2;
'O': bVal := 3;
'Q': bVal := 4;
'@': bVal := 5;
'W': bVal := 6;
'#': bVal := 7
else bVal := 8;
end;
GetSGVal := bVal;
end;
//------------------------------------------------------------------------------
// #SG - Semigraphics .*oO
function TInOut.ReadFileSG: Boolean;
var
i, j, iRow: Integer;
sBff: String;
bVal: Byte;
begin
ReadFileSG := False;
// analyze all lines
iRow := 0;
for i := 0 to m_LineStrings.Count - 1 do // for all rows
begin
sBff := Trim(m_LineStrings[i]);
if StrStartsWith(sBff, '#SG') then
begin
ReadFileSG := True;
sBff := Trim(Copy(sBff, 4, Length(sBff)));
for j := 1 to Length(sBff) do
begin
bVal := GetSGVal(sBff[j]);
if bVal > 0 then
AddCell(j-1, iRow, bVal);
end;
Inc(iRow); // next line
end;
end;
end;
//------------------------------------------------------------------------------
// *.lif, *.life files line parser
// Interprets also mixed LIFE/RLE files
// Return True if at least one cell was added
function TInOut.ProcessOneLIF105Line(bff: String; var iBlkX, iBlkY: Integer; var iRow: Integer): Boolean;
var
iPos: Integer;
tok: String;
iCol: Integer;
i, j, iNum: Integer;
begin
bff := Trim(bff);
ProcessOneLIF105Line := False;
if Length(bff) > 0 then
begin
if bff[1] in ['#', '!', '/'] then // special characters
begin
if StrStartsWith(bff, '#P') then // the block position
begin
iRow := 0;
tok := Trim(Copy(bff, 3, Length(bff)));
iPos := Pos(' ', tok); // blank separates x and y
if iPos > 0 then
begin
iBlkX := CvtStr2Int(Copy(tok, 1, iPos - 1));
iBlkY := CvtStr2Int(Copy(tok, iPos + 1, Length(tok) - iPos));
end;
end
else if StrStartsWith(bff, '#N') then // standard rules
begin
m_sRules := '23/3'; // standard Conway's rules
end
else if StrStartsWith(bff, '#R') then // specific rules
begin
tok := Copy(bff, 3, Length(bff));
m_sRules := tok; // set rules
end
else if StrStartsWith(bff, '#S') then // speed
begin
tok := Copy(bff, 3, Length(bff));
m_Speed := CvtStr2Int(tok);
end
else if StrStartsWith(bff, '#D') or
StrStartsWith(bff, '#C') or
StrStartsWith(bff, '!') then // description
begin
if StrStartsWith(bff, '#D') or StrStartsWith(bff, '#C') then
begin
tok := Copy(bff, 3, Length(bff));
if Length(tok) > 0 then // remove one leading blank
if tok[1] = ' ' then
tok := Copy(tok, 2, Length(tok)-1);
end
else // '!'
tok := Copy(bff, 2, Length(bff));
m_Description.Add(tok); // add the line
end;
end
else // cells data line
begin
iCol := 0;
iNum := 0;
bff := Trim(bff); // in Life105 blanks are insignificant
for i := 1 to Length(bff) do
begin
if bff[i] in ['0'..'9'] then
iNum := iNum * 10 + CvtStr2Int(bff[i])
else
begin
if iNum = 0 then iNum := 1;
if bff[i] in ['*', 'o', 'O'] then // alive cell
begin
for j := 0 to iNum-1 do
begin
AddCell(iCol + j + iBlkX, iRow + iBlkY, 1);
end;
ProcessOneLIF105Line := True;
iCol := iCol + iNum;
end
else
begin
iCol := iCol + iNum; // blank
end;
iNum := 0;
end;
end;
Inc(iRow);
end;
end;
end;
//------------------------------------------------------------------------------
// Life 1.05
function TInOut.ReadFileLIF105: Boolean;
var
bff: String;
i, iRow: Integer;
iBlkX, iBlkY: Integer; // Block left-top corner
begin
ReadFileLIF105 := False;
iBlkX := 0;
iBlkY := 0;
iRow := 0;
// analyze all lines
for i := 0 to m_LineStrings.Count - 1 do
begin
bff := m_LineStrings[i];
if ProcessOneLIF105Line(bff, iBlkX, iBlkY, iRow) then
ReadFileLIF105 := True;
end;
end;
//------------------------------------------------------------------------------
// DOS *.lif files line parser
// Return True if at least one cell was added
function TInOut.ProcessOneLIF106Line(bff: String): Boolean;
var
iCol, iRow: Integer;
iPos: Integer;
tok: String;
begin
ProcessOneLIF106Line := False;
bff := Trim(bff);
if Length(bff) > 0 then
if (bff[1] in ['#', '/', '.', '*']) then // it's a comment
begin
if StrStartsWith(bff, '#N') then // standard rules
begin
m_sRules := '23/3'; // standard Conway's rules
end
else if StrStartsWith(bff, '#R') then // specific rules
begin
tok := Copy(bff, 3, Length(bff));
m_sRules := tok; // set rules
end
else if StrStartsWith(bff, '#S') then // speed
begin
tok := Copy(bff, 3, Length(bff));
m_Speed := CvtStr2Int(tok);
end
else if StrStartsWith(bff, '#D') or
StrStartsWith(bff, '#C') or
StrStartsWith(bff, '!') then // description
begin
if StrStartsWith(bff, '#D') or StrStartsWith(bff, '#C') then
begin
tok := Copy(bff, 3, Length(bff));
if Length(tok) > 0 then // remove one leading blank
if tok[1] = ' ' then
tok := Copy(tok, 2, Length(tok)-1);
end
else // '!'
tok := Copy(bff, 2, Length(bff));
m_Description.Add(tok); // add the line
end;
end
else
begin
iPos := Pos(' ', bff);
if iPos > 1 then
begin
tok := Copy(bff, 1, iPos - 1); iCol := CvtStr2Int(tok);
tok := Copy(bff, iPos + 1, 100); iRow := CvtStr2Int(tok);
if Board.IsCellValid(iCol, iRow) then
begin
AddCell(iCol, iRow, 1);
ProcessOneLIF106Line := True;
end;
end;
end;
end;
//------------------------------------------------------------------------------
// Life 1.06 - DOS format, cell coordinates (x y)
// Return True if at least one cell was added
function TInOut.ReadFileLIF106: Boolean;
var
bff: String;
i: Integer;
begin
ReadFileLIF106 := False;
// analyze all lines
for i := 0 to m_LineStrings.Count - 1 do
begin
bff := m_LineStrings[i];
if ProcessOneLIF106Line(bff) then
ReadFileLIF106 := True;
end;
end;
//------------------------------------------------------------------------------
// *.l, *.rle files line parser
// Return True if at least one cell was added
function TInOut.ProcessOneRLELine(bff: String; var iCol, iRow, iNum: Integer; var fEndFlg, fXYFound: Boolean): Boolean;
const
iniCol: Integer = 0;
var
i, j, iTmp: Integer;
sTmp: String;
begin
bff := Trim(bff);
ProcessOneRLELine := False;
if StrStartsWith(bff, '#D') or StrStartsWith(bff, '#C') then // strange description
begin
bff := Copy(bff, 3, Length(bff));
if Length(bff) > 0 then // remove one leading blank
if bff[1] = ' ' then
bff := Copy(bff, 2, Length(bff)-1);
m_Description.Add(bff); // add the line
end
else
begin
if fEndFlg then // past the end - the description
begin
m_Description.Add(bff); // add the line
end
else
begin
if Length(bff) > 0 then
begin
if (not fXYFound) and (Pos('x', bff) = 1) then // the first line
begin
fXYFound := True;
ProcessOneRLELine := True; // any line processed
i := Pos('x', bff); // X size
if i > 0 then
begin
i := i + 1;
sTmp := GetNextToken(bff, i, ' =,');
iCol := -(abs(CvtStr2Int(sTmp)) div 2);
iniCol := iCol;
end;
i := Pos('y', bff); // Y size
if i > 0 then
begin
i := i + 1;
sTmp := GetNextToken(bff, i, ' =,');
iRow := -(abs(CvtStr2Int(sTmp)) div 2);
end;
i := Pos('rules', bff); // rules
if i > 0 then
begin
i := i + 5;
m_sRules := GetNextToken(bff, i, ' =');
end
else
begin
i := Pos('rule', bff);
if i > 0 then
begin
i := i + 4;
m_sRules := GetNextToken(bff, i, ' =');
end
end;
i := Pos('fps', bff); // speed
if i > 0 then
begin
sTmp := Copy(bff, 4, Length(bff));
m_Speed := CvtStr2Int(sTmp);
end;
i := Pos('skip', bff); // ?
if i > 0 then
begin
// QQtodo
end;
end
else // the normal line