File: Start.pas

package info (click to toggle)
c-evo-dh 3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 10,548 kB
  • sloc: pascal: 57,426; xml: 256; makefile: 114; sh: 4
file content (1945 lines) | stat: -rw-r--r-- 66,305 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
{$INCLUDE Switches.inc}
unit Start;

interface

uses
  GameServer, Messg, ButtonBase, ButtonA, ButtonC, ButtonB, Area, Types,
  LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls,
  Menus, Registry, DrawDlg, Generics.Collections, Protocol, UMiniMap, UBrain,
  UTranslator;

type
  { TPlayerSlot }

  TPlayerSlot = class
    DiffUpBtn: TButtonC;
    DiffDownBtn: TButtonC;
    MultiBtn: TButtonC;
    OfferMultiple: Boolean;
    Rect: TRect;
  end;

  TPlayerSlots = class(TObjectList<TPlayerSlot>)
  end;

  TStartPage = (
    pgStartRandom,
    pgStartMap,
    pgNoLoad,
    pgLoad,
    pgEditRandom,
    pgEditMap,
    pgMain
  );

  TStartTab = (tbMain, tbMap, tbNew, tbPrevious);
  TMainAction = (maConfig, maManual, maCredits, maAIDev, maWeb, maNone);
  TMainActionSet = set of TMainAction;

  { TStartDlg }

  TStartDlg = class(TDrawDlg)
    PopupMenu1: TPopupMenu;
    StartBtn: TButtonA;
    Down1Btn: TButtonC2;
    Up1Btn: TButtonC2;
    List: TListBox;
    RenameBtn: TButtonB;
    DeleteBtn: TButtonB;
    Down2Btn: TButtonC2;
    Up2Btn: TButtonC2;
    QuitBtn: TButtonB;
    CustomizeBtn: TButtonC2;
    AutoDiffUpBtn: TButtonC2;
    AutoDiffDownBtn: TButtonC2;
    AutoEnemyUpBtn: TButtonC2;
    AutoEnemyDownBtn: TButtonC2;
    ReplayBtn: TButtonB;
    procedure ListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure ListKeyPress(Sender: TObject; var Key: char);
    procedure StartBtnClick(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure BrainClick(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; x, y: integer);
    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; x, y: integer);
    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; x, y: integer);
    procedure Up1BtnClick(Sender: TObject);
    procedure Down1BtnClick(Sender: TObject);
    procedure ListClick(Sender: TObject);
    procedure RenameBtnClick(Sender: TObject);
    procedure DeleteBtnClick(Sender: TObject);
    procedure DiffBtnClick(Sender: TObject);
    procedure MultiBtnClick(Sender: TObject);
    procedure Up2BtnClick(Sender: TObject);
    procedure Down2BtnClick(Sender: TObject);
    procedure QuitBtnClick(Sender: TObject);
    procedure CustomizeBtnClick(Sender: TObject);
    procedure AutoDiffUpBtnClick(Sender: TObject);
    procedure AutoDiffDownBtnClick(Sender: TObject);
    procedure AutoEnemyUpBtnClick(Sender: TObject);
    procedure AutoEnemyDownBtnClick(Sender: TObject);
    procedure ReplayBtnClick(Sender: TObject);
  private
    WorldSize: Integer;
    StartLandMass: Integer;
    MaxTurn: Integer;
    AutoEnemies: Integer;
    AutoDiff: Integer;
    MultiControl: Integer;
    Page: TStartPage;
    ShowTab: TStartTab;
    Tab: TStartTab;
    Diff0: Integer;
    BrainDefault: TBrain;
    nMapLandTiles: Integer;
    nMapStartPositions: Integer;
    LoadTurn: Integer;
    LastTurn: Integer;
    { last turn of selected former game }
    SlotAvailable: Integer;
    PlayerPopupIndex: Integer; { brain concerned by brain context menu }
    ListIndex: array [TStartTab] of Integer;
    MapFileName: string;
    FormerGames: TStringList;
    Maps: TStringList;
    LogoBuffer: TBitmap;
    // BookDate: string;
    PlayerSlots: TPlayerSlots;
    ActionsOffered: TMainActionSet;
    SelectedAction: TMainAction;
    TurnValid: Boolean;
    Tracking: Boolean;
    DefaultAI: string;
    MiniMap: TMiniMap;
    LastGame: string;
    procedure DrawAction(y, IconIndex: integer; HeaderItem, TextItem: string);
    procedure InitPopup(PlayerIndex: Integer);
    procedure OfferBrain(Brain: TBrain; FixedLines: Integer);
    procedure PaintInfo;
    procedure ChangePage(NewPage: TStartPage);
    procedure ChangeTab(NewTab: TStartTab);
    procedure UnlistBackupFile(FileName: string);
    procedure SmartInvalidate(x0, y0, x1, y1: integer;
      invalidateTab0: boolean = false); overload;
    procedure LoadConfig;
    procedure SaveConfig;
    procedure LoadLanguages;
    procedure LoadAiBrainsPictures;
    procedure UpdateInterface;
    procedure ShowSettings;
  public
    EmptyPicture: TBitmap;
    Translator: TTranslator;
    procedure UpdateFormerGames;
    procedure UpdateMaps;
  end;

var
  StartDlg: TStartDlg;


implementation

uses
  Global, Directories, Direct, ScreenTools, Inp, Back, Settings, UKeyBindings,
  ULanguages;

{$R *.lfm}

const
  // predefined world size
  // attention: lx*ly +1 MUST BE PRIME!!   and ly MUST BE EVEN
  MaxWorldSize = 9;
  WorldSizes: array [0 .. MaxWorldSize - 1] of TPoint = (
    (X: 30;  Y: 46),
    (X: 40;  Y: 52),
    (X: 50;  Y: 60),
    (X: 60;  Y: 70),
    (X: 75;  Y: 82),
    (X: 84;  Y: 90),
    (X: 100; Y: 96),
    (X: 105; Y: 120),
    (X: 126; Y: 132)
  );


  DefaultWorldTiles = 4150;
  DefaultWorldSize 	= 3;
  DefaultLandMass 	= 32;
  LandMassDelta		= 4;

  nPlOffered = 9;
  yMain = 14;
  xActionIcon = 55;
  xAction = 111;
  yAction = 60;
  ActionPitch = 56;
  ActionSideBorder = 24;
  ActionBottomBorder = 10;
  wBuffer = 91;
  x0Mini = 458; //437;
  y0Mini = 178;
  xTurnSlider = 346+27; {Reposition slider for large mini-map}
  yTurnSlider = 262+12; { "" }
  wTurnSlider = 168;
  yLogo = 74;
  xDefault = 234;
  yDefault = 148;
  x0Brain = 146;
  y0Brain = 148;
  dxBrain = 104;
  dyBrain = 80;
  xBrain: array [0 .. nPlOffered - 1] of integer = (x0Brain, x0Brain,
    x0Brain + dxBrain, x0Brain + dxBrain, x0Brain + dxBrain, x0Brain,
    x0Brain - dxBrain, x0Brain - dxBrain, x0Brain - dxBrain);
  yBrain: array [0 .. nPlOffered - 1] of integer = (y0Brain, y0Brain - dyBrain,
    y0Brain - dyBrain, y0Brain, y0Brain + dyBrain, y0Brain + dyBrain,
    y0Brain + dyBrain, y0Brain, y0Brain - dyBrain);
  TabOffset = -115;
  TabSize = 175; //159; {Increase for large mini-map}
  TabHeight = 40;

  InitAlive: array [1 .. nPl] of integer = (1, 1 + 2, 1 + 2 + 32,
    1 + 2 + 8 + 128, 1 + 2 + 8 + 32 + 128, 1 + 2 + 8 + 16 + 64 + 128,
    1 + 2 + 4 + 16 + 32 + 64 + 256, 511 - 32, 511, 511 - 32, 511, 511 - 32, 511,
    511 - 32, 511);
  InitMulti: array [nPlOffered + 1 .. nPl] of integer = (256, 256, 256 + 128,
    256 + 128, 256 + 128 + 64, 256 + 128 + 64);

  PlayerAutoDiff: array [1 .. 5] of integer = (1, 1, 2, 2, 3);
  EnemyAutoDiff: array [1 .. 5] of integer = (4, 3, 2, 1, 1);

{ TStartDlg }

procedure TStartDlg.FormCreate(Sender: TObject);
var
  x, i: Integer;
  PlayerSlot: TPlayerSlot;
  AIBrains: TBrains;
begin
  PlayerSlots := TPlayerSlots.Create;
  PlayerSlots.Count := nPlOffered;
  for I := 0 to PlayerSlots.Count - 1 do begin
    PlayerSlot := TPlayerSlot.Create;
    PlayerSlot.Rect := Bounds(xBrain[I], YBrain[I], 0, 0);
    PlayerSlots[I] := PlayerSlot;
  end;
  LoadConfig;
  LoadAssets;
  LoadLanguages;

  ActionsOffered := [maConfig, maManual, maCredits, maWeb];
  if FileExists(HomeDir + AITemplateFileName) then
    Include(ActionsOffered, maAIDev);

  BrainDefault := nil;
  for i := Brains.IndexOf(BrainRandom) to Brains.Count - 1 do
    if AnsiCompareFileName(DefaultAI, Brains[i].FileName) = 0 then
      BrainDefault := Brains[i];
  if (BrainDefault = BrainRandom) and (Brains.GetKindCount(btAI) < 2) then
    BrainDefault := nil;
  if (not Assigned(BrainDefault)) and (Brains.GetKindCount(btAI) > 0) then
    begin
      AIBrains := TBrains.Create(False);
      Brains.GetByKind(btAI, AIBrains);
      BrainDefault := Brains[0];
      FreeAndNil(AIBrains);
    end; // default AI not found, use any

  DirectDlg.Left := (Screen.Width - DirectDlg.Width) div 2;
  DirectDlg.Top := (Screen.Height - DirectDlg.Height) div 2;

  UpdateInterface;

  Canvas.Font.Assign(UniFont[ftNormal]);
  Canvas.Brush.Style := bsClear;

  QuitBtn.Hint := Phrases.Lookup('STARTCONTROLS', 0);
  ReplayBtn.Hint := Phrases.Lookup('BTN_REPLAY');
  PlayerSlots.Count := nPlOffered;
  for i := 0 to PlayerSlots.Count - 1 do
  with PlayerSlots[i] do begin
    DiffUpBtn := TButtonC.Create(self);
    DiffUpBtn.Graphic := HGrSystem.Data;
    DiffUpBtn.left := xBrain[i] - 18;
    DiffUpBtn.top := yBrain[i] + 39;
    DiffUpBtn.ButtonIndex := 1;
    DiffUpBtn.Parent := self;
    DiffUpBtn.OnClick := DiffBtnClick;
    DiffDownBtn := TButtonC.Create(self);
    DiffDownBtn.Graphic := HGrSystem.Data;
    DiffDownBtn.left := xBrain[i] - 18;
    DiffDownBtn.top := yBrain[i] + 51;
    DiffDownBtn.ButtonIndex := 0;
    DiffDownBtn.Parent := self;
    DiffDownBtn.OnClick := DiffBtnClick;
  end;
  for i := 6 to 8 do
  with PlayerSlots[i] do begin
    MultiBtn := TButtonC.Create(self);
    MultiBtn.Graphic := HGrSystem.Data;
    MultiBtn.left := xBrain[i] - 18;
    MultiBtn.top := yBrain[i];
    MultiBtn.Parent := self;
    MultiBtn.OnClick := MultiBtnClick;
    OfferMultiple := True;
  end;

  x := BiColorTextWidth(Canvas, Phrases.Lookup('STARTCONTROLS', 7)) div 2;
  CustomizeBtn.left := x0Brain + 4 - x;
  if AutoDiff < 0 then
    CustomizeBtn.ButtonIndex := 3
  else
    CustomizeBtn.ButtonIndex := 2;

  BitBltBitmap(BrainNoTerm.Picture, 0, 0, 64, 64, HGrSystem2.Data, GBrainNoTerm.Left, GBrainNoTerm.Top);
  BitBltBitmap(BrainSuperVirtual.Picture, 0, 0, 64, 64, HGrSystem2.Data, GBrainSuperVirtual.Left, GBrainSuperVirtual.Top);
  BitBltBitmap(BrainTerm.Picture, 0, 0, 64, 64, HGrSystem2.Data, GBrainTerm.Left, GBrainTerm.Top);
  BitBltBitmap(BrainRandom.Picture, 0, 0, 64, 64, HGrSystem2.Data, GBrainRandom.Left, GBrainRandom.Top);

  LoadAiBrainsPictures;

  EmptyPicture := TBitmap.Create;
  EmptyPicture.PixelFormat := pf24bit;
  EmptyPicture.SetSize(64, 64);
  EmptyPicture.Canvas.FillRect(0, 0, EmptyPicture.Width, EmptyPicture.Height);
  LogoBuffer := TBitmap.Create;
  LogoBuffer.PixelFormat := pf24bit;
  LogoBuffer.SetSize(wBuffer, 56);
  LogoBuffer.Canvas.FillRect(0, 0, LogoBuffer.Width, LogoBuffer.Height);

  MiniMap := TMiniMap.Create;
  InitButtons;

  PlayersBrain[0] := BrainTerm;
  SlotAvailable := -1;
  Tab := tbNew;
  Diff0 := 2;
  TurnValid := False;
  Tracking := False;
  FormerGames := TStringList.Create;
  UpdateFormerGames;
  MapFileName := '';
  Maps := TStringList.Create;
  UpdateMaps;
end;

procedure TStartDlg.FormDestroy(Sender: TObject);
begin
  SaveConfig;
  FreeAndNil(Translator);
  FreeAndNil(FormerGames);
  FreeAndNil(Maps);
  FreeAndNil(EmptyPicture);
  FreeAndNil(LogoBuffer);
  FreeAndNil(PlayerSlots);
  FreeAndNil(MiniMap);
end;

procedure TStartDlg.SmartInvalidate(x0, y0, x1, y1: integer;
  invalidateTab0: boolean);
var
  i: integer;
  r0, r1: HRgn;
begin
  r0 := CreateRectRgn(x0, y0, x1, y1);
  for i := 0 to ControlCount - 1 do
    if not (Controls[i] is TArea) and Controls[i].Visible then
    begin
      with Controls[i].BoundsRect do
        r1 := CreateRectRgn(left, top, Right, Bottom);
      CombineRgn(r0, r0, r1, RGN_DIFF);
      DeleteObject(r1);
    end;
  if not invalidateTab0 then begin
    r1 := CreateRectRgn(0, 0, 6 + 36, 3 + 38); // tab 0 icon
    CombineRgn(r0, r0, r1, RGN_DIFF);
    DeleteObject(r1);
  end;
  InvalidateRgn(Handle, r0, false);
  DeleteObject(r0);
end;

procedure TStartDlg.LoadConfig;
var
  Reg: TRegistry;
  I: Integer;
  S: string;
  {$IFDEF WINDOWS}
  ResolutionX, ResolutionY, ResolutionBPP, ResolutionFreq: Integer;
  {$ENDIF}
  ScreenMode: Integer;
begin
  Reg := TRegistry.Create;
  with Reg do try
    // Initialize AI assignment
    OpenKey(AppRegistryKey + '\AI', True);
    for I := 0 to nPlOffered - 1 do begin
      if I = 0 then S := ':StdIntf'
        else S := 'StdAI';
      if not ValueExists('Control' + IntToStr(I)) then
        WriteString('Control' + IntToStr(I), S);
      if not ValueExists('Diff' + IntToStr(I)) then
        WriteInteger('Diff' + IntToStr(I), 2);
    end;

    OpenKey(AppRegistryKey, True);
    if ValueExists('Gamma') then Gamma := ReadInteger('Gamma')
      else Gamma := 100;
    if Gamma <> 100 then InitGammaLookupTable;
    if ValueExists('Locale') then LocaleCode := ReadString('Locale')
      else LocaleCode := '';
    if ValueExists('WorldSize') then WorldSize := Reg.ReadInteger('WorldSize')
      else WorldSize := DefaultWorldSize;
    if ValueExists('LandMass') then StartLandMass := Reg.ReadInteger('LandMass')
      else StartLandMass := DefaultLandMass;
    if ValueExists('MaxTurn') then MaxTurn := Reg.ReadInteger('MaxTurn')
      else MaxTurn := 900;
    if ValueExists('DefaultAI') then DefaultAI := Reg.ReadString('DefaultAI')
      else DefaultAI := 'StdAI';
    if ValueExists('AutoEnemies') then AutoEnemies := Reg.ReadInteger('AutoEnemies')
      else AutoEnemies := 8;
    if ValueExists('AutoDiff') then AutoDiff := Reg.ReadInteger('AutoDiff')
      else AutoDiff := 1;
    if ValueExists('StartTab') then ShowTab := TStartTab(Reg.ReadInteger('StartTab'))
       else ShowTab := tbNew;
    if ValueExists('LastGame') then LastGame := Reg.ReadString('LastGame')
       else LastGame := '';
    if ValueExists('NetworkEnabled') then NetworkEnabled := Reg.ReadBool('NetworkEnabled')
       else NetworkEnabled := False;

    if ValueExists('ScreenMode') then
      ScreenMode := ReadInteger('ScreenMode')
      else ScreenMode := 1;
    FullScreen := ScreenMode > 0;
    if ValueExists('MultiControl') then
      MultiControl := ReadInteger('MultiControl')
      else MultiControl := 0;
    {$IFDEF WINDOWS}
    if ValueExists('ResolutionX') then
      ResolutionX := ReadInteger('ResolutionX');
    if ValueExists('ResolutionY') then
      ResolutionY := ReadInteger('ResolutionY');
    if ValueExists('ResolutionBPP') then
      ResolutionBPP := ReadInteger('ResolutionBPP');
    if ValueExists('ResolutionFreq') then
      ResolutionFreq := ReadInteger('ResolutionFreq');
    if ScreenMode = 2 then
      ChangeResolution(ResolutionX, ResolutionY, ResolutionBPP,
        ResolutionFreq);
    {$ENDIF}
  finally
    Free;
  end;

  KeyBindings.LoadFromRegistry(HKEY_CURRENT_USER, AppRegistryKey + '\KeyBindings');
end;

procedure TStartDlg.SaveConfig;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  with Reg do try
    OpenKey(AppRegistryKey, True);
    WriteInteger('WorldSize', WorldSize);
    WriteInteger('LandMass', StartLandMass);
    WriteString('Locale', LocaleCode);
    WriteInteger('Gamma', Gamma);
    if FullScreen then WriteInteger('ScreenMode', 1)
      else WriteInteger('ScreenMode', 0);
    WriteInteger('MultiControl', MultiControl);
    WriteInteger('StartTab', Integer(ShowTab));
    WriteString('LastGame', LastGame);
    WriteBool('NetworkEnabled', NetworkEnabled);
  finally
    Free;
  end;

  KeyBindings.SaveToRegistry(HKEY_CURRENT_USER, AppRegistryKey + '\KeyBindings');
end;

procedure TStartDlg.LoadLanguages;
var
  I: Integer;
begin
  Translator := TTranslator.Create(nil);
  with Translator, Languages do begin
    AddNew('zh-Hant', 'Traditional Chinese');
    AddNew('zh-Hans', 'Simplified Chinese');
    SearchByCode('').Available := True;

    for I := 1 to Languages.Count - 1 do
    with Languages[I] do begin
      Available := DirectoryExists(HomeDir + 'Localization' + DirectorySeparator + Code) or (Code = 'en');
    end;
  end;
end;

procedure TStartDlg.LoadAiBrainsPictures;
var
  AiBrains: TBrains;
begin
  AiBrains := TBrains.Create(False);
  try
    Brains.GetByKind(btAI, AiBrains);
    AiBrains.LoadPictures;
  finally
    FreeAndNil(AiBrains);
  end;
end;

procedure TStartDlg.UpdateInterface;
var
  r0, r1: HRgn;
  Location: TPoint;
begin
  if FullScreen then begin
    Location := Point((Screen.Width - 800) * 3 div 8,
      Screen.Height - Height - (Screen.Height - 600) div 3);
    BoundsRect := Bounds(Location.X, Location.Y, Width, Height);

    r0 := CreateRectRgn(0, 0, Width, Height);
    r1 := CreateRectRgn(TabOffset + 4 * TabSize + 2, 0, Width, TabHeight);
    CombineRgn(r0, r0, r1, RGN_DIFF);
    DeleteObject(r1);
    r1 := CreateRectRgn(QuitBtn.Left, QuitBtn.Top, QuitBtn.Left + QuitBtn.Width,
      QuitBtn.top + QuitBtn.Height);
    CombineRgn(r0, r0, r1, RGN_OR);
    DeleteObject(r1);
    SetWindowRgn(Handle, r0, False);
    DeleteObject(r0); // causes crash with Windows 95
  end else begin
    BoundsRect := Bounds((Screen.Width - Width) div 2,
      (Screen.Height - Height) div 2, Width, Height)
  end;
end;

procedure TStartDlg.ShowSettings;
begin
  SettingsDlg := TSettingsDlg.Create(nil);
  if SettingsDlg.ShowModal = mrOk then begin
    LoadAssets;
    Invalidate;
    UpdateInterface;
    Background.UpdateInterface;
  end;
  FreeAndNil(SettingsDlg);
end;

procedure TStartDlg.DrawAction(y, IconIndex: integer; HeaderItem, TextItem: string);
begin
  Canvas.Font.Assign(UniFont[ftCaption]);
  Canvas.Font.Style := Canvas.Font.Style + [fsUnderline];
  RisedTextOut(Canvas, xAction, y - 3, Phrases2.Lookup(HeaderItem));
  Canvas.Font.Assign(UniFont[ftNormal]);
  BiColorTextOut(Canvas, Colors.Canvas.Pixels[clkAge0 - 1, cliDimmedText],
    $000000, xAction, y + 21, Phrases2.Lookup(TextItem));

  UnshareBitmap(LogoBuffer);
  BitBltCanvas(LogoBuffer.Canvas, 0, 0, 50, 50, Canvas,
    xActionIcon - 2, y - 2);
  GlowFrame(LogoBuffer, 8, 8, 34, 34, $202020);
  BitBltCanvas(Canvas, xActionIcon - 2, y - 2, 50, 50,
    LogoBuffer.Canvas, 0, 0);
  BitBltCanvas(Canvas, xActionIcon, y, 40, 40, BigImp.Canvas,
    (IconIndex mod 7) * xSizeBig + 8, (IconIndex div 7) * ySizeBig);
  RFrame(Canvas, xActionIcon - 1, y - 1, xActionIcon + 40, y + 40,
    $000000, $000000);
end;

procedure TStartDlg.FormPaint(Sender: TObject);
const
  TabNames: array[TStartTab] of Integer = (0, 11, 3, 4);
var
  i, w, h, xMini, yMini, y: integer;
  s: string;
  Tab2: TStartTab;
  MainAction: TMainAction;
begin
  PaintBackground(self, 3, 3, TabOffset + 4 * TabSize - 4, TabHeight - 3);
  PaintBackground(self, 3, TabHeight + 3, ClientWidth - 6,
    ClientHeight - TabHeight - 6);
  with Canvas do
  begin
    Brush.Color := $000000;
    FillRect(Rect(0, 1, ClientWidth, 3));
    FillRect(Rect(TabOffset + 4 * TabSize + 2, 0, ClientWidth, TabHeight));
    Brush.Style := bsClear;
  end;
  if Page in [pgStartRandom, pgStartMap] then
  begin
    Frame(Canvas, 328, yMain + 112 - 15, ClientWidth, Up2Btn.top + 38,
      MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
    if AutoDiff > 0 then
    begin
      Frame(Canvas, -1 { x0Brain-dxBrain } ,
        yMain + 112 - 15 { Up1Btn.Top-12 }{ y0Brain-dyBrain } ,
        x0Brain + dxBrain + 64, Up2Btn.top + 38 { y0Brain+dyBrain+64 } ,
        MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
    end;
  end
  else if Page <> pgMain then
    Frame(Canvas, 328, Up1Btn.top - 15, ClientWidth, Up2Btn.top + 38,
      MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
  Frame(Canvas, 0, 0, ClientWidth - 1, ClientHeight - 1, 0, 0);

  // draw tabs
  Frame(Canvas, 2, 2 + 2 * integer(Tab <> tbMain), TabOffset + (0 + 1) * TabSize - 1,
    TabHeight, MainTexture.ColorBevelLight, MainTexture.ColorBevelShade);
  Frame(Canvas, 1, 1 + 2 * integer(Tab <> tbMain), TabOffset + (0 + 1) * TabSize,
    TabHeight, MainTexture.ColorBevelLight, MainTexture.ColorBevelShade);
  Canvas.Pixels[1, 1 + 2 * integer(Tab <> tbMain)] := MainTexture.ColorBevelShade;
  for Tab2 := tbMap to tbPrevious do
  begin
    Frame(Canvas, TabOffset + Integer(Tab2) * TabSize + 2, 2 + 2 * integer(Tab <> Tab2),
      TabOffset + (Integer(Tab2) + 1) * TabSize - 1, TabHeight, MainTexture.ColorBevelLight,
      MainTexture.ColorBevelShade);
    Frame(Canvas, TabOffset + Integer(Tab2) * TabSize + 1, 1 + 2 * integer(Tab <> Tab2),
      TabOffset + (Integer(Tab2) + 1) * TabSize, TabHeight, MainTexture.ColorBevelLight,
      MainTexture.ColorBevelShade);
    Canvas.Pixels[TabOffset + Integer(Tab2) * TabSize + 1, 1 + 2 * integer(Tab <> Tab2)] :=
      MainTexture.ColorBevelShade;
  end;
  Canvas.Font.Assign(UniFont[ftNormal]);
  for Tab2 := tbMap to tbPrevious do
  begin
    s := Phrases.Lookup('STARTCONTROLS', TabNames[Tab2]);
    RisedTextOut(Canvas, TabOffset + Integer(Tab2) * TabSize + 1 +
      (TabSize - BiColorTextWidth(Canvas, s)) div 2,
      10 + 2 * integer(Tab <> Tab2), s);
  end;
  Frame(Canvas, TabOffset + 4 * TabSize + 1, -1, ClientWidth, TabHeight,
    $000000, $000000);
  Frame(Canvas, 1, TabHeight + 1, ClientWidth - 2, ClientHeight - 2,
    MainTexture.ColorBevelLight, MainTexture.ColorBevelShade);
  Frame(Canvas, 2, TabHeight + 2, ClientWidth - 3, ClientHeight - 3,
    MainTexture.ColorBevelLight, MainTexture.ColorBevelShade);
  if Tab = tbMain then
  begin
    PaintBackground(self, 3, TabHeight - 1, TabSize - 4 - 3 + TabOffset + 3, 4);
    Canvas.Pixels[2, TabHeight] := MainTexture.ColorBevelLight;
  end
  else
  begin
    PaintBackground(self, TabOffset + 3 + Integer(Tab) * TabSize, TabHeight - 1,
      TabSize - 4, 4);
    Canvas.Pixels[TabOffset + Integer(Tab) * TabSize + 2, TabHeight] :=
      MainTexture.ColorBevelLight;
  end;
  Canvas.Pixels[TabOffset + (Integer(Tab) + 1) * TabSize - 1, TabHeight + 1] :=
    MainTexture.ColorBevelShade;
  if Tab < tbPrevious then
    Frame(Canvas, TabOffset + (Integer(Tab) + 1) * TabSize + 1, 3,
      TabOffset + (Integer(Tab) + 1) * TabSize + 2, TabHeight, MainTexture.ColorBevelShade,
      MainTexture.ColorBevelShade); // Tab shadow

  // Paint menu logo
  UnshareBitmap(LogoBuffer);
  BitBltCanvas(LogoBuffer.Canvas, 0, 0, MenuLogo.Width, MenuLogo.Height, Canvas, 6,
    3 + 2 * integer(Tab <> tbMain));

  ImageOp_BCC(LogoBuffer, Templates.Data, 0, 0, MenuLogo.Left, MenuLogo.Top,
    MenuLogo.Width, MenuLogo.Height - 9, $BFBF20, $4040DF); // logo part 1
  ImageOp_BCC(LogoBuffer, Templates.Data, 10, 27, MenuLogo.Left + 10,
    MenuLogo.Top + 27, MenuLogo.Width - 10, 9, $BFBF20, $4040DF); // logo part 2
  BitBltCanvas(Canvas, 6, 3 + 2 * integer(Tab <> tbMain), MenuLogo.Width, MenuLogo.Height,
    LogoBuffer.Canvas, 0, 0);

  if Page = pgMain then begin
    if SelectedAction <> maNone then // mark selected action
      for i := 0 to (ClientWidth - 2 * ActionSideBorder) div wBuffer + 1 do
      begin
        w := ClientWidth - 2 * ActionSideBorder - i * wBuffer;
        if w > wBuffer then
          w := wBuffer;
        h := ActionPitch;
        if yAction + Integer(SelectedAction) * ActionPitch - 8 + h > ClientHeight - ActionBottomBorder
        then
          h := ClientHeight - ActionBottomBorder -
            (yAction + Integer(SelectedAction) * ActionPitch - 8);

        UnshareBitmap(LogoBuffer);
        BitBltCanvas(LogoBuffer.Canvas, 0, 0, w, h, Canvas,
          ActionSideBorder + i * wBuffer, yAction + Integer(SelectedAction) * ActionPitch
          - 8);
        MakeBlue(LogoBuffer, 0, 0, w, h);
        BitBltCanvas(Canvas, ActionSideBorder + i * wBuffer,
          yAction + Integer(SelectedAction) * ActionPitch - 8, w, h,
          LogoBuffer.Canvas, 0, 0);
      end;
    y := yAction;
    for MainAction := Low(TMainActionSet) to High(TMainActionSet) do
    begin
      if MainAction in ActionsOffered then
        case MainAction of
          maConfig: DrawAction(y, 25, 'ACTIONHEADER_CONFIG', 'ACTION_CONFIG');
          maManual: DrawAction(y, 19, 'ACTIONHEADER_MANUAL', 'ACTION_MANUAL');
          maCredits: DrawAction(y, 22, 'ACTIONHEADER_CREDITS', 'ACTION_CREDITS');
          maAIDev: DrawAction(y, 24, 'ACTIONHEADER_AIDEV', 'ACTION_AIDEV');
          maWeb:
            begin
              Canvas.Font.Assign(UniFont[ftCaption]);
              // Canvas.Font.Style:=Canvas.Font.Style+[fsUnderline];
              RisedTextOut(Canvas, xActionIcon + 99, y,
                Format(Phrases2.Lookup('ACTIONHEADER_WEB'), [CevoHomepageShort]));
              Canvas.Font.Assign(UniFont[ftNormal]);

              UnshareBitmap(LogoBuffer);
              BitBltCanvas(LogoBuffer.Canvas, 0, 0, LinkArrows.Width, LinkArrows.Height, Canvas,
                xActionIcon, y + 2);
              ImageOp_BCC(LogoBuffer, Templates.Data, Point(0, 0), LinkArrows.BoundsRect, 0,
                Colors.Canvas.Pixels[clkAge0 - 1, cliDimmedText]);
              BitBltCanvas(Canvas, xActionIcon, y + 2, LinkArrows.Width, LinkArrows.Height,
                LogoBuffer.Canvas, 0, 0);
            end;
        end;
      Inc(y, ActionPitch);
    end;
  end
  else if Page in [pgStartRandom, pgStartMap] then
  begin
    UnderlinedTitleValue(Canvas, Phrases.Lookup('STARTCONTROLS', 10),
      TurnToString(MaxTurn), 344, y0Mini + 61+12, 170);

    s := Phrases.Lookup('STARTCONTROLS', 7);
    w := Canvas.TextWidth(s);
    LoweredTextOut(Canvas, -2, MainTexture, x0Brain + 32 - w div 2,
      y0Brain + dyBrain + 69, s);

    InitOrnament;
    if AutoDiff < 0 then
    begin
      for i := 12 to 19 do
        if (i < 13) or (i > 17) then begin
          BitBltCanvas(Canvas, 9 + i * 27, yLogo - 2, Ornament.Width, Ornament.Height,
            HGrSystem2.Mask.Canvas, Ornament.Left, Ornament.Top, SRCAND);
          BitBltCanvas(Canvas, 9 + i * 27, yLogo - 2, Ornament.Width, Ornament.Height,
            HGrSystem2.Data.Canvas, Ornament.Left, Ornament.Top, SRCPAINT);
        end;
      PaintLogo(Canvas, 69 + 11 * 27, yLogo, MainTexture.ColorBevelLight,
        MainTexture.ColorBevelShade);

      for i := 0 to nPlOffered - 1 do
        if 1 shl i and SlotAvailable <> 0 then
        begin
          if Assigned(PlayersBrain[i]) then
            FrameImage(Canvas, PlayersBrain[i].Picture, xBrain[i], yBrain[i],
              64, 64, 0, 0, true)
          else
            FrameImage(Canvas, EmptyPicture, xBrain[i], yBrain[i], 64, 64,
              0, 0, true);
          if Assigned(PlayersBrain[I]) and (PlayersBrain[i].Kind in [btTerm, btRandom, btAI]) then
          begin
            BitBltCanvas(Canvas, xBrain[i] - 18, yBrain[i] + 19, 12, 14,
              HGrSystem.Data.Canvas, 134 + (Difficulty[i] - 1) *
              13, 28);
            Frame(Canvas, xBrain[i] - 19, yBrain[i] + 18, xBrain[i] - 18 + 12,
              yBrain[i] + (19 + 14), $000000, $000000);
            RFrame(Canvas, PlayerSlots[i].DiffUpBtn.left - 1, PlayerSlots[i].DiffUpBtn.top - 1,
              PlayerSlots[i].DiffUpBtn.left + 12, PlayerSlots[i].DiffUpBtn.top + 24,
              MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
            with Canvas do
            begin
              Brush.Color := $000000;
              FillRect(Rect(xBrain[i] - 5, yBrain[i] + 25, xBrain[i] - 2,
                yBrain[i] + 27));
              Brush.Style := bsClear;
            end;
            if PlayerSlots[I].OfferMultiple then
            begin
              RFrame(Canvas, PlayerSlots[I].MultiBtn.left - 1, PlayerSlots[I].MultiBtn.top - 1,
                PlayerSlots[I].MultiBtn.left + 12, PlayerSlots[I].MultiBtn.top + 12,
                MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
              BitBltCanvas(Canvas, xBrain[i] - 31, yBrain[i], 13, 12,
                HGrSystem.Data.Canvas, 88, 47);
            end;
          end;
          if Assigned(PlayersBrain[i]) then
          begin
            PlayerSlots[i].DiffUpBtn.Hint := Format(Phrases.Lookup('STARTCONTROLS', 9),
              [PlayersBrain[i].Name]);
            PlayerSlots[i].DiffDownBtn.Hint := PlayerSlots[i].DiffUpBtn.Hint;
          end;
        end;
    end
    else
    begin
      DLine(Canvas, 24, 198, yMain + 140 + 19, MainTexture.ColorBevelLight,
        MainTexture.ColorBevelShade);
      RisedTextOut(Canvas, 24 { x0Brain+32-BiColorTextWidth(Canvas,s) div 2 } ,
        yMain + 140 { y0Mini-77 } , Phrases.Lookup('STARTCONTROLS', 15));
      if Page = pgStartRandom then
        s := IntToStr(AutoEnemies)
      else if nMapStartPositions = 0 then
        s := '0'
      else
        s := IntToStr(nMapStartPositions - 1);
      RisedTextOut(Canvas, 198 - BiColorTextWidth(Canvas, s), yMain + 140, s);

      DLine(Canvas, 24, xDefault - 6, yMain + 164 + 19,
        MainTexture.ColorBevelLight, MainTexture.ColorBevelShade);
      RisedTextOut(Canvas, 24 { x0Brain+32-BiColorTextWidth(Canvas,s) div 2 } ,
        yMain + 164 { y0Mini-77 } , Phrases.Lookup('STARTCONTROLS', 16));
      if AutoDiff = 1 then
        FrameImage(Canvas, Brains.GetBeginner.Picture, xDefault, yDefault, 64,
          64, 0, 0, false)
      else
        FrameImage(Canvas, BrainDefault.Picture, xDefault, yDefault, 64, 64,
          0, 0, true);
      DLine(Canvas, 56, 272, y0Mini + 61 + 19, MainTexture.ColorBevelLight,
        MainTexture.ColorBevelShade);

      RisedTextOut(Canvas, 56, y0Mini + 61,
        Phrases.Lookup('STARTCONTROLS', 14));
      s := Phrases.Lookup('AUTODIFF', AutoDiff - 1);
      RisedTextOut(Canvas, 272 - BiColorTextWidth(Canvas, s), y0Mini + 61, s);

      for i := 0 to 19 do
        if (i < 2) or (i > 6) then begin
          BitBltCanvas(Canvas, 9 + i * 27, yLogo - 2, Ornament.Width, Ornament.Height,
            HGrSystem2.Mask.Canvas, Ornament.Left, Ornament.Top, SRCAND);
          BitBltCanvas(Canvas, 9 + i * 27, yLogo - 2, Ornament.Width, Ornament.Height,
            HGrSystem2.Data.Canvas, Ornament.Left, Ornament.Top, SRCPAINT);
        end;
      PaintLogo(Canvas, 69, yLogo, MainTexture.ColorBevelLight,
        MainTexture.ColorBevelShade);
    end;
  end
  else if Page = pgLoad then
  begin
    // RisedTextOut(Canvas,x0Mini+2-BiColorTextWidth(Canvas,BookDate) div 2,y0Mini-73,BookDate);
    if LastTurn > 0 then
    begin
      PaintProgressBar(Canvas, 6, xTurnSlider, yTurnSlider, 0,
        LoadTurn * wTurnSlider div LastTurn, wTurnSlider, MainTexture);
      Frame(Canvas, xTurnSlider - 2, yTurnSlider - 2, xTurnSlider + wTurnSlider
        + 1, yTurnSlider + 8, $B0B0B0, $FFFFFF);
      RFrame(Canvas, xTurnSlider - 3, yTurnSlider - 3, xTurnSlider + wTurnSlider
        + 2, yTurnSlider + 9, $FFFFFF, $B0B0B0);
    end
    else
      DLine(Canvas, 344, 514, y0Mini + 61+12 + 19, MainTexture.ColorBevelLight,
        MainTexture.ColorBevelShade);
    RisedTextOut(Canvas, 344+48, y0Mini + 61+12, Phrases.Lookup('STARTCONTROLS', 8)); { Shift right for larger mini-map}
    s := TurnToString(LoadTurn);
    RisedTextOut(Canvas, 518 - BiColorTextWidth(Canvas, s), y0Mini + 61+12, s);
  end
  else if Page = pgEditRandom then // {BigMap}
  begin
    UnderlinedTitleValue(Canvas, Phrases.Lookup('STARTCONTROLS', 5),
      IntToStr((WorldSizes[WorldSize].X * WorldSizes[WorldSize].Y * 20 +
      DefaultWorldTiles div 2) div DefaultWorldTiles * 5) + '%',
      344, y0Mini - 77 -12, 170);
    UnderlinedTitleValue(Canvas, Phrases.Lookup('STARTCONTROLS', 6),
      IntToStr(StartLandMass) + '%', 344, y0Mini + 61 +12, 170);
  end
  else if Page = pgEditMap then
  begin
    // DLine(Canvas,344,514,y0Mini+61+19,MainTexture.ColorBevelLight,MainTexture.ColorBevelShade);
    s := Format(Phrases2.Lookup('MAPPROP'),
      [(nMapLandTiles * 100 + 556) div 1112,
      // 1112 is typical for world with 100% size and default land mass
      nMapStartPositions]);
    RisedTextOut(Canvas, x0Mini - BiColorTextWidth(Canvas, s) div 2,
      y0Mini + 61, s);
  end;

  if StartBtn.Visible then
    BtnFrame(Canvas, StartBtn.BoundsRect, MainTexture);
  if Up2Btn.Visible then
    RFrame(Canvas, Up2Btn.left - 1, Up2Btn.top - 1, Up2Btn.left + bC2w,
      Up2Btn.top + 2*bC2w, MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
  if Up1Btn.Visible then
    RFrame(Canvas, Up1Btn.left - 1, Up1Btn.top - 1, Up1Btn.left + bC2w,
      Up1Btn.top + 2*bC2w, MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
  if AutoDiffUpBtn.Visible then
    RFrame(Canvas, AutoDiffUpBtn.left - 1, AutoDiffUpBtn.top - 1,
      AutoDiffUpBtn.left + bC2w, AutoDiffUpBtn.top + 2*bC2w, MainTexture.ColorBevelShade,
      MainTexture.ColorBevelLight);
  if AutoEnemyUpBtn.Visible then
    RFrame(Canvas, AutoEnemyUpBtn.left - 1, AutoEnemyUpBtn.top - 1,
      AutoEnemyUpBtn.left + bC2w, AutoEnemyUpBtn.top + 2*bC2w,
      MainTexture.ColorBevelShade, MainTexture.ColorBevelLight);
  if CustomizeBtn.Visible then
    RFrame(Canvas, CustomizeBtn.left - 1, CustomizeBtn.top - 1,
      CustomizeBtn.left + bC2w, CustomizeBtn.top + bC2w, MainTexture.ColorBevelShade,
      MainTexture.ColorBevelLight);
  if List.Visible then
    EditFrame(Canvas, List.BoundsRect, MainTexture);
  if RenameBtn.Visible then
    BtnFrame(Canvas, RenameBtn.BoundsRect, MainTexture);
  if DeleteBtn.Visible then
    BtnFrame(Canvas, DeleteBtn.BoundsRect, MainTexture);
  if Page = pgLoad then
    BtnFrame(Canvas, ReplayBtn.BoundsRect, MainTexture);

  if not (Page in [pgMain, pgNoLoad]) then
  begin
    xMini := x0Mini - MiniMap.Size.X;
    yMini := y0Mini - MiniMap.Size.Y div 2;
    Frame(Canvas, xMini, yMini, xMini + 3 + MiniMap.Size.X * 2,
      yMini + 3 + MiniMap.Size.Y, MainTexture.ColorBevelLight,
      MainTexture.ColorBevelShade);
    Frame(Canvas, xMini + 1, yMini + 1, xMini + 2 + MiniMap.Size.X * 2,
      yMini + 2 + MiniMap.Size.Y, MainTexture.ColorBevelShade,
      MainTexture.ColorBevelLight);

    s := '';
    if MiniMap.Mode = mmPicture then
    begin
      BitBltCanvas(Canvas, xMini + 2, yMini + 2, MiniMap.Size.X * 2, MiniMap.Size.Y,
        MiniMap.Bitmap.Canvas, 0, 0);
      if Page = pgStartRandom then
        s := Phrases.Lookup('RANMAP')
    end
    else if MiniMap.Mode = mmMultiPlayer then
      s := Phrases.Lookup('MPMAP')
    else if Page = pgStartMap then
      s := Copy(MapFileName, 1, Length(MapFileName) - Length(CevoMapExt))
    else if Page = pgEditMap then
      s := List.Items[List.ItemIndex]
    else if Page = pgNoLoad then
      s := Phrases.Lookup('NOGAMES');
    if s <> '' then
      RisedTextOut(Canvas, x0Mini + 2 - BiColorTextWidth(Canvas, s) div 2,
        y0Mini - 8, s);
  end;
end;

procedure TStartDlg.FormShow(Sender: TObject);
begin
  {$IFDEF UNIX}
  ShowInTaskBar := stAlways;
  {$ENDIF}
  MainTexture.Age := -1;
  List.Font.Color := MainTexture.ColorMark;

  Fill(EmptyPicture.Canvas, Bounds(0, 0, 64, 64),
    Point((Maintexture.Width - 64) div 2, (Maintexture.Height - 64) div 2));

  DarkenImage(EmptyPicture, 28);

  Difficulty[0] := Diff0;

  SelectedAction := maNone;
  if ShowTab = tbPrevious then
    PreviewMap(StartLandMass); // avoid delay on first TabX change
  ChangeTab(ShowTab);
  Background.Enabled := False;
end;

procedure TStartDlg.UnlistBackupFile(FileName: string);
var
  I: Integer;
begin
  if FileName[1] <> '~' then
    FileName := '~' + FileName;
  I := FormerGames.Count - 1;
  while (I >= 0) and (AnsiCompareFileName(FormerGames[I], FileName) <> 0) do
    Dec(I);
  if I >= 0 then
  begin
    FormerGames.Delete(I);
    if ListIndex[tbNew] = I then
      ListIndex[tbNew] := 0;
  end;
end;

procedure TStartDlg.StartBtnClick(Sender: TObject);
var
  I, GameCount, MapCount: Integer;
  FileName: string;
  Reg: TRegistry;
begin
  case Page of
    pgLoad:
      begin // load
        FileName := List.Items[List.ItemIndex];
        if LoadGame(GetSavedDir + DirectorySeparator, FileName + CevoExt, LoadTurn, false)
        then
          UnlistBackupFile(FileName)
        else
          SimpleMessage(Phrases.Lookup('LOADERR'));
        SlotAvailable := -1;
      end;
    pgStartRandom, pgStartMap:
      if Assigned(PlayersBrain[0]) then
      begin
        if (Page = pgStartMap) and (nMapStartPositions = 0) and (AutoDiff > 0)
        then
        begin
          SimpleMessage(Phrases.Lookup('NOSTARTPOS'));
          Exit;
        end;

        Reg := TRegistry.Create;
        with Reg do
        try
          OpenKey(AppRegistryKey, true);
          if ValueExists('GameCount') then GameCount := ReadInteger('GameCount')
            else GameCount := 0;

          if (AutoDiff < 0) and (PlayersBrain[0].Kind = btNoTerm) then
            FileName := 'Round' + IntToStr(GetProcessID())
          else begin
            Inc(GameCount);
            FileName := Format(Phrases.Lookup('GAME'), [GameCount]);
          end;

          // Save settings and AI assignment
          if Page = pgStartRandom then begin
            SaveConfig;
            OpenKey(AppRegistryKey + '\AI', True);
            if AutoDiff < 0 then
              for I := 0 to nPlOffered - 1 do begin
                if not Assigned(PlayersBrain[I]) then
                  Reg.WriteString('Control' + IntToStr(I), '')
                else Reg.WriteString('Control' + IntToStr(I),
                  PlayersBrain[I].FileName);
                WriteInteger('Diff' + IntToStr(I), Difficulty[I]);
              end;
          end;

          OpenKey(AppRegistryKey, True);
          if BrainDefault.Kind <> btNetworkClient then begin
            if AutoDiff > 0 then begin
              WriteString('DefaultAI', BrainDefault.FileName);
              SlotAvailable := 0; // PlayerSlot will be invalid hereafter
              PlayersBrain[0] := BrainTerm;
              Difficulty[0] := PlayerAutoDiff[AutoDiff];
              for I := 1 to nPl - 1 do
                if (Page = pgStartRandom) and (I <= AutoEnemies) or
                  (Page = pgStartMap) and (I < nMapStartPositions) then begin
                  if AutoDiff = 1 then PlayersBrain[I] := Brains.GetBeginner
                    else PlayersBrain[I] := BrainDefault;
                  Difficulty[I] := EnemyAutoDiff[AutoDiff];
                end else PlayersBrain[I] := nil;
            end else begin
              for I := 6 to 8 do
                if (PlayersBrain[0].Kind <> btNoTerm) and (MultiControl and (1 shl I) <> 0)
                then begin
                  PlayersBrain[I + 3] := PlayersBrain[I];
                  Difficulty[I + 3] := Difficulty[I];
                  PlayersBrain[I + 6] := PlayersBrain[I];
                  Difficulty[I + 6] := Difficulty[I];
                end else begin
                  PlayersBrain[I + 3] := nil;
                  PlayersBrain[I + 6] := nil;
                end;
            end;
          end;

          WriteInteger('AutoDiff', AutoDiff);
          WriteInteger('AutoEnemies', AutoEnemies);
          WriteInteger('MaxTurn', MaxTurn);
          WriteInteger('GameCount', GameCount);
        finally
          Free;
        end;

        StartNewGame(GetSavedDir + DirectorySeparator, FileName + CevoExt, MapFileName,
          WorldSizes[WorldSize].X, WorldSizes[WorldSize].Y, StartLandMass, MaxTurn);
        UnlistBackupFile(FileName);
      end;
    pgEditMap:
      EditMap(GetMapsDir + DirectorySeparator + MapFileName, lxmax, lymax, StartLandMass);
    pgEditRandom: // new map
      begin
        Reg := TRegistry.Create;
        with Reg do
        try
          OpenKey(AppRegistryKey, True);
          if ValueExists('MapCount') then MapCount := ReadInteger('MapCount')
            else MapCount := 0;
          Inc(MapCount);
          WriteInteger('MapCount', MapCount);
        finally
          Free;
        end;
        MapFileName := Format(Phrases.Lookup('MAP'), [MapCount]) + CevoMapExt;
        EditMap(GetMapsDir + DirectorySeparator + MapFileName,
          WorldSizes[WorldSize].X, WorldSizes[WorldSize].Y, StartLandMass);
      end;
  end;
end;

procedure TStartDlg.ListKeyPress(Sender: TObject; var Key: char);
begin
  if Key = #13 then StartBtnClick(Sender);
end;

procedure TStartDlg.ListKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
const
  DelKey = 46;
begin
  if Key = DelKey then DeleteBtnClick(Sender)
    else FormKeyDown(Sender, Key, Shift);
end;

procedure TStartDlg.PaintInfo;
begin
  case Page of
    pgStartRandom: begin
      MiniMap.Mode := mmPicture;
      MiniMap.PaintRandom(3, StartLandMass, WorldSizes[WorldSize]);
    end;
    pgNoLoad: begin
      MiniMap.Mode := mmNone;
      MiniMap.Size := WorldSizes[DefaultWorldSize];
    end;
    pgLoad: begin
        MiniMap.LoadFromLogFile(GetSavedDir + DirectorySeparator +
          List.Items[List.ItemIndex] + CevoExt, LastTurn, WorldSizes[DefaultWorldSize]);
        // BookDate:=DateToStr(FileDateToDateTime(FileAge(FileName)));
        if not TurnValid then  begin
          LoadTurn := LastTurn;
          SmartInvalidate(xTurnSlider - 2, y0Mini + 61,
            xTurnSlider + wTurnSlider + 2, yTurnSlider + 9);
        end;
        TurnValid := True;
      end;
    pgEditRandom: begin
      MapFileName := '';
      MiniMap.Mode := mmPicture;
      MiniMap.PaintRandom(4, StartLandMass, WorldSizes[WorldSize]);
    end;
    pgStartMap, pgEditMap:
      begin
        if Page = pgEditMap then
          MapFileName := List.Items[List.ItemIndex] + CevoMapExt;
        MiniMap.LoadFromMapFile(GetMapsDir + DirectorySeparator + MapFileName,
          nMapLandTiles, nMapStartPositions);
        if Page = pgEditMap then
          SmartInvalidate(x0Mini - 112, y0Mini + 61, x0Mini + 112, y0Mini + 91);
      end;
  end;
  SmartInvalidate(x0Mini - lxmax, y0Mini - lymax div 2,
    x0Mini - lxmax + 2 * lxmax + 4, y0Mini - lymax div 2 + lymax + 4);
end;

procedure TStartDlg.BrainClick(Sender: TObject);
var
  I: Integer;
begin
  // Play('BUTTON_UP');
  if PlayerPopupIndex < 0 then
  begin // change default AI
    BrainDefault := Brains[TMenuItem(Sender).Tag];
    SmartInvalidate(xDefault, yDefault, xDefault + 64, yDefault + 64);
  end
  else
  begin
    if Assigned(PlayersBrain[PlayerPopupIndex]) then
      PlayersBrain[PlayerPopupIndex].Flags := PlayersBrain[PlayerPopupIndex].Flags and not fUsed;
    if TMenuItem(Sender).Tag = -1 then begin
      PlayersBrain[PlayerPopupIndex] := nil;
      PlayerSlots[PlayerPopupIndex].DiffUpBtn.Visible := False;
      PlayerSlots[PlayerPopupIndex].DiffDownBtn.Visible := False;
      if PlayerSlots[PlayerPopupIndex].OfferMultiple then begin
        PlayerSlots[PlayerPopupIndex].MultiBtn.Visible := False;
        PlayerSlots[PlayerPopupIndex].MultiBtn.ButtonIndex := 2 + (MultiControl shr PlayerPopupIndex) and 1;
      end;
      MultiControl := MultiControl and not (1 shl PlayerPopupIndex);
    end else begin
      PlayersBrain[PlayerPopupIndex] := Brains[TMenuItem(Sender).Tag];
      PlayerSlots[PlayerPopupIndex].DiffUpBtn.Visible := PlayersBrain[PlayerPopupIndex].Kind in [btTerm, btRandom, btAI];
      PlayerSlots[PlayerPopupIndex].DiffDownBtn.Visible := PlayersBrain[PlayerPopupIndex].Kind in [btTerm, btRandom, btAI];
      if PlayerSlots[PlayerPopupIndex].OfferMultiple then begin
        PlayerSlots[PlayerPopupIndex].MultiBtn.Visible := PlayersBrain[PlayerPopupIndex].Kind in [btTerm, btRandom, btAI];
        PlayerSlots[PlayerPopupIndex].MultiBtn.ButtonIndex := 2 + (MultiControl shr PlayerPopupIndex) and 1;
      end;
      PlayersBrain[PlayerPopupIndex].Flags := PlayersBrain[PlayerPopupIndex].Flags or fUsed;
      if PlayersBrain[PlayerPopupIndex].Kind in [btNoTerm, btSuperVirtual] then
        Difficulty[PlayerPopupIndex] := 0 { supervisor }
      else
        Difficulty[PlayerPopupIndex] := 2;
      if (Page = pgStartRandom) and (PlayerSlots[PlayerPopupIndex].OfferMultiple) and
        (not Assigned(PlayersBrain[PlayerPopupIndex])) then
        MultiControl := MultiControl and not (1 shl PlayerPopupIndex);
      if (PlayerPopupIndex = 0) and (MapFileName <> '') then
        ChangePage(Page);
      if PlayersBrain[PlayerPopupIndex].Kind = btNoTerm then
      begin // turn all local players off
        for I := 1 to PlayerSlots.Count - 1 do
          if Assigned(PlayersBrain[I]) and (PlayersBrain[I].Kind = btTerm) then begin
            PlayersBrain[I] := nil;
            PlayerSlots[I].DiffUpBtn.Visible := false;
            PlayerSlots[I].DiffUpBtn.Tag := 0;
            PlayerSlots[I].DiffDownBtn.Visible := false;
            PlayerSlots[I].DiffDownBtn.Tag := 0;
            if PlayerSlots[I].OfferMultiple then begin
              PlayerSlots[I].MultiBtn.Visible := false;
              PlayerSlots[I].MultiBtn.Tag := 0;
            end;
            SmartInvalidate(xBrain[I] - 31, yBrain[I] - 1, xBrain[I] + 64,
              PlayerSlots[I].DiffUpBtn.top + 25);
          end;
        BrainTerm.Flags := BrainTerm.Flags and not fUsed;
      end;
    end;
    SmartInvalidate(xBrain[PlayerPopupIndex] - 31, yBrain[PlayerPopupIndex] - 1,
      xBrain[PlayerPopupIndex] + 64, PlayerSlots[PlayerPopupIndex].DiffUpBtn.top + 25);
  end;
end;

procedure TStartDlg.OfferBrain(Brain: TBrain; FixedLines: Integer);
var
  J: Integer;
  MenuItem: TMenuItem;
begin
  MenuItem := TMenuItem.Create(PopupMenu1);
  if not Assigned(Brain) then MenuItem.Caption := Phrases.Lookup('NOMOD')
    else MenuItem.Caption := Brain.Name;
  MenuItem.Tag := Brains.IndexOf(Brain);
  MenuItem.OnClick := BrainClick;
  J := FixedLines;
  while (J < PopupMenu1.Items.Count) and
    (StrIComp(pchar(MenuItem.Caption), pchar(PopupMenu1.Items[J].Caption)) > 0) do
    Inc(J);
  MenuItem.RadioItem := True;
  if (PlayerPopupIndex < 0) then MenuItem.Checked := BrainDefault = Brain
    else MenuItem.Checked := PlayersBrain[PlayerPopupIndex] = Brain;
  PopupMenu1.Items.Insert(J, MenuItem);
end;

procedure TStartDlg.InitPopup(PlayerIndex: Integer);
var
  I: Integer;
  FixedLines: integer;
  MenuItem: TMenuItem;
  AIBrains: TBrains;
begin
  FixedLines := 0;
  PlayerPopupIndex := PlayerIndex;
  EmptyMenu(PopupMenu1.Items);
  if PlayerPopupIndex < 0 then begin // select default AI
    if NetworkEnabled then begin
      OfferBrain(BrainNetworkClient, FixedLines);
      Inc(FixedLines);
    end;

    MenuItem := TMenuItem.Create(PopupMenu1);
    MenuItem.Caption := '-';
    PopupMenu1.Items.Add(MenuItem);

    Inc(FixedLines);
    if Brains.GetKindCount(btAI) >= 2 then begin
      OfferBrain(BrainRandom, FixedLines);
      Inc(FixedLines);
    end;
    AIBrains := TBrains.Create(False);
    Brains.GetByKind(btAI, AIBrains);
    for I := 0 to AIBrains.Count - 1 do // offer available AIs
      if AIBrains[I].Flags and fMultiple <> 0 then
        OfferBrain(AIBrains[I], FixedLines);
    FreeAndNil(AIBrains);
  end else begin
    if PlayerPopupIndex > 0 then begin
      OfferBrain(nil, FixedLines);
      Inc(FixedLines);
    end;
    for I := Brains.IndexOf(BrainTerm) downto 0 do // offer game interfaces
      if (PlayerPopupIndex = 0) or (Brains[i].Kind = btTerm) and
        (PlayersBrain[0].Kind <> btNoTerm) then begin
        OfferBrain(Brains[I], FixedLines);
        Inc(FixedLines);
      end;
    if PlayerPopupIndex > 0 then begin
      if NetworkEnabled then begin
        OfferBrain(BrainNetworkServer, FixedLines);
        Inc(FixedLines);
      end;

      MenuItem := TMenuItem.Create(PopupMenu1);
      MenuItem.Caption := '-';
      PopupMenu1.Items.Add(MenuItem);
      Inc(FixedLines);
      if Brains.GetKindCount(btAI) >= 2 then begin
        OfferBrain(BrainRandom, FixedLines);
        Inc(FixedLines);
      end;
      AIBrains := TBrains.Create(False);
      Brains.GetByKind(btAI, AIBrains);
      for I := 0 to AIBrains.Count - 1 do // offer available AIs
        if (AIBrains[I].Flags and fMultiple <> 0) or (AIBrains[I].Flags and fUsed = 0)
          or (Brains[I] = PlayersBrain[PlayerPopupIndex]) then
          OfferBrain(AIBrains[i], FixedLines);
      FreeAndNil(AIBrains);
    end;
  end;
end;

procedure TStartDlg.UpdateFormerGames;
var
  I: Integer;
  F: TSearchRec;
begin
  FormerGames.Clear;
  if FindFirst(GetSavedDir + DirectorySeparator + '*' + CevoExt, $21, F) = 0 then
    repeat
      I := FormerGames.Count;
      while (I > 0) and (F.Time < integer(FormerGames.Objects[I - 1])) do
        Dec(I);
      FormerGames.InsertObject(I, Copy(F.Name, 1, Length(F.Name) - 5),
        TObject(F.Time));
    until FindNext(F) <> 0;
  FindClose(F);
  I := FormerGames.IndexOf(LastGame);
  if I >= 0 then ListIndex[tbPrevious] := I
    else ListIndex[tbPrevious] := FormerGames.Count - 1;
  TurnValid := False;
end;

procedure TStartDlg.UpdateMaps;
var
  f: TSearchRec;
begin
  Maps.Clear;
  if FindFirst(GetMapsDir + DirectorySeparator + '*' + CevoMapExt, $21, f) = 0 then
    repeat
      Maps.Add(Copy(f.Name, 1, Length(f.Name) - Length(CevoMapExt)));
    until FindNext(f) <> 0;
  FindClose(F);
  Maps.Sort;
  Maps.Insert(0, Phrases.Lookup('RANMAP'));
  ListIndex[tbMain] := Maps.IndexOf(Copy(MapFileName, 1, Length(MapFileName) - Length(CevoMapExt)));
  if ListIndex[tbMain] < 0 then
    ListIndex[tbMain] := 0;
end;

procedure TStartDlg.ChangePage(NewPage: TStartPage);
var
  i, j, p1: integer;
  s: string;
  Reg: TRegistry;
  InvalidateTab0: boolean;
begin
  InvalidateTab0 := (Page = pgMain) or (NewPage = pgMain);
  Page := NewPage;
  case Page of
    pgStartRandom, pgStartMap:
      begin
        StartBtn.Caption := Phrases.Lookup('STARTCONTROLS', 1);
        if Page = pgStartRandom then
          i := nPlOffered
        else
        begin
          i := nMapStartPositions;
          if i = 0 then
          begin
            PlayersBrain[0] := BrainSuperVirtual;
            Difficulty[0] := 0;
          end;
          if PlayersBrain[0].Kind in [btNoTerm, btSuperVirtual] then
            inc(i);
          if i > nPl then
            i := nPl;
          if i <= nPlOffered then
            MultiControl := 0
          else
            MultiControl := InitMulti[i];
        end;
        if InitAlive[i] <> SlotAvailable then
          if Page = pgStartRandom then
          begin // restore AI assignment of last start
            Reg := TRegistry.Create;
            with Reg do
            try
              OpenKey(AppRegistryKey + '\AI', True);
              for p1 := 0 to nPlOffered - 1 do begin
                PlayersBrain[p1] := nil;
                s := ReadString('Control' + IntToStr(p1));
                Difficulty[p1] := ReadInteger('Diff' + IntToStr(p1));
                if s <> '' then
                  for j := 0 to Brains.Count - 1 do
                    if AnsiCompareFileName(s, Brains[j].FileName) = 0 then
                      PlayersBrain[p1] := Brains[j];
              end;
            finally
              Free;
            end;
          end
          else
            for p1 := 1 to nPl - 1 do
              if 1 shl p1 and InitAlive[i] <> 0 then
              begin
                PlayersBrain[p1] := BrainDefault;
                Difficulty[p1] := 2;
              end
              else
                PlayersBrain[p1] := nil;
        SlotAvailable := InitAlive[i];
        for i := 0 to nPlOffered - 1 do
          if (AutoDiff < 0) and Assigned(PlayersBrain[i]) and
            (PlayersBrain[i].Kind in [btTerm, btRandom, btAI]) then
          begin
            PlayerSlots[i].DiffUpBtn.Tag := 768;
            PlayerSlots[i].DiffDownBtn.Tag := 768;
          end
          else
          begin
            PlayerSlots[i].DiffUpBtn.Tag := 0;
            PlayerSlots[i].DiffDownBtn.Tag := 0;
          end;
        for i := 6 to 8 do
          if (AutoDiff < 0) and Assigned(PlayersBrain[i]) and
            (PlayersBrain[i].Kind in [btTerm, btRandom, btAI]) then
          begin
            PlayerSlots[i].MultiBtn.Tag := 768;
            PlayerSlots[i].MultiBtn.ButtonIndex := 2 + (MultiControl shr i) and 1;
            PlayerSlots[i].MultiBtn.Enabled := Page = pgStartRandom
          end
          else
            PlayerSlots[i].MultiBtn.Tag := 0;
        if (AutoDiff > 0) and (Page <> pgStartMap) then
        begin
          AutoEnemyUpBtn.Tag := 768;
          AutoEnemyDownBtn.Tag := 768;
        end
        else
        begin
          AutoEnemyUpBtn.Tag := 0;
          AutoEnemyDownBtn.Tag := 0;
        end;
        if AutoDiff > 0 then
        begin
          AutoDiffUpBtn.Tag := 768;
          AutoDiffDownBtn.Tag := 768;
        end
        else
        begin
          AutoDiffUpBtn.Tag := 0;
          AutoDiffDownBtn.Tag := 0;
        end;
      end;

    pgNoLoad, pgLoad:
      begin
        StartBtn.Caption := Phrases.Lookup('STARTCONTROLS', 2);
        RenameBtn.Hint := Phrases.Lookup('BTN_RENGAME');
        DeleteBtn.Hint := Phrases.Lookup('BTN_DELGAME');
      end;

    pgEditRandom, pgEditMap:
      begin
        StartBtn.Caption := Phrases.Lookup('STARTCONTROLS', 12);
        RenameBtn.Hint := Phrases.Lookup('BTN_RENMAP');
        DeleteBtn.Hint := Phrases.Lookup('BTN_DELMAP');
      end;
  end;

  PaintInfo;
  for i := 0 to ControlCount - 1 do
    Controls[i].Visible := Controls[i].Tag and (256 shl Integer(Page)) <> 0;
  if Page = pgLoad then
    ReplayBtn.Visible := MiniMap.Mode <> mmMultiPlayer;
  List.Invalidate;
  SmartInvalidate(0, 0, ClientWidth, ClientHeight, invalidateTab0);
end;

procedure TStartDlg.ChangeTab(NewTab: TStartTab);
begin
  Tab := NewTab;
  case Tab of
    tbMap:
      List.Items.Assign(Maps);
    tbPrevious:
      List.Items.Assign(FormerGames);
  end;
  if Tab <> tbNew then
    if List.Count > 0 then begin
      if (ListIndex[Tab] < List.Count) and (ListIndex[Tab] >= 0) then begin
        List.ItemIndex := ListIndex[Tab];
      end else List.ItemIndex := 0;
    end else List.ItemIndex := -1;
  case Tab of
    tbMain:
      ChangePage(pgMain);
    tbMap:
      if List.ItemIndex = 0 then
        ChangePage(pgEditRandom)
      else
        ChangePage(pgEditMap);
    tbNew:
      if MapFileName = '' then
        ChangePage(pgStartRandom)
      else
        ChangePage(pgStartMap);
    tbPrevious:
      if FormerGames.Count = 0 then
        ChangePage(pgNoLoad)
      else
        ChangePage(pgLoad);
  end;
end;

procedure TStartDlg.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; x, y: integer);
var
  I: Integer;
begin
  if (y < TabHeight + 1) and (x - TabOffset < TabSize * 4) and
    ((x - TabOffset) div TabSize <> Integer(Tab)) then
  begin
    // Play('BUTTON_DOWN');
    ListIndex[Tab] := List.ItemIndex;
    ChangeTab(TStartTab((x - TabOffset) div TabSize));
  end
  else if Page = pgMain then begin
    case SelectedAction of
      maConfig: ShowSettings;
      maManual: DirectHelp(cStartHelp);
      maCredits: DirectHelp(cStartCredits);
      maAIDev: OpenDocument(HomeDir + AITemplateFileName);
      maWeb: OpenURL(CevoHomepage);
    end;
  end
  else if (AutoDiff < 0) and ((Page = pgStartRandom) or (Page = pgStartMap) and
    (nMapStartPositions > 0)) then
  begin
    for I := 0 to nPlOffered - 1 do
      if (1 shl I and SlotAvailable <> 0) and (x >= xBrain[I]) and
        (y >= yBrain[I]) and (x < xBrain[I] + 64) and (y < yBrain[I] + 64) then
      begin
        InitPopup(I);
        if yBrain[I] > y0Brain then
          PopupMenu1.Popup(left + xBrain[I] + 4, top + yBrain[I] + 60)
        else
          PopupMenu1.Popup(left + xBrain[I] + 4, top + yBrain[I] + 4);
      end;
  end
  else if (AutoDiff > 1) and ((Page = pgStartRandom) or (Page = pgStartMap)) and
    (x >= xDefault) and (y >= yDefault) and (x < xDefault + 64) and
    (y < yDefault + 64) then
    if Brains.GetKindCount(btAI) < 2 then
      SimpleMessage(Phrases.Lookup('NOALTAI'))
    else
    begin
      InitPopup(-1);
      PopupMenu1.Popup(left + xDefault + 4, top + yDefault + 4);
    end
  else if (Page = pgLoad) and (LastTurn > 0) and (y >= yTurnSlider) and
    (y < yTurnSlider + 7) and (x >= xTurnSlider) and
    (x <= xTurnSlider + wTurnSlider) then
  begin
    LoadTurn := LastTurn * (x - xTurnSlider) div wTurnSlider;
    SmartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider + 2,
      yTurnSlider + 9);
    Tracking := True;
  end;
end;

procedure TStartDlg.Up2BtnClick(Sender: TObject);
begin
  case Page of
    pgStartRandom, pgStartMap:
      if MaxTurn < 1900 then
      begin
        inc(MaxTurn, 200);
        SmartInvalidate(344, y0Mini + 61+12, 514, y0Mini + 82+12);
      end;
    pgLoad:
      if LoadTurn < LastTurn then
      begin
        inc(LoadTurn);
        SmartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider
          + 2, yTurnSlider + 9);
      end;
    pgEditRandom:
      begin
        inc(StartLandMass, LandmassDelta);
        if StartLandMass > 100 then
		  StartLandMass := 100;

        PaintInfo;
        SmartInvalidate(344, y0Mini + 61+12, 514, y0Mini + 61+12 + 21);
      end;
  end;
end;

procedure TStartDlg.Down2BtnClick(Sender: TObject);
begin
  case Page of
    pgStartRandom, pgStartMap:
      if MaxTurn > 400 then
      begin
        dec(MaxTurn, 200);
        SmartInvalidate(344, y0Mini + 61+12, 514, y0Mini + 82+12);
      end;
    pgLoad:
      if LoadTurn > 0 then
      begin
        dec(LoadTurn);
        SmartInvalidate(xTurnSlider - 2, y0Mini + 61+12, xTurnSlider + wTurnSlider
          + 2, yTurnSlider + 9+12);
      end;
    pgEditRandom:
      begin
        dec(StartLandMass, LandMassDelta);
        if StartLandMass < LandMassDelta then
          StartLandMass := LandMassDelta;

        PaintInfo;
        SmartInvalidate(344, y0Mini + 61+12, 514, y0Mini + 61+12 + 21);
      end;
  end;
end;

procedure TStartDlg.Up1BtnClick(Sender: TObject);
begin
  if WorldSize < MaxWorldSize - 1 then
  begin
    Inc(WorldSize);
    PaintInfo;
    SmartInvalidate(344, y0Mini - 77-12, 510, y0Mini - 77-12 + 21);
  end;
end;

procedure TStartDlg.Down1BtnClick(Sender: TObject);
begin
  if WorldSize > 0 then
  begin
    Dec(WorldSize);
    PaintInfo;
    SmartInvalidate(344, y0Mini - 77-12, 510, y0Mini - 77-12 + 21);
  end;
end;

procedure TStartDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  DirectDlg.Close;
end;

procedure TStartDlg.ListClick(Sender: TObject);
var
  I: Integer;
begin
  if (Tab = tbMap) and ((List.ItemIndex = 0) <> (Page = pgEditRandom)) then
  begin
    if List.ItemIndex = 0 then
      Page := pgEditRandom
    else
      Page := pgEditMap;
    for I := 0 to ControlCount - 1 do
      Controls[I].Visible := Controls[I].Tag and (256 shl Integer(Page)) <> 0;
    SmartInvalidate(328, Up1Btn.top - 12, ClientWidth, Up2Btn.top + 35);
  end;
  if Page = pgLoad then
    TurnValid := False;
  PaintInfo;
  if Page = pgLoad then
    ReplayBtn.Visible := MiniMap.Mode <> mmMultiPlayer;
end;

procedure TStartDlg.RenameBtnClick(Sender: TObject);
var
  i: integer;
  NewName: string;
  f: file;
  ok: boolean;
  MapPictureFileName: string;
begin
  if List.ItemIndex >= 0 then
  begin
    if Page = pgLoad then
      InputDlg.Caption := Phrases.Lookup('TITLE_BOOKNAME')
    else
      InputDlg.Caption := Phrases.Lookup('TITLE_MAPNAME');
    InputDlg.EInput.Text := List.Items[List.ItemIndex];
    InputDlg.CenterToRect(BoundsRect);
    InputDlg.ShowModal;
    NewName := InputDlg.EInput.Text;
    while (NewName <> '') and (NewName[1] = '~') do
      Delete(NewName, 1, 1);
    if (InputDlg.ModalResult = mrOK) and (NewName <> '') and
      (NewName <> List.Items[List.ItemIndex]) then
    begin
      for i := 1 to Length(NewName) do
        if NewName[i] in ['\', '/', ':', '*', '?', '"', '<', '>', '|'] then
        begin
          SimpleMessage(Format(Phrases.Lookup('NOFILENAME'), [NewName[i]]));
          Exit;
        end;
      if Page = pgLoad then
        AssignFile(f, GetSavedDir + DirectorySeparator + List.Items[List.ItemIndex] + CevoExt)
      else
        AssignFile(f, GetMapsDir + DirectorySeparator + List.Items[List.ItemIndex] +
          CevoMapExt);
      ok := true;
      try
        if Page = pgLoad then
          Rename(f, GetSavedDir + DirectorySeparator + NewName + CevoExt)
        else
          Rename(f, GetMapsDir + DirectorySeparator + NewName + CevoMapExt);
      except
        // Play('INVALID');
        ok := False;
      end;
      if Page <> pgLoad then begin
        // Rename map picture
        MapPictureFileName := GetMapsDir + DirectorySeparator +
          List.Items[List.ItemIndex] + CevoMapPictureExt;
        if FileExists(MapPictureFileName) then
        try
          AssignFile(f, GetMapsDir + DirectorySeparator + List.Items[List.ItemIndex]
            + CevoMapPictureExt);
          Rename(f, GetMapsDir + DirectorySeparator + NewName + CevoMapPictureExt);
        except
        end;
      end;
      if ok then begin
        if Page = pgLoad then
          FormerGames[List.ItemIndex] := NewName
        else
          Maps[List.ItemIndex] := NewName;
        List.Items[List.ItemIndex] := NewName;
        if Page = pgEditMap then
          PaintInfo;
        List.Invalidate;
      end;
    end;
  end;
end;

procedure TStartDlg.DeleteBtnClick(Sender: TObject);
var
  iDel: integer;
  f: file;
begin
  if List.ItemIndex >= 0 then
  begin
    if Page = pgLoad then
      MessgDlg.MessgText := Phrases.Lookup('DELETEQUERY')
    else
      MessgDlg.MessgText := Phrases.Lookup('MAPDELETEQUERY');
    MessgDlg.Kind := mkOKCancel;
    MessgDlg.ShowModal;
    if MessgDlg.ModalResult = mrOK then
    begin
      if Page = pgLoad then
        AssignFile(f, GetSavedDir + DirectorySeparator + List.Items[List.ItemIndex] + CevoExt)
      else
        AssignFile(f, GetMapsDir + DirectorySeparator + List.Items[List.ItemIndex] +
          CevoMapExt);
      Erase(f);
      iDel := List.ItemIndex;
      if Page = pgLoad then
        FormerGames.Delete(iDel)
      else
        Maps.Delete(iDel);
      List.Items.Delete(iDel);
      if List.Items.Count = 0 then
        ChangePage(pgNoLoad)
      else
      begin
        if iDel = 0 then
          List.ItemIndex := 0
        else
          List.ItemIndex := iDel - 1;
        if (Page = pgEditMap) and (List.ItemIndex = 0) then
          ChangePage(pgEditRandom)
        else
        begin
          List.Invalidate;
          if Page = pgLoad then
            TurnValid := false;
          PaintInfo;
          if Page = pgLoad then
            ReplayBtn.Visible := MiniMap.Mode <> mmMultiPlayer;
        end;
      end;
    end;
  end;
end;

procedure TStartDlg.DiffBtnClick(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to nPlOffered - 1 do
    if (Sender = PlayerSlots[I].DiffUpBtn) and (Difficulty[I] < 3) or
      (Sender = PlayerSlots[I].DiffDownBtn) and (Difficulty[I] > 1) then
    begin
      if Sender = PlayerSlots[I].DiffUpBtn then
        Inc(Difficulty[I])
      else
        Dec(Difficulty[I]);
      SmartInvalidate(xBrain[I] - 18, yBrain[I] + 19, xBrain[I] - 18 + 12,
        yBrain[I] + (19 + 14));
    end;
end;

procedure TStartDlg.MultiBtnClick(Sender: TObject);
var
  I: Integer;
begin
  for I := 6 to 8 do
    if Sender = PlayerSlots[I].MultiBtn then
    begin
      MultiControl := MultiControl xor (1 shl I);
      TButtonC(Sender).ButtonIndex := 2 + (MultiControl shr I) and 1;
    end;
end;

procedure TStartDlg.FormHide(Sender: TObject);
begin
  Diff0 := Difficulty[0];
  ListIndex[Tab] := List.ItemIndex;
  ShowTab := Tab;
  Background.Enabled := True;

  if ListIndex[tbPrevious] < 0 then
    LastGame := ''
  else
    LastGame := FormerGames[ListIndex[tbPrevious]];
end;

procedure TStartDlg.QuitBtnClick(Sender: TObject);
begin
  Close;
end;

procedure TStartDlg.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  ShortCut: TShortCut;
begin
  ShortCut := KeyToShortCut(Key, Shift);
  if BFullScreen.Test(ShortCut) then begin
    FullScreen := not FullScreen;
    UpdateInterface;
    Background.UpdateInterface;
    SetFocus;
  end else
  if BHelp.Test(ShortCut) then
    DirectHelp(cStartHelp);
end;

procedure TStartDlg.CustomizeBtnClick(Sender: TObject);
begin
  AutoDiff := -AutoDiff;
  CustomizeBtn.ButtonIndex := CustomizeBtn.ButtonIndex xor 1;
  ChangePage(Page);
end;

procedure TStartDlg.AutoDiffUpBtnClick(Sender: TObject);
begin
  if AutoDiff < 5 then
  begin
    Inc(AutoDiff);
    SmartInvalidate(120, y0Mini + 61, 272, y0Mini + 61 + 21);
    SmartInvalidate(xDefault - 2, yDefault - 2, xDefault + 64 + 2,
      yDefault + 64 + 2);
  end;
end;

procedure TStartDlg.AutoDiffDownBtnClick(Sender: TObject);
begin
  if AutoDiff > 1 then
  begin
    Dec(AutoDiff);
    SmartInvalidate(120, y0Mini + 61, 272, y0Mini + 61 + 21);
    SmartInvalidate(xDefault - 2, yDefault - 2, xDefault + 64 + 2,
      yDefault + 64 + 2);
  end;
end;

procedure TStartDlg.FormMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; x, y: integer);
begin
  Tracking := False;
end;

procedure TStartDlg.FormMouseMove(Sender: TObject; Shift: TShiftState;
  x, y: integer);
var
  OldLoadTurn: Integer;
  NewSelectedAction: TMainAction;
begin
  if Tracking then
  begin
    x := x - xTurnSlider;
    if x < 0 then
      x := 0
    else if x > wTurnSlider then
      x := wTurnSlider;
    OldLoadTurn := LoadTurn;
    LoadTurn := LastTurn * x div wTurnSlider;
    if LoadTurn < OldLoadTurn then
    begin
      SmartInvalidate(xTurnSlider + LoadTurn * wTurnSlider div LastTurn,
        yTurnSlider, xTurnSlider + OldLoadTurn * wTurnSlider div LastTurn + 1,
        yTurnSlider + 7);
      SmartInvalidate(344, y0Mini + 61, 514, y0Mini + 82);
    end
    else if LoadTurn > OldLoadTurn then
    begin
      SmartInvalidate(xTurnSlider + OldLoadTurn * wTurnSlider div LastTurn,
        yTurnSlider, xTurnSlider + LoadTurn * wTurnSlider div LastTurn + 1,
        yTurnSlider + 7);
      SmartInvalidate(344, y0Mini + 61, 514, y0Mini + 82);
    end;
  end
  else if Page = pgMain then
  begin
    if (x >= ActionSideBorder) and (x < ClientWidth - ActionSideBorder) and
      (y >= yAction - 8) and (y < ClientHeight - ActionBottomBorder) then
    begin
      NewSelectedAction := TMainAction((y - (yAction - 8)) div ActionPitch);
      if not (NewSelectedAction in ActionsOffered) then
        NewSelectedAction := maNone;
    end
    else
      NewSelectedAction := maNone;
    if NewSelectedAction <> SelectedAction then
    begin
      if SelectedAction <> maNone then
        SmartInvalidate(ActionSideBorder, yAction + Integer(SelectedAction) * ActionPitch
          - 8, ClientWidth - ActionSideBorder, yAction + (Integer(SelectedAction) + 1) *
          ActionPitch - 8);
      SelectedAction := NewSelectedAction;
      if SelectedAction <> maNone then
        SmartInvalidate(ActionSideBorder, yAction + Integer(SelectedAction) * ActionPitch
          - 8, ClientWidth - ActionSideBorder, yAction + (Integer(SelectedAction) + 1) *
          ActionPitch - 8);
    end;
  end;
end;

procedure TStartDlg.AutoEnemyUpBtnClick(Sender: TObject);
begin
  if AutoEnemies < nPl - 1 then
  begin
    Inc(AutoEnemies);
    SmartInvalidate(160, yMain + 140, 198, yMain + 140 + 21);
  end;
end;

procedure TStartDlg.AutoEnemyDownBtnClick(Sender: TObject);
begin
  if AutoEnemies > 0 then
  begin
    Dec(AutoEnemies);
    SmartInvalidate(160, yMain + 140, 198, yMain + 140 + 21);
  end;
end;

procedure TStartDlg.ReplayBtnClick(Sender: TObject);
begin
  LoadGame(GetSavedDir + DirectorySeparator, List.Items[List.ItemIndex] + CevoExt,
    LastTurn, True);
  SlotAvailable := -1;
end;

end.