summaryrefslogtreecommitdiff
path: root/orig/pq/Main.pas
blob: 1623e154e4d328773da421c726559a401edcaa09 (plain)
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
unit Main;
{ copyright (c)2002 Eric Fredricksen all rights reserved }

{$DEFINE CHEATS}
{$UNDEF LOGGING}

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, ImgList, Menus, ShellAPI;

const
  // revs:
  // 5: pq 6.3
  // 4: pq 6.2
  // 3: pq 6.1
  // 2: pq 6.0
  // 1: pq 6.0, some early release I guess; don't remember
  RevString = '&rev=5';
  wmIconTray = WM_USER + Ord('t');
  kFileExt = '.pq3';

type
  TMainForm = class(TForm)
    Panel1: TPanel;
    Label1: TLabel;
    Traits: TListView;
    Equips: TListView;
    Panel3: TPanel;
    Label3: TLabel;
    QuestBar: TProgressBar;
    Stats: TListView;
    Label2: TLabel;
    PlotBar: TProgressBar;
    Plots: TListView;
    Quests: TListView;
    Panel2: TPanel;
    Label4: TLabel;
    Spells: TListView;
    InventoryLabelAlsoGameStyle: TLabel;
    Inventory: TListView;
    Panel4: TPanel;
    Kill: TStatusBar;
    Label6: TLabel;
    ExpBar: TProgressBar;
    TaskBar: TProgressBar;
    Timer1: TTimer;
    EncumBar: TProgressBar;
    Label7: TLabel;
    ImageList1: TImageList;
    Label8: TLabel;
    Cheats: TPanel;
    CashIn: TButton;
    Button1: TButton;
    FinishQuest: TButton;
    Button3: TButton;
    CheatPlot: TButton;
    vars: TPanel;
    fTask: TLabel;
    fQuest: TLabel;
    fQueue: TListBox;
    procedure GoButtonClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure CashInClick(Sender: TObject);
    procedure FinishQuestClick(Sender: TObject);
    procedure CheatPlotClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
  private
    procedure Task(caption: String; msec: Integer);
    procedure Dequeue;
    procedure Q(s: string);
    function TaskDone: Boolean;
    procedure CompleteQuest;
    procedure CompleteAct;
    procedure WinEquip;
    procedure WinSpell;
    procedure WinStat;
    procedure WinItem;
    function SpecialItem: String;
    procedure LevelUp;
    function BoringItem: String;
    function InterestingItem: String;
    function MonsterTask(var level: Integer): String;
    function EquipPrice: Integer;
    procedure Brag(trigger: String);
    procedure TriggerAutosizes;
    function GameSaveName: String;
    procedure OnTrayMessage(var Msg: TMessage); message wmIconTray;
    procedure OnSysCommand(var Msg : TWMSysCommand); message WM_SYSCOMMAND;
    procedure Guildify;
    procedure ClearAllSelections;
    procedure OnQueryEndSession(var Msg : TMessage); message WM_QUERYENDSESSION;
    procedure OnEndSession(var Msg : TMessage); message WM_ENDSESSION;
    procedure RestoreIt;
    function AuthenticateUrl(url: String): String;
    {$IFDEF LOGGING}
    procedure Log(line: String);
    {$ENDIF}
    procedure ExportCharSheet;
    function CharSheet: String;
    procedure InterplotCinematic;
    function NamedMonster(level: Integer): String;
    function ImpressiveGuy: String;
  public
    FTrayIcon: TNotifyIconData;
    FReportSave: Boolean;
    FLogEvents: Boolean;
    FMakeBackups: Boolean;
    FMinToTray: Boolean;
    FExportSheets: Boolean;
    FSaveFileName: String;
    procedure MinimizeIt;
    procedure LoadGame(name: String);
    function SaveGame: Boolean;
    procedure Put(list: TListView; key: String; value: String); overload;
    procedure Put(list: TListView; pos: Integer; value: String); overload;
    procedure Put(list: TListView; key: String; value: Integer); overload;
    procedure Add(list: TListView; key: String; value: Integer); overload;
    procedure AddR(list: TListView; key: String; value: Integer); overload;
    function Get(list: TListView; key: String): String; overload;
    function Get(list: TListView; index: Integer): String; overload;
    function GetI(list: TListView; key: String): Integer; overload;
    function GetI(list: TListView; index: Integer): Integer; overload;
    function Sum(list: TListView): Integer;
    function RollCharacter: Boolean;
    function GetMotto: String;
    function GetPasskey: Integer;
    procedure SetMotto(v: String);
    procedure SetPasskey(v: String);
    function GetHostAddr: String;
    function GetHostName: String;
    procedure SetHostAddr(v: String);
    procedure SetHostName(v: String);
    function GetLogin: String;
    function GetPassword: String;
    procedure SetLogin(v: String);
    procedure SetPassword(v: String);
    function GetGuild: String;
    procedure SetGuild(v: String);
  end;

var
  MainForm: TMainForm;

function Split(s: String; field: Integer): String; overload;
function Split(s: String; field: Integer; separator: String): String; overload;

procedure Navigate(url: String);

implementation

uses Web, StrUtils, NewGuy, Math, Config, Front, zlibex, SelServ, Login,
  mmsystem, Registry, ShlObj;

{$R *.dfm}

// Returns '' if not there, which is lame, but okay for my purposes
function RegRead(root: HKEY; path, name: String): String;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    Reg.RootKey := root;
    if Reg.OpenKey(path, false) then
      Result := Reg.ReadString(name);
    Reg.CloseKey;
  finally
    Reg.Free;
  end;
end;

procedure RegWrite(root: HKEY; path, name, value: String);
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    Reg.RootKey := root;
    Reg.OpenKey(path, true);
    Reg.WriteString(name, value);
    Reg.CloseKey;
  finally
    Reg.Free;
  end;
end;

procedure MakeFileAssociations;
const
  kPQFileType = 'ProgressQuest.GameSave';
var
  kOpenCommand: String;
begin
  kOpenCommand := '"' + Application.ExeName + '" "%1"';
  try
    RegWrite(HKEY_CLASSES_ROOT, kFileExt,'', kPQFileType);
    RegWrite(HKEY_CLASSES_ROOT, kPQFileType, '', 'Progresss Quest saved game');
    RegWrite(HKEY_CLASSES_ROOT, kPQFileType + '\DefaultIcon', '', Application.ExeName + ',0');
    RegWrite(HKEY_CLASSES_ROOT, kPQFileType + '\Shell\Open', '', '&Open');
    if RegRead(HKEY_CLASSES_ROOT, kPQFileType + '\Shell\Open\Command', '') <> kOpenCommand then begin
      RegWrite(HKEY_CLASSES_ROOT, kPQFileType + '\Shell\Open\Command', '', kOpenCommand);
      // Notify Windows Explorer to realize we added this. In case this is slow
      // I don't do this unless I'm sure this one has changed.
      SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
    end;
  except
    on Exception do begin
      // Don't care
    end;
  end;
end;

procedure TMainForm.MinimizeIt;
begin
  if not FMinToTray then Exit;
  with FTrayIcon do
  begin
    cbSize := SizeOf(FTrayIcon);
    Wnd := Handle;
    uID := 0;
    uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
    uCallbackMessage := wmIconTray;
    hIcon := Application.Icon.Handle;
    StrPLCopy(szTip, Caption, 63);
  end;
  Application.Minimize;
  ShowWindow(Application.Handle, SW_HIDE);
  Shell_NotifyIcon(NIM_ADD,@FTrayIcon);
end;

procedure TMainForm.OnSysCommand(var Msg: TWMSysCommand);
begin
  if (Msg.CmdType = SC_MINIMIZE) and FMinToTray then
    MinimizeIt();
  inherited;
end;

procedure TMainForm.RestoreIt;
begin
  ShowWindow(Application.Handle, SW_SHOW);
  Application.Restore;
  Shell_NotifyIcon(NIM_DELETE, @MainForm.FTrayIcon);
end;

procedure TMainForm.OnTrayMessage(var Msg: TMessage);
begin
  case Msg.lParam of
    WM_LBUTTONDOWN, WM_RBUTTONDOWN:
      RestoreIt;

    WM_LBUTTONDBLCLK, WM_RBUTTONDBLCLK:
      RestoreIt;
  end;
end;

procedure StartTimer;
begin
  if not MainForm.Timer1.Enabled then begin
    MainForm.Timer1.Tag := timeGetTime;
    //Shell_NotifyIcon(NIM_ADD, @MainForm.FTrayIcon);
  end;
  MainForm.Timer1.Enabled := True;
  // BS location for this, but...
  MainForm.Caption := 'ProgressQuest - ' + ChangeFileExt(ExtractFileName(MainForm.GameSaveName), '');
end;

function TMainForm.GetPasskey: Integer; begin Result := Traits.Tag; end;
procedure TMainForm.SetPasskey(v: String);
begin
  Traits.Hint := v;
  Traits.Tag := StrToIntDef(Traits.Hint,0);
end;

function TMainForm.GetMotto: String; begin Result := Stats.Hint; end;
procedure TMainForm.SetMotto(v: String); begin Stats.Hint := v; end;

function TMainForm.GetHostName: String; begin Result := Spells.Hint; end;
procedure TMainForm.SetHostName(v: String); begin Spells.Hint := v; end;

function TMainForm.GetHostAddr: String;
begin
  Result := Equips.Hint;
  if (Result = '') and (GetPasskey <> 0) then
    Result := 'http://www.progressquest.com/knoram.php?';
end;
procedure TMainForm.SetHostAddr(v: String); begin Equips.Hint := v; end;

function TMainForm.GetLogin: String; begin Result := Inventory.Hint; end;
procedure TMainForm.SetLogin(v: String); begin Inventory.Hint := v; end;

function TMainForm.GetPassword: String; begin Result := Plots.Hint; end;
procedure TMainForm.SetPassword(v: String); begin Plots.Hint := v; end;

function TMainForm.GetGuild: String; begin Result := Label1.Hint; end;
procedure TMainForm.SetGuild(v: String); begin Label1.Hint := v; end;

procedure TMainForm.Q(s: string);
begin
  fQueue.Items.Add(s);
  Dequeue;
end;

function TMainForm.TaskDone: Boolean;
begin
  with TaskBar do
    Result := Position >= Max;
end;

function Odds(chance, outof: Integer): Boolean;
begin
  Result := Random(outof) < chance;
end;

function RandSign(): Integer;
begin
  Result := Random(2) * 2 - 1;
end;

function Pick(s: TStrings): String;
begin
  Result := s[Random(s.Count)];
end;

function RandomLow(below: Integer): Integer;
begin
  Result := Min(Random(below),Random(below));
end;

function PickLow(s: TStrings): String;
begin
  Result := s[RandomLow(s.Count)];
end;

function Ends(s,e: String): Boolean;
begin
  Result := Copy(s,1+Length(s)-Length(e),Length(e)) = e;
end;

function Plural(s: String): String;
begin
       if Ends(s,'y')
       then Result := Copy(s,1,Length(s)-1) + 'ies'
  else if Ends(s,'us')
       then Result := Copy(s,1,Length(s)-2) + 'i'
  else if Ends(s,'ch') or Ends(s,'x') or Ends(s,'s')
       then Result := s + 'es'
  else if Ends(s,'f')
       then Result := Copy(s,1,Length(s)-1) + 'ves'
  else if Ends(s,'man') or Ends(s,'Man')
       then Result := Copy(s,1,Length(s)-2) + 'en'
       else Result := s + 's';
end;

function Split(s: String; field: Integer; separator: String): String;
var
  p: Integer;
begin
  while field > 0 do begin
    p := Pos(separator,s);
    s := Copy(s,p+1,10000);
    Dec(field);
  end;
  if Pos(separator,s) > 0
  then Result := Copy(s,1,Pos(separator,s)-1)
  else Result := s;
end;

function Split(s: String; field: Integer): String;
begin
  result := Split(s, field, '|');
end;

function Indefinite(s: String; qty: Integer): String;
begin
  if qty = 1 then begin
    if Pos(s[1], 'AEIOUÜaeiouü') > 0
    then Result := 'an ' + s
    else Result := 'a ' + s;
  end else begin
    Result := IntToStr(qty) + ' ' + Plural(s);
  end;
end;

function Definite(s: String; qty: Integer): String;
begin
  if qty > 1 then
    s := {IntToStr(qty) + ' ' +} Plural(s);
  Result := 'the ' + s;
end;

function Sick(m: Integer; s: String): String;
begin
  Result := IntToStr(m) + s; // in case I screw up
  case m of
  -5,5: Result := 'dead ' + s;
  -4,4: Result := 'comatose ' + s;
  -3,3: Result := 'crippled ' + s;
  -2,2: Result := 'sick ' + s;
  -1,1: Result := 'undernourished ' + s;
  end;
end;

function Young(m: Integer; s: String): String;
begin
  Result := IntToStr(m) + s; // in case I screw up
  case -m of
  -5,5: Result := 'foetal ' + s;
  -4,4: Result := 'baby ' + s;
  -3,3: Result := 'preadolescent ' + s;
  -2,2: Result := 'teenage ' + s;
  -1,1: Result := 'underage ' + s;
  end;
end;

function Big(m: Integer; s: String): String;
begin
  Result := s; // in case I screw up
  case m of
  1,-1: Result := 'greater ' + s;
  2,-2: Result := 'massive ' + s;
  3,-3: Result := 'enormous ' + s;
  4,-4: Result := 'giant ' + s;
  5,-5: Result := 'titanic ' + s;
  end;
end;

function Special(m: Integer; s: String): String;
begin
  Result := s; // in case I screw up
  case -m of
  1,-1:
      if Pos(' ',Result) > 0
      then Result := 'veteran ' + s
      else Result := 'Battle-' + s;
  2,-2: Result := 'cursed ' + s;
  3,-3:
      if Pos(' ',Result) > 0
      then Result := 'warrior ' + s
      else Result := 'Were-' + s;
  4,-4: Result := 'undead ' + s;
  5,-5: Result := 'demon ' + s;
  end;
end;

procedure TMainForm.InterplotCinematic;
var
  nemesis: String;
  i, s: Integer;
begin
  case Random(3) of
  0: begin
    Q('task|1|Exhausted, you arrive at a friendly oasis in a hostile land');
    Q('task|2|You greet old friends and meet new allies');
    Q('task|2|You are privy to a council of powerful do-gooders');
    Q('task|1|There is much to be done. You are chosen!');
     end;
  1: begin
    Q('task|1|Your quarry is in sight, but a mighty enemy bars your path!');
    nemesis := NamedMonster(GetI(Traits,'Level')+3);
    Q('task|4|A desperate struggle commences with ' + nemesis);
    s := Random(3);
    for i := 1 to Random(1 + Plots.Items.Count) do begin
      Inc(s, 1 + Random(2));
      case s mod 3 of
      0: Q('task|2|Locked in grim combat with ' + nemesis);
      1: Q('task|2|' + nemesis + ' seems to have the upper hand');
      2: Q('task|2|You seem to gain the advantage over ' + nemesis);
      end;
    end;
    Q('task|3|Victory! ' + nemesis + ' is slain! Exhausted, you lose conciousness');
    Q('task|2|You awake in a friendly place, but the road awaits');
      end;
  2: begin
    nemesis := ImpressiveGuy;
    Q('task|2|Oh sweet relief! You''ve reached the protection of the good ' + nemesis);
    Q('task|3|There is rejoicing, and an unnerving encouter with ' + nemesis + ' in private');
    Q('task|2|You forget your ' + BoringItem + ' and go back to get it');
    Q('task|2|What''s this!? You overhear something shocking!');
    Q('task|2|Could ' + nemesis + ' be a dirty double-dealer?');
    Q('task|3|Who can possibly be trusted with this news!? ... Oh yes, of course');
      end;
  end;
  Q('plot|1|Loading');
end;


function TMainForm.NamedMonster(level: Integer): String;
var
  lev, i: Integer;
  m: String;
begin
  lev := 0;  // shut up, compiler hint
  for i := 1 to 5 do begin
    m := Pick(K.Monsters.Lines);
    if (Result = '') or (abs(level-StrToInt(Split(m,1))) < abs(level-lev)) then begin
      Result := Split(m,0);
      lev := StrToInt(Split(m,1));
    end;
  end;
  Result := GenerateName + ' the ' + Result;
end;

function TMainForm.ImpressiveGuy: String;
begin
  Result := Pick(K.ImpressiveTitles.Lines);
  case Random(2) of
  0: Result := Result + ' of the ' + Pick(K.Races.Lines);
  1: Result := Result + ' of ' + GenerateName;
  end;
end;

function TMainForm.MonsterTask(var level: Integer): String;
var
  qty, lev, i: Integer;
  monster, m1: string;
  definite: Boolean;
begin
  definite := false;
  for i := level downto 1 do begin
    if Odds(2,5) then
      Inc(level, RandSign());
  end;
  if level < 1 then level := 1;
  // level = level of puissance of opponent(s) we'll return

  if Odds(1,25) then begin
    // use an NPC every once in a while
    monster := ' ' + Pick(NewGuyForm.Race.Items);
    if Odds(1,2)
    then monster := 'passing' + monster + ' ' + Pick(NewGuyForm.Klass.Items)
    else begin
      monster := PickLow(K.Titles.Lines) + ' ' + GenerateName + ' the' + monster;
      definite := true;
    end;
    lev := level;
    monster := monster + '|' + IntToStr(level) + '|*';
  end else if (fQuest.Caption <> '') and Odds(1,4) then begin
    // use the quest monster
    monster := k.Monsters.Lines[fQuest.Tag];
    lev := StrToInt(Split(monster,1));
  end else begin
    // pick the monster out of so many random ones closest to the level we want
    monster := Pick(K.Monsters.Lines);
    lev := StrToInt(Split(monster,1));
    i := 5;
    while (i > 0) do begin // or (lev - level > 4) do begin
      m1 := Pick(K.Monsters.Lines);
      if abs(level-StrToInt(Split(m1,1))) < abs(level-lev) then begin
        monster := m1;
        lev := StrToInt(Split(monster,1));
      end;
      if i > 0 then Dec(i);
    end;
  end;

  fTask.Caption := monster;
  Result := Split(monster,0);
  fTask.Caption := 'kill|' + fTask.Caption;

  qty := 1;
  if (level-lev) > 10 then begin
      // lev is too low. multiply...
      qty := (level + Random(lev)) div max(lev,1);
      if qty < 1 then qty := 1;
      level := level div qty;
  end;

  if (level - lev) <= -10 then begin
    Result := 'imaginary ' + Result;
  end else if (level-lev) < -5 then begin
    i := 10+(level-lev);
    i := 5-Random(i+1);
    Result := Sick(i,Young((lev-level)-i,Result));
  end else if ((level-lev) < 0) and (Random(2) = 1) then begin
    Result := Sick(level-lev,Result);
  end else if ((level-lev) < 0) then begin
    Result := Young(level-lev,Result);
  end else if (level-lev) >= 10 then begin
    Result := 'messianic ' + Result;
  end else if (level-lev) > 5 then begin
    i := 10-(level-lev);
    i := 5-Random(i+1);
    Result := Big(i,Special((level-lev)-i,Result));
  end else if ((level-lev) > 0) and (Random(2) = 1) then begin
    Result := Big(level-lev,Result);
  end else if ((level-lev) > 0) then begin
    Result := Special(level-lev,Result);
  end;

  lev := level;
  level := lev * qty;

  if not definite then Result := Indefinite(Result, qty);
end;

function ProperCase(s:String):String;
begin
  Result := UpperCase(Copy(s,1,1)) + Copy(s,2,10000);
end;

function TMainForm.EquipPrice: Integer;
begin
  Result :=  5 * GetI(Traits,'Level') * GetI(Traits,'Level')
          + 10 * GetI(Traits,'Level')
          + 20;
end;

procedure TMainForm.Dequeue;
var
  s, a, old: String;
  n, l: Integer;
begin
  while TaskDone do begin
    if Split(fTask.Caption,0) = 'kill' then begin
      if Split(fTask.Caption,3) = '*' then begin
        WinItem;
      end else if Split(fTask.Caption,3) <> '' then begin
        Add(Inventory,LowerCase(Split(fTask.Caption,1) + ' ' + ProperCase(Split(fTask.Caption,3))),1);
      end;
    end else if fTask.Caption = 'buying' then begin
      // buy some equipment
      Add(Inventory,'Gold',-EquipPrice);
      WinEquip;
    end else if (fTask.Caption = 'market') or (fTask.Caption = 'sell') then with Inventory do begin
      if fTask.Caption = 'sell' then begin
        Tag := GetI(Inventory,1);
        Tag := Tag * GetI(Traits,'Level');
        if Pos(' of ',Items[1].Caption) > 0 then
          Tag := Tag * (1+RandomLow(10)) * (1+RandomLow(GetI(Traits,'Level')));
        Items[0].MakeVisible(false);
        Items.Delete(1);
        Add(Inventory,'Gold',Tag);
      end;
      if Items.Count > 1 then begin
        Task('Selling ' + Indefinite(Inventory.Items[1].Caption, GetI(Inventory,1)), 1 * 1000);
        fTask.Caption := 'sell';
        break;
      end;
    end;
    old := fTask.Caption;
    fTask.Caption := '';
    if (fQueue.Items.Count > 0) then begin
      a := Split(fQueue.Items[0],0);
      n := StrToInt(Split(fQueue.Items[0],1));
      s := Split(fQueue.Items[0],2);
      if (a = 'task') or (a = 'plot') then begin
        if a = 'plot' then begin
          CompleteAct;
          s := 'Loading ' + Plots.Items[Plots.Items.Count-1].Caption;
        end;
        Task(s, n * 1000);
        fQueue.Items.Delete(0);
      end else begin
        raise Exception.Create('bah!');
      end;
    end else with Encumbar do if Position >= Max then begin
      Task('Heading to market to sell loot',4 * 1000);
      fTask.Caption := 'market';
    end else if (Pos('kill|',old) <= 0) and (old <> 'heading') then begin
      if GetI(Inventory, 'Gold') > EquipPrice then begin
        Task('Negotiating purchase of better equipment', 5 * 1000);
        fTask.Caption := 'buying';
      end else begin
        Task('Heading to the killing fields', 4 * 1000);
        fTask.Caption := 'heading';
      end;
    end else begin
      n := GetI(Traits,'Level');
      l := n;
      s := MonsterTask(n);
      n := (2 * InventoryLabelAlsoGameStyle.Tag * n * 1000) div l;
      Task('Executing ' + s, n);
    end;
  end;
end;

function IndexOf(list: TListView; key: String): Integer;
var
  i: Integer;
begin
  for i := 0 to list.Items.Count-1 do    if list.Items.Item[i].Caption = key then begin
      Result := i;
      Exit;
    end;
  with list.Items.Add do begin
    Result := Index;
    Caption := key;
    MakeVisible(false);
    list.Width := list.Width - 1; // trigger an autosize
  end;
end;

procedure TMainForm.Put(list: TListView; key, value: String);
begin
  Put(list, IndexOf(list,key), value);
end;

procedure TMainForm.Put(list: TListView; key: String; value: Integer);
begin
  Put(list,key,IntToStr(value));
  if key = 'STR' then
    Encumbar.Max := 10 + value;
  if list = Inventory then with Encumbar do begin
    Position := Sum(Inventory) - GetI(Inventory,'Gold');
    Hint := IntToStr(Position) + '/' + IntToStr(Max) + ' cubits';
  end;
end;

procedure TMainForm.Put(list: TListView; pos: Integer; value: String);
begin
  with list.Items.Item[pos] do begin
    if SubItems.Count < 1
    then SubItems.Add(value)
    else SubItems[0] := value;
  end;
  //list.MultiSelect := true;
  //list.RowSelect := true;
  //list.HideSelection := false;
  list.Items[pos].Selected := true;
end;

function LevelUpTime(level: Integer): Integer;  // seconds
begin
  // 20 minutes per level
  Result := 20 * level * 60;
end;

procedure TMainForm.GoButtonClick(Sender: TObject);
begin
  with ExpBar do begin
    Position := 0;
    Max := LevelUpTime(1);
  end;

  fTask.Caption := '';
  fQuest.Caption := '';
  fQueue.Items.Clear;

  Task('Loading.',2000); // that dot is spotted for later...
  Q('task|10|Experiencing an enigmatic and foreboding night vision');
  Q('task|6|Much is revealed about that wise old bastard you''d underestimated');
  Q('task|6|A shocking series of events leaves you alone and bewildered, but resolute');
  Q('task|4|Drawing upon an unexpected reserve of determination, you set out on a long and dangerous journey');
  Q('task|2|Loading');

  PlotBar.Max := 26;
  with Plots.Items.Add do begin
    Caption := 'Prologue';
    StateIndex := 0;
  end;

  StartTimer;
  SaveGame;
  Brag('s');
end;

procedure TMainForm.WinSpell;
begin
  AddR(Spells, K.Spells.Lines[RandomLow(Min(GetI(Stats,'WIS')+GetI(Traits,'Level'),
                                            K.Spells.Lines.Count))], 1);
end;

function LPick(list: TStrings; goal: Integer): String;
var
  i, best, b1: Integer;
  s: String;
begin
  Result := Pick(list);
  for i := 1 to 5 do begin
    best := StrToInt(Split(Result,1));
    s := Pick(list);
    b1 := StrToInt(Split(s,1));
    if abs(goal-best) > abs(goal-b1) then
      Result := s;
  end;
end;

procedure TMainForm.WinEquip;
var
  posn, qual, plus, count: Integer;
  name, modifier: String;
  stuff, better, worse: TStrings;
begin
  posn := Random(Equips.Items.Count);
  Equips.Tag := posn; // remember as the "best item"
  if posn = 0 then begin
    stuff := K.Weapons.Lines;
    better := K.OffenseAttrib.Lines;
    worse := K.OffenseBad.Lines;
  end else begin
    better := K.DefenseAttrib.Lines;
    worse := K.DefenseBad.Lines;
    if posn = 1
    then stuff := K.Shields.Lines
    else stuff := K.Armors.Lines;
  end;
  name := LPick(stuff,GetI(Traits,'Level'));
  qual := StrToInt(Split(name,1));
  name := Split(name,0);
  plus := GetI(Traits,'Level') - qual;
  if plus < 0 then better := worse;
  count := 0;
  while (count < 2) and (plus <> 0) do begin
    modifier := Pick(better);
    qual := StrToInt(Split(modifier, 1));
    modifier := Split(modifier, 0);
    if Pos(modifier, name) > 0 then Break; // no repeats
    if Abs(plus) < Abs(qual) then Break; // too much
    name := modifier + ' ' + name;
    Dec(plus, qual);
    Inc(count);
  end;
  if plus <> 0 then name := IntToStr(plus) + ' ' + name;
  if plus > 0 then name := '+' + name;

  Put(Equips, posn, name);
end;

procedure TMainForm.WinStat;
var
  i,t: Integer;
  function Square(x: Integer): Integer; begin Result := x * x; end;
begin
  if Odds(1,2)
  then i := Random(Stats.Items.Count)
  else begin
    // favor the best stat so it will tend to clump
    t := 0;
    for i := 0 to 5 do Inc(t,Square(GetI(Stats,i)));
    t := Random(t);
    i := -1;
    while t >= 0 do begin
      Inc(i);
      Dec(t,Square(GetI(Stats,i)));
    end;
  end;
  Add(Stats, Stats.Items[i].Caption, 1);
end;

function TMainForm.SpecialItem: String;
begin
  Result := InterestingItem + ' of ' +
            Pick(K.ItemOfs.Lines);
end;

function TMainForm.InterestingItem: String;
begin
  Result := Pick(K.ItemAttrib.Lines) + ' ' +
            Pick(K.Specials.Lines);
end;

function TMainForm.BoringItem: String;
begin
  Result := Pick(K.BoringItems.Lines);
end;

procedure TMainForm.WinItem;
begin
  Add(Inventory, SpecialItem, 1);
end;

procedure TMainForm.CompleteQuest;
var
  lev, level, l, i, montag: Integer;
  m: string;
begin
  lev := 0;  // Quell stupid compiler warning
  with QuestBar do begin
    Position := 0;
    Max := 50 + Random(100);
  end;
  with Quests do begin
    if Items.Count > 0 then begin
      {$IFDEF LOGGING}
      Log('Quest completed: ' + Items[Items.Count-1].Caption);
      {$ENDIF}
      Items[Items.Count-1].StateIndex := 1;
      case Random(4) of
        0: WinSpell;
        1: WinEquip;
        2: WinStat;
        3: WinItem;
      end;
    end;
    while Items.Count > 99 do Items.Delete(0);

    with Items.Add do begin
      case Random(5) of
        0: begin
          level := GetI(Traits,'Level');
          for i := 1 to 4 do begin
            montag := Random(K.Monsters.Lines.Count);
            m := K.Monsters.Lines[montag];
            l := StrToInt(Split(m,1));
            if (i = 1) or (abs(l - level) < abs(lev - level)) then begin
              lev := l;
              fQuest.Caption := m;
              fQuest.Tag := montag;
            end;
          end;
          Caption := 'Exterminate ' + Definite(Split(fQuest.Caption,0),2);
        end;
        1: begin
          fQuest.Caption := InterestingItem;
          Caption := 'Seek ' + Definite(fQuest.Caption,1);
          fQuest.Caption := '';
        end;
        2: begin
          fQuest.Caption := BoringItem;
          Caption := 'Deliver this ' + fQuest.Caption;
          fQuest.Caption := '';
        end;
        3: begin
          fQuest.Caption := BoringItem;
          Caption := 'Fetch me ' + Indefinite(fQuest.Caption,1);
          fQuest.Caption := '';
        end;
        4: begin
          level := GetI(Traits,'Level');
          for i := 1 to 2 do begin
            montag := Random(K.Monsters.Lines.Count);
            m := K.Monsters.Lines[montag];
            l := StrToInt(Split(m,1));
            if (i = 1) or (abs(l - level) < abs(lev - level)) then begin
              lev := l;
              fQuest.Caption := m;
            end;
          end;
          Caption := 'Placate ' + Definite(Split(fQuest.Caption,0),2);
          fQuest.Caption := '';
        end;
      end;
      {$IFDEF LOGGING}
      Log('Commencing quest: ' + Caption);
      {$ENDIF}
      StateIndex := 0;
      MakeVisible(false);
    end;
    Width := Width - 1; // trigger a column resize
  end;
  SaveGame;
end;

function Rome(var n: Integer; dn: Integer; var s: String; ds: String): Boolean;
begin
  Result := (n >= dn);
  if Result then begin
    n := n - dn;
    s := s + ds;
  end;
end;

function UnRome(var s: String; dn: Integer; var n: Integer; ds: String): Boolean;
begin
  Result := (Copy(s,1,Length(ds)) = ds);
  if Result then begin
    s := Copy(s,Length(ds)+1,10000);
    n := n + dn;
  end;
end;

function IntToRoman(n: Integer): String;
begin
  while Rome(n, 1000, Result, 'M') do ;
  Rome(n, 900, Result, 'CM');
  Rome(n, 500, Result, 'D');
  Rome(n, 400, Result, 'CD');
  while Rome(n, 100, Result, 'C') do ;
  Rome(n, 90, Result, 'XC');
  Rome(n, 50, Result, 'L');
  Rome(n, 40, Result, 'XL');
  while Rome(n, 10, Result, 'X') do ;
  Rome(n, 9, Result, 'IX');
  Rome(n, 5, Result, 'V');
  Rome(n, 4, Result, 'IV');
  while Rome(n, 1, Result, 'I') do ;
end;

function RomanToInt(n: String): Integer;
begin
  Result := 0;
  while UnRome(n, 1000, Result, 'M') do ;
  UnRome(n, 900, Result, 'CM');
  UnRome(n, 500, Result, 'D');
  UnRome(n, 400, Result, 'CD');
  while UnRome(n, 100, Result, 'C') do ;
  UnRome(n, 90, Result, 'XC');
  UnRome(n, 50, Result, 'L');
  UnRome(n, 40, Result, 'XL');
  while UnRome(n, 10, Result, 'X') do ;
  UnRome(n, 9, Result, 'IX');
  UnRome(n, 5, Result, 'V');
  UnRome(n, 4, Result, 'IV');
  while UnRome(n, 1, Result, 'I') do ;
end;

procedure TMainForm.CompleteAct;
begin
  PlotBar.Position := 0;
  with Plots do begin
    Items[Items.Count-1].StateIndex := 1;
    PlotBar.Max := 60 * 60 * (1 + 5 * Items.Count); // 1 hr + 5/act
    PlotBar.Hint := 'Cutscene omitted';
    with Items.Add do begin
      Caption := 'Act ' + IntToRoman(Items.Count-1);
      MakeVisible(false);
      StateIndex := 0;
      Width := Width-1;
    end;
  end;
  WinItem;
  WinEquip;
  SaveGame;
  Brag('a');
end;


{$IFDEF LOGGING}
procedure TMainForm.Log(line: String);
var
  stamp: String;
  logname: String;
  log: Text;
begin
  if FLogEvents then begin
    logname := ChangeFileExt(GameSaveName, '.log');
    DateTimeToString(stamp, '[yyyy-mm-dd hh:nn:ss]', Now);
    AssignFile(log, logname);
    if FileExists(logname) then Append(log) else Rewrite(log);
    WriteLn(log, stamp + ' ' + line);
    Flush(log);
    CloseFile(log);
  end;
end;
{$ENDIF}

procedure TMainForm.ExportCharSheet;
var
  f: TextFile;
begin
  AssignFile(f, ChangeFileExt(GameSaveName, '.sheet'));
  Rewrite(f);
  Write(f, CharSheet);
  Flush(f);
  CloseFile(f);
end;

function TMainForm.CharSheet: String;
var
  i: Integer;
  f: String;
  procedure Wr(a: String); begin f := f + a; end;
  procedure WrLn(a: String); overload; begin Wr(a + #13#10); end;
  procedure WrLn; overload; begin Wr(#13#10); end;
begin
  Wr(Get(Traits,'Name'));
  if GetHostName <> '' then
    Wr(' [' + GetHostName + ']');
  WrLn;
  WrLn(Get(Traits,'Race') + ' ' +  Get(Traits,'Class'));
  WrLn(Format('Level %d (exp. %d/%d)', [GetI(Traits,'Level'), ExpBar.Position, ExpBar.Max]));
  //WrLn('Level ' + Get(Traits,'Level') + ' (' + ExpBar.Hint + ')');
  WrLn;
  with Plots do if Items.Count > 0 then
    WrLn('Plot stage: ' + Items[Items.Count-1].Caption + ' (' + PlotBar.Hint + ')');
  with Quests do if Items.Count > 0 then
    WrLn('Quest: ' + Items[Items.Count-1].Caption + ' (' + QuestBar.Hint + ')');
  WrLn;
  WrLn( 'Stats:');
  WrLn( Format('  STR%7d', [GetI(Stats,'STR')]));
  WrLn( Format('  CON%7d', [GetI(Stats,'CON')]));
  WrLn( Format('  DEX%7d', [GetI(Stats,'DEX')]));
  WrLn( Format('  INT%7d', [GetI(Stats,'INT')]));
  WrLn( Format('  WIS%7d      HP Max%7d', [GetI(Stats,'WIS'), GetI(Stats,'HP Max')]));
  WrLn( Format('  CHA%7d      MP Max%7d', [GetI(Stats,'CHA'), GetI(Stats,'MP Max')]));
  WrLn;
  WrLn( 'Equipment:');
  for i := 1 to Equips.Items.Count-1 do
    if Get(Equips,i) <> '' then
      WrLn( '  ' + LeftStr(Equips.Items[i].Caption + '            ', 12) + Get(Equips,i));
  WrLn;
  WrLn( 'Spell Book:');
  with Spells do
    for i := 1 to Items.Count-1 do
      WrLn( '  ' + Items[i].Caption + ' ' + Get(Spells,i));
  WrLn;
  WrLn( 'Inventory (' + EncumBar.Hint + '):');
  WrLn( '  ' + Indefinite('gold piece', GetI(Inventory, 'Gold')));
  with Inventory do
    for i := 2 to Items.Count-1 do
      if Pos(' of ', Items[i].Caption) > 0
      then WrLn( '  ' + Definite(Items[i].Caption, GetI(Inventory,i)))
      else WrLn( '  ' + Indefinite(Items[i].Caption, GetI(Inventory,i)));
  WrLn;
  WrLn( '-- ' + DateTimeToStr(Now));
  WrLn( '-- Progress Quest 6.2 - http://progressquest.com/');
  Result := f;
end;

procedure TMainForm.Task(caption: String; msec: Integer);
begin
  Kill.SimpleText := caption + '...';
  {$IFDEF LOGGING}
  Log(Kill.SimpleText);
  {$ENDIF}
  with TaskBar do begin
    Position := 0;
    Max := msec;
  end;
end;

procedure TMainForm.Add(list: TListView; key: String; value: Integer);
var line: String;
begin
  Put(list, key, value + GetI(list,key));
  if value = 0 then Exit;

  if value > 0 then line := 'Gained' else line := 'Lost';
  if key = 'Gold' then begin
    key := 'gold piece';
    if value > 0 then line := 'Got paid' else line := 'Spent';
  end;
  if value < 0 then value := -value;
  line := line + ' ' + Indefinite(key, value);
  {$IFDEF LOGGING}
  Log(line);
  {$ENDIF}
end;

procedure TMainForm.AddR(list: TListView; key: String; value: Integer);
begin
  Put(list, key, IntToRoman(value + RomanToInt(Get(list,key))));
end;

function TMainForm.Get(list: TListView; key: String): String;
begin
  Result := Get(list, IndexOf(list,key));
end;

function TMainForm.Get(list: TListView; index: Integer): String;
begin
  with list.Items.Item[index] do begin
    if SubItems.Count < 1
    then Result := ''
    else Result := SubItems[0];
  end;
end;

function TMainForm.GetI(list: TListView; key: String): Integer;
begin
  Result := StrToIntDef(Get(list,key),0);
end;

function TMainForm.GetI(list: TListView; index: Integer): Integer;
begin
  Result := StrToIntDef(Get(list,index),0);
end;

function TMainForm.Sum(list: TListView): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := 0 to list.Items.Count - 1 do
    Inc(Result, GetI(list,i));
end;

procedure PutLast(list: TListView; value: String);
begin
  if list.Items.Count > 0 then
  with list.Items.Item[list.Items.Count-1] do begin
    if SubItems.Count < 1
    then SubItems.Add(value)
    else SubItems[0] := value;
  end;
  list.Width := list.Width - 1; // trigger an autosize
end;

procedure TMainForm.LevelUp;
var
  i: Integer;
begin
  Add(Traits,'Level',1);
  Add(Stats,'HP Max', GetI(Stats,'CON') div 3 + 1 + Random(4));
  Add(Stats,'MP Max', GetI(Stats,'INT') div 3 + 1 + Random(4));
  for i := 1 to 2 do WinStat;
  WinSpell;
  with ExpBar do begin
    Position := 0;
    Max := LevelUpTime(GetI(Traits,'Level'));
  end;
  SaveGame;
  Brag('l');
end;

procedure TMainForm.ClearAllSelections;
begin
      Equips.ClearSelection;
      Spells.ClearSelection;
      Stats.ClearSelection;
      Traits.ClearSelection;
      Inventory.ClearSelection;
      Plots.ClearSelection;
      Quests.ClearSelection;
end;

function RoughTime(s: Integer): String;
begin
  if s < 120 then Result := IntToStr(s) + ' seconds'
  else if s < 60 * 120 then Result := IntToStr(s div 60) + ' minutes'
  else if s < 60 * 60 * 48 then Result := IntToStr(s div 3600) + ' hours'
  else Result := IntToStr(s div (3600 * 24)) + ' days';
end;

procedure TMainForm.Timer1Timer(Sender: TObject);
var
  gain: Boolean;
  elapsed: Integer;
begin
  gain := Pos('kill|',fTask.Caption) = 1;
  with TaskBar do begin
    if Position >= Max then begin
      ClearAllSelections;

      if Kill.SimpleText = 'Loading....' then Max := 0;

      // gain XP / level up
      if gain then with ExpBar do if Position >= Max
      then LevelUp
      else Position := Position + TaskBar.Max div 1000;
      with ExpBar do Hint := IntToStr(Max-Position) + ' XP needed for next level';

      // advance quest
      if gain then if Plots.Items.Count > 1 then with QuestBar do if Position >= Max then begin
          CompleteQuest;
      end else if Quests.Items.Count > 0 then begin
          Position := Position + TaskBar.Max div 1000;
          Hint := IntToStr(100 * Position div Max) + '% complete';
      end;

      // advance plot
      if gain then with PlotBar do if Position >= Max
      then InterplotCinematic
      else Position := Position + TaskBar.Max div 1000;

      //Time.Caption := FormatDateTime('h:mm:ss',PlotBar.Position / (24.0 * 60 * 60));
      PlotBar.Hint := RoughTime(PlotBar.Max-PlotBar.Position) + ' remaining';
      //PlotBar.Hint := FormatDateTime('h:mm:ss" remaining"',(PlotBar.Max-PlotBar.Position) / (24.0 * 60 * 60));

      Dequeue();
    end else with TaskBar do begin
      elapsed := LongInt(timeGetTime) - LongInt(Timer1.Tag);
      if elapsed > 100 then elapsed := 100;
      if elapsed < 0 then elapsed := 0;
      Position := Position + elapsed;
    end;
  end;
  Timer1.Tag := timeGetTime;
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  QuestBar.Position := 0;
  PlotBar.Position := 0;
  TaskBar.Position := 0;
  ExpBar.Position := 0;
  Encumbar.Position := 0;

  FReportSave := true;
  FLogEvents := false;
  FMakeBackups := true;
  FMinToTray := true;
  FExportSheets := false;

  MakeFileAssociations;
end;

procedure TMainForm.SpeedButton1Click(Sender: TObject);
begin
  {$IFDEF CHEATS}
  TaskBar.Position := TaskBar.Max;
  {$ENDIF}
end;

function TMainForm.RollCharacter: Boolean;
var
  f: Integer;
begin
  Result := true;
  repeat
    if not NewGuyForm.Go then begin
      Result := false;
      Exit;
    end;
    Put(Traits, 'Name', NewGuyForm.Name.Text);
    if FileExists(GameSaveName) and
          (mrNo = MessageDlg('The saved game "' + GameSaveName + '" already exists. Do you want to overwrite it?', mtWarning, [mbYes,mbNo], 0)) then begin
      // go around again
    end else begin
      f := FileCreate(GameSaveName);
      if f = -1 then begin
        ShowMessage('The thought police don''t like the name "' + GameSaveName + '". Choose a name without \\ / : * ? " < > or | in it.');
      end else begin
        FileClose(f);
        Break;
      end;
    end;
  until false;

  with NewGuyForm do begin
    Put(Traits,'Name',Name.Text);
    Put(Traits,'Race',Race.Items[Race.ItemIndex]);
    Put(Traits,'Class',Klass.Items[Klass.ItemIndex]);
    Put(Traits,'Level',1);
    Put(Stats,'STR',STR.Tag);
    Put(Stats,'CON',CON.Tag);
    Put(Stats,'DEX',DEX.Tag);
    Put(Stats,'INT',INT.Tag);
    Put(Stats,'WIS',WIS.Tag);
    Put(Stats,'CHA',CHA.Tag);
    Put(Stats,'HP Max',Random(8) + CON.Tag div 6);
    Put(Stats,'MP Max',Random(8) + INT.Tag div 6);
    Put(Equips,'Weapon','Sharp Stick');
    Put(Inventory,'Gold',0);
    InventoryLabelAlsoGameStyle.Tag := 3;//GameStyle.Position;
    ClearAllSelections;
    GoButtonClick(NewGuyForm);
  end;
end;

const
  KUsage =
    'Usage: pq [flags] [game.pq3]'#10 +
    #10 +
    'Flags:'#10 +
    '  -no-backup     Do not make a backup file when saving the game'#10 +
    {$IFDEF LOGGING}
    '  -log           Create a text log of events as they occur in the game'#10 +
    {$ENDIF}
    '  -no-report-save   Do not display the "Game saved" message when saving'#10 +
    '  -no-tray       Do not minimize to the system tray'#10 +
    '  -export        Export a text character sheet periodically'#10 +
    '  -export-only   Export a text character sheet now, then exit'#10 +
    '  -no-proxy      Do not use Internet Explorer proxy settings'#10 +
    '  -help          Display this chatter (and exit)'#10 ;

procedure TMainForm.FormShow(Sender: TObject);
var
  done, exportandexit: Boolean;
  i: Integer;
begin
  if Timer1.Enabled then Exit;
  done := false;
  exportandexit := false;
  for i := 1 to ParamCount do begin
    if ParamStr(i) = '-backup'
    then FMakeBackups := true
    {$IFDEF LOGGING}
    else if ParamStr(i) = '-log'
    then FLogEvents := true
    {$ENDIF}
    else if ParamStr(i) = '-no-report-save'
    then FReportSave := false
    else if ParamStr(i) = '-no-tray'
    then FMinToTray := false
    else if ParamStr(i) = '-export'
    then FExportSheets := true
    else if ParamStr(i) = '-export-only'
    then exportandexit := true
    else if ParamStr(i) = '-no-proxy'
    then ProxyOK := false
    else if ParamStr(i) = '-help'
    then begin
      ShowMessage(KUsage);
      Close;
      Exit;
    end else begin
      LoadGame(ParamStr(i));
      if exportandexit then begin
        ExportCharSheet;
        Timer1.Enabled := false;
        Close;
      end;
      Exit;
    end;
  end;
  while not Done do begin
    SetHostName('');
    SetHostAddr('');
    SetLogin('');
    SetPassword('');
    case FrontForm.ShowModal of
    mrOk: begin
        done := RollCharacter;
      end;
    mrRetry: begin
      // load
        if FrontForm.OpenDialog1.Execute then begin
          LoadGame(FrontForm.OpenDialog1.Filename);
          Done := true;
        end;
      end;
    mrYesToAll: begin
        Done := ServerSelectForm.Go;
      end;
    mrCancel: begin
        Close;
        Done := true;
      end;
    end;
  end;
end;

procedure TMainForm.Button1Click(Sender: TObject);
begin
  {$IFDEF CHEATS}
  LevelUp;
  {$ENDIF}
end;

procedure TMainForm.CashInClick(Sender: TObject);
begin
  {$IFDEF CHEATS}
  WinEquip;
  WinItem;
  WinSpell;
  WinStat;
  Add(Inventory,'Gold',Random(100));
  {$ENDIF}
end;

procedure TMainForm.FinishQuestClick(Sender: TObject);
begin
  {$IFDEF CHEATS}
  QuestBar.Position := QuestBar.Max;
  TaskBar.Position := TaskBar.Max;
  {$ENDIF}
end;

procedure TMainForm.CheatPlotClick(Sender: TObject);
begin
  {$IFDEF CHEATS}
  PlotBar.Position := PlotBar.Max;
  TaskBar.Position := TaskBar.Max;
  {$ENDIF}
end;

function TMainForm.SaveGame: Boolean;
var
  f: TFileStream;
  m: TMemoryStream;
  i: Integer;
begin
  {$IFDEF LOGGING}
  Log('Saving game: ' + GameSaveName);
  {$ENDIF}
  Result := true;
  try
    if FMakeBackups then begin
      DeleteFile(ChangeFileExt(GameSaveName, '.bak'));
      MoveFile(PChar(GameSaveName), PChar(ChangeFileExt(GameSaveName, '.bak')));
    end;
    f := TFileStream.Create(GameSaveName, fmCreate);
  except
    on EfCreateError do begin
      Result := false;
      Exit;
    end;
  end;

  //ClearAllSelections;
  m := TMemoryStream.Create;
  for i := 0 to ComponentCount-1 do
    m.WriteComponent(Components[i]);

  m.Seek(0, soFromBeginning);
  ZCompressStream(m, f);

  m.Free;
  f.Free;
end;

procedure TMainForm.LoadGame(name: String);
var
  f: TStream;
  m: TStream;
  i: Integer;
begin
  FSaveFileName := name;
  m := TMemoryStream.Create;
  f := TFileStream.Create(name, fmOpenRead);
  try
    ZDecompressStream(f, m);
    f.Free;
  except
    on EZCompressionError do begin
      ShowMessage('Error loading game.');
      Close;
      Exit;
    end;
  end;
  Traits.Items.Clear;
  Stats.Items.Clear;
  Equips.Items.Clear;
  m.Seek(0, soFromBeginning);
  for i := 0 to ComponentCount-1 do
    m.ReadComponent(Components[i]);
  m.Free;
  {$IFDEF LOGGING}
  Log('Loaded game: ' + name);
  {$ENDIF}
  StartTimer;
  TriggerAutosizes;
end;

procedure TMainForm.TriggerAutosizes;
begin
  Plots.Width := 100;
  Quests.Width := 100;
  Inventory.Width := 100;
  Equips.Width := 100;
  Spells.Width := 100;
  Traits.Width := 100;
  Stats.Width := 100;
end;

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Timer1.Enabled then begin
    Timer1.Enabled := false;
    Shell_NotifyIcon(NIM_DELETE, @FTrayIcon);
    if SaveGame then
      if FReportSave then
        ShowMessage('Game saved as ' + GameSaveName);
  end;
  FReportSave := true;
  Action := caFree;
end;

function TMainForm.GameSaveName: String;
begin
  if FSaveFileName = '' then begin
    FSaveFileName := Get(Traits,'Name');
    if GetHostName <> '' then
      FSaveFileName := FSaveFileName + ' [' + GetHostName + ']';
    FSaveFileName := FSaveFileName + kFileExt;
    FSaveFileName := ExpandFileName(PChar(FSaveFileName));
  end;
  Result := FSaveFileName;
end;

procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (FindWindow('TAppBuilder', nil) > 0) and (ssCtrl in Shift) and (ssShift in Shift) and (Key = ord('C')) then begin
    {$IFDEF CHEATS}
    Cheats.Visible := not Cheats.Visible;
    {$ENDIF}
  end;
  if (ssCtrl in Shift) and (Key = ord('A')) then begin
    ShowMessage(CharSheet);
  end;
  if GetPasskey = 0 then Exit; // no need for these things
  if (ssCtrl in Shift) and (Key = ord('B')) then begin
    Brag('b');
    Navigate(GetHostAddr + 'name=' + UrlEncode(Get(Traits,'Name')));
  end;
  if (ssCtrl in Shift) and (Key = ord('M')) then begin
    SetMotto(InputBox('Progress Quest', 'Declare your motto!', GetMotto));
    Brag('m');
    Navigate(GetHostAddr + 'name=' + UrlEncode(Get(Traits,'Name')));
  end;
  if (ssCtrl in Shift) and (Key = ord('G')) then begin
    SetGuild(InputBox('Progress Quest', 'Choose a guild.'#13#13'Make sure you undestand the guild rules before you join one. To learn more about guilds, visit http://progressquest.com/guilds.php', GetGuild));
    Guildify;
  end;
end;

procedure Navigate(url: String);
begin
  ShellExecute(GetDesktopWindow(), 'open', PChar(url), nil, '', SW_SHOW);
end;

function LFSR(pt: String; salt: Integer): Integer;
var
  k: Integer;
begin
  Result := salt;
  for k := 1 to Length(pt) do
    Result := Ord(pt[k])
          xor (Result shl 1)
          xor (1 and ((Result shr 31) xor (Result shr 5)));
  for k := 1 to 10 do
    Result := (Result shl 1)
          xor (1 and ((Result shr 31) xor (Result shr 5)));
end;


procedure TMainForm.Brag(trigger: String);
var
  url, body: string;
  best, i: Integer;
const
  flat = 1;
begin
  if FExportSheets then
    ExportCharSheet;
  if GetPasskey = 0 then Exit; // not a online game!
  url := 'cmd=b&t=' + trigger;
  with Traits do for i := 0 to Items.Count-1 do
    url := url + '&' + LowerCase(Items[i].Caption[1]) + '=' + UrlEncode(Items[i].Subitems[0]);
  url := url + '&x=' + IntToStr(ExpBar.Position);
  url := url + '&i=' + UrlEncode(Get(Equips,Equips.Tag));
  if Equips.Tag > 1 then url := url + '+' + Equips.Items[Equips.Tag].Caption;
  best := 0;
  if Spells.Items.Count > 0 then with Spells do begin
    for i := 1 to Items.Count-1 do
      if (i+flat) * RomanToInt(Get(Spells,i)) >
         (best+flat) * RomanToInt(Get(Spells,best)) then
        best := i;
    url := url + '&z=' + UrlEncode(Items[best].Caption + ' ' + Get(Spells,best));
  end;
  best := 0;
  for i := 1 to 5 do
    if GetI(Stats,i) > GetI(Stats,best) then best := i;
  url := url + '&k=' + Stats.Items[best].Caption + '+' + Get(Stats,best);
  url := url + '&a=' + UrlEncode(Plots.Items[Plots.Items.Count-1].Caption);
  url := url + '&h=' + UrlEncode(GetHostName);
  url := url + RevString;
  url := url + '&p=' + IntToStr(LFSR(url, GetPasskey));
  url := url + '&m=' + UrlEncode(GetMotto);
  url := AuthenticateUrl(GetHostAddr + url);
  try
    body := DownloadString(url);
    if (LowerCase(Split(body,0)) = 'report') then
      ShowMessage(Split(body,1));
  except
    on EWebError do begin
      // 'ats okay.
    end;
  end;
end;

function TMainForm.AuthenticateUrl(url: String): String;
begin
  if (GetLogin <> '') or (GetPassword <> '') then
    Result := StuffString(url, 8, 0, GetLogin+':'+GetPassword+'@')
  else
    Result := url;
end;

procedure TMainForm.Guildify;
var
  url, s,b: string;
  i: Integer;
begin
  if GetPasskey = 0 then Exit; // not a online game!
  url := 'cmd=guild';
  with Traits do for i := 0 to Items.Count-1 do
    url := url + '&' + LowerCase(Items[i].Caption[1]) + '=' + UrlEncode(Items[i].Subitems[0]);
  url := url + '&h=' + UrlEncode(GetHostName);
  url := url + RevString;
  url := url + '&guild=' + UrlEncode(GetGuild);
  url := url + '&p=' + IntToStr(LFSR(url, GetPasskey));
  url := AuthenticateUrl(GetHostAddr + url);
  try
    b := DownloadString(url);
    s := Take(b);
    if s <> '' then ShowMessage(s);
    s := Take(b);
    if s <> '' then Navigate(s);
  except
    on EWebError do begin
      // 'ats okay.
      Abort;
    end;
  end;
end;

procedure TMainForm.OnQueryEndSession(var Msg: TMessage);
var Action: TCloseAction;
begin
  FReportSave := false;
  FormClose(Self, Action);
  ReplyMessage(-1);
end;

procedure TMainForm.OnEndSession(var Msg: TMessage);
var Action: TCloseAction;
begin
  Msg.Result := 0;
  if Msg.wParam <> 0 then begin
    FReportSave := false;
    FormClose(Self, Action);
  end;
  ReplyMessage(0);
end;

initialization
  RegisterClasses([TMainForm]);
end.