-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.pas
7441 lines (6171 loc) · 263 KB
/
Server.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit Server;
// routine principali:
// procedure TcpserverDataAvailable <-- tutti gli input del client passano da qui
// procedure QueueThreadTimer <-- crea le partite(brain) in base agli utenti in coda di attesa
// procedure MatchThreadTimer <-- in caso di bot o disconessione, esegue l'intelligenza artificiale TSoccerBrain.AI_think
// procedure CreateAndLoadMatch <-- crea una partita (brain)
{$R-}
{$DEFINE BOTS} // se uso i bot o solo partite di player reali
{$DEFINE useMemo} // se uso il debug a video delle informazioni importanti
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Hash , DateUtils,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Strutils,generics.collections, generics.defaults,
Vcl.ExtCtrls, Vcl.Mask, Vcl.Grids, inifiles, System.Types, FolderDialog,
ZLIBEX,
Soccerbrainv3,
utilities,
// shotcellsv1,
// AIFieldv1,
// TVAICrossingAreaCellsv1,
DSE_theater,
DSE_SearchFiles,
DSE_Random,
DSE_ThreadTimer,
DSE_GRID,
DSE_Misc,
MyAccess, DBAccess, Data.DB,
OverbyteIcsWndControl, OverbyteIcsWSocket, OverbyteIcsWSocketS, OverbyteIcsWSocketTS, Vcl.ComCtrls ;
const gender ='fm';
const PlayerCountStart = 15;
type TAuthInfo = record // usato durante il login in TFormServer.TcpserverDataAvailable
GmLevel: Integer; // gm=1 il client può mandare comandi di utilità come spostare manualmente la palla
Account: Integer; // DB realmd.account.id
AccountStatus : Integer; // 0=login errore, 1=ok login, ma ancora senza team--> selezione team, 2=tutto ok
GuidTeams: TguidTeams; // DB f_game.teams.guid
TeamName: string;
WorldTeam: Integer;
PassWord: string;
UserName: string;
Flags: Integer; // se devo loggare la partita o no
nextha: integer; // prossima partita in casa o fuori (Home,Away)
mi : Integer; // media inglese
end;
type TServerOpponent = record
GuidTeam : integer;
UserName: string;
bot : Boolean;
CliId : Integer;
end;
type TBrainManager = class
public
lstBrain: TObjectList<TSoccerBrain>;
constructor Create( Server: TWSocketThrdServer );
destructor Destroy;override;
procedure input (brain: TSoccerBrain; data: string );
function GetbrainStream ( brain: TSoccerBrain) : string;
procedure FinalizeBrain (brain: TSoccerBrain );
procedure DecodeBrainIds ( brainIds: string; var MyYear, MyMonth, MyDay, MyHour, MyMin, MySec: string );
function RndGenerate( Upper: integer ): integer;
function RndGenerate0( Upper: integer ): integer;
function RndGenerateRange( Lower, Upper: integer ): integer;
function FindBrain ( ids: string ): TSoccerbrain; overload;
function FindBrain ( CliId: integer ): TSoccerbrain; overload;
procedure AddBrain ( brain: TSoccerbrain );
procedure RemoveBrain ( brainIds: string);
end;
type
TFormServer = class(TForm)
Tcpserver: TWSocketThrdServer;
Memo1: TMemo;
Label1: TLabel;
btnKillAllBrain: TButton;
btnStopAllBrain: TButton;
btnStartAllBrain: TButton;
Button1: TButton;
QueueThread: SE_ThreadTimer;
MatchThread: SE_ThreadTimer;
Button2: TButton;
threadBot: SE_ThreadTimer;
Button3: TButton;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
Label3: TLabel;
CheckBox2: TCheckBox;
CheckBoxActiveMacthes: TCheckBox;
CheckBox1: TCheckBox;
Edit1: TEdit;
edit4: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Panel1: TPanel;
Button5: TButton;
Edit5: TEdit;
Edit6: TEdit;
Button6: TButton;
FolderDialog1: TFolderDialog;
Button7: TButton;
Button8: TButton;
StringGrid1: TStringGrid;
Button4: TButton;
Button9: TButton;
Edit7: TEdit;
Edit8: TEdit;
Button10: TButton;
ProgressBar1: TProgressBar;
Memo2: TMemo;
Button11: TButton;
Button12: TButton;
procedure FormCreate(Sender: TObject);
procedure CleanDirectory(dir:string);
procedure FormDestroy(Sender: TObject);
procedure LoadPreset;
// tcp
procedure TcpserverBgException(Sender: TObject; E: Exception; var CanClose: Boolean);
procedure TcpserverClientConnect(Sender: TObject; Client: TWSocketClient; Error: Word);
procedure TcpserverClientDisconnect(Sender: TObject; Client: TWSocketClient; Error: Word);
procedure TcpserverDataAvailable(Sender: TObject; ErrCode: Word);
procedure TcpserverException(Sender: TObject; SocExcept: ESocketException);
procedure TcpserverLineLimitExceeded(Sender: TObject; RcvdLength: Integer; var ClearData: Boolean);
procedure TcpserverThreadException(Sender: TObject; AThread: TWsClientThread; const AErrMsg: string);
procedure TcpserverError(Sender: TObject);
procedure TcpserverSocksError(Sender: TObject; Error: Integer; Msg: string);
Function CheckAuth ( UserName, Password: string): TAuthInfo;
function CreateGameTeam ( fm :char; cli: TWSocketThrdClient; WorldTeamGuid: string): integer;
function GetQueueOpponent ( fm : Char; WorldTeam : integer; Rank, NextHA: byte ): TWSocketThrdClient; // rank < > 1 = tolleranza
procedure GetGuidTeamOpponentBOT (fm :Char; WorldTeam : integer; Rank, NextHA: byte; var BotGuidTeam: Integer; var BotUserName: string ); // rank < > 1 = tolleranza
function GetTCPClient ( CliId: integer): TWSocketClient;
function GetTCPClientQueue ( CliId: integer): TWSocketClient;
procedure QueueThreadTimer(Sender: TObject);
function GetbrainIds ( fm :Char; GuidTeam0, GuidTeam1: string ) : string;
procedure MatchThreadTimer(Sender: TObject);
procedure btnKillAllBrainClick(Sender: TObject);
procedure btnStopAllBrainClick(Sender: TObject);
procedure btnStartAllBrainClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure threadBotTimer(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure RadioButton1Click(Sender: TObject);
procedure RadioButton2Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure Button10Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button11Click(Sender: TObject);
procedure Button12Click(Sender: TObject);
private
{ Private declarations }
procedure Display(Msg : String);
(* validazione input dal client di gioco*)
procedure validate_login ( const CommaText: string; Cli:TWSocketThrdClient );
function LastIncMoveIni ( directory: string ): string;
procedure validate_getteamsbycountry ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_clientcreateteam ( const CommaText: string; Cli:TWSocketThrdClient) ;
procedure validate_viewMatch ( const CommaText: string; Cli:TWSocketThrdClient) ;
procedure validate_levelupAttribute ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_levelupTalent ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMDlop ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD4 ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD3 ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD2 ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_debug_CMD2 ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD1 ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD_coa ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD_cod ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD_bar ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_CMD_subs ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_aiteam ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_setplayer ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_pause ( const CommaText: string; Cli:TWSocketThrdClient );
procedure validate_setformation ( CommaText: string; Cli:TWSocketThrdClient );
procedure validate_setuniform ( CommaText: string; Cli:TWSocketThrdClient );
function validate_player ( const guid: integer; Cli:TWSocketThrdClient): TValidPlayer;
procedure validate_sell ( commatext: string; Cli:TWSocketThrdClient );
procedure validate_cancelsell ( commatext: string; Cli:TWSocketThrdClient );
procedure validate_buy ( commatext: string; Cli:TWSocketThrdClient );
procedure validate_market ( commatext: string; Cli:TWSocketThrdClient );
procedure validate_dismiss ( commatext: string; Cli:TWSocketThrdClient );
procedure reset_formation ( Cli:TWSocketThrdClient ); overload;
procedure reset_formation ( fm : Char;GuidTeam: integer ); overload;
function checkformation ( Cli:TWSocketThrdClient ): Boolean;
procedure store_formation ( fm : Char; CommaText: string );
procedure store_Uniform ( Guidteam: integer; CommaText: string );
// mercato player
procedure MarketSell ( Cli: TWSocketThrdClient; CommaText: string );
procedure MarketCancelSell ( Cli: TWSocketThrdClient; CommaText: string );
procedure DismissPlayer ( Cli: TWSocketThrdClient; CommaText: string );
procedure MarketBuy ( Cli: TWSocketThrdClient; CommaText: string );
function TryAddYoung ( fm :Char; GuidTeam: Integer): Boolean;
function CalculateRank ( mi : integer): Integer;
function RandomPassword(PLen: Integer): string; // deprecated
function RndGenerate( Upper: integer ): integer;
function RndGenerate0( Upper: integer ): integer;
function RndGenerateRange( Lower, Upper: integer ): integer;
function RemoveFromQueue(Cliid: integer ): Boolean;
function inQueue(Cliid: integer ): Boolean;
function inSpectator(Cliid: integer ): boolean;
function inLiveMatchCliid(Cliid: integer ): Boolean;
function inLivematchGuidTeam(fm : char;GuidTeam: integer ): TSoccerBrain;
function inSpectatorGetBrain(Cliid: integer ): TSoccerBrain;
function RemoveFromSpectator(Cliid: integer ): boolean;
procedure CreateAndLoadMatch ( fm:Char; brain: TSoccerBrain; GuidTeam0, GuidTeam1: integer; Username0, UserName1: string );
procedure CreateMatchBOTvsBOT ( fm:Char; GuidTeam0, GuidTeam1: integer; Username0, UserName1: string );
function CreateRandomPlayer ( fm :Char; Country: integer; EnableTalent2: boolean ) : TBasePlayer;
function CreatePresetPlayer ( fm :Char; Country, index: integer ) : TBasePlayer;
function CreateSurname ( fm : Char; Country: Integer ): string;
procedure CreateRandomBotMatch ( fm :char) ;
procedure CreateRewards;
public
procedure SetupRefreshGrid;
(* procedure che si attivano solo al primo login o comunque se l'account non ha ancora scelto la sua squadra del cuore *)
procedure PrepareWorldCountries ( directory: string ); overload;
procedure PrepareWorldCountries ; overload;
procedure PrepareWorldTeams( directory, CountryID: string );overload;
procedure PrepareNationTeams( CountryID: integer; var TsNationTeam: TStringList );
procedure PrepareWorldTeams( CountryID: integer ); overload;
function GetTeamStream ( GuidTeam: Integer; fm :char): string; // dati compressi del proprio team
function GetListActiveBrainStream (fm : Char) : string;
function GetMarketPlayers (fm: Char; Myteam, Maxvalue: Integer): string;
end;
const EndofLine = 'ENDSOCCER';
const GLOBAL_COOLDOWN = 200; // 200 misslisecondi tra un input e l'altro del client, altrimenti è spam/cheating
const MIN_DEVA=5; MIN_DEVT = 5; MIN_DEVI =1; MAX_DEVA=30; MAX_DEVT=30; MAX_DEVI=20;
var
FormServer: TFormServer;
BrainManager: TBrainManager;
TsWorldCountries: TStringList;
TsWorldTeams: array [1..6] of TStringList; // le nazioni del DB world
Queue: TObjectList<TWSocketThrdClient>;
RandGen: TtdBasePRNG;
Mutex,MutexMarket,MutexLockbrain: cardinal;
dir_log: string;
MySqlServerGame, MySqlServerWorld, MySqlServerAccount: string; // le 3 tabelle del DB: account, world e Game
// world contiene le definizioni come i nomi delle squadre e i cognomi dei player
Rewards : array [1..4, 1..20] of Integer;
mfaces : array[1..6] of Integer;
ffaces : array[1..6] of Integer;
mp_template: array [0..PlayerCountStart-1] of Integer;
PresetF : array[0..PlayerCountStart-1] of string;
PresetM : array[0..PlayerCountStart-1] of string;
PresetFT : array[0..PlayerCountStart-1] of byte;
PresetMT : array[0..PlayerCountStart-1] of byte;
implementation
{$R *.dfm}
function RemoveEndOfLine(const Line : String) : String;
begin
if (Length(Line) >= Length(EndOfLine)) and
(StrLComp(PChar(@Line[1 + Length(Line) - Length(EndOfLine)]),
PChar(EndOfLine),
Length(EndOfLine)) = 0) then
Result := Copy(Line, 1, Length(Line) - Length(EndOfLine))
else
Result := Line;
end;
function IsStandardText(const aValue: string): Boolean; // accetta solo certi caratteri in input dal client
const
CHARS = ['0'..'9', 'a'..'z', 'A'..'Z', ',', ':','=','.','_' ,'-' ];
var
i: Integer;
aString: string;
begin
aString := aValue.Trim;
for i := 1 to Length(aString) do begin
if not (aString[i] in CHARS) then begin
Result := False;
Exit;
end;
end;
Result := true;
end;
function GetStrHashSHA1(Str: String): String; // decodifica password DB
var
HashSHA: THashSHA1;
begin
HashSHA := THashSHA1.Create;
HashSHA.GetHashString(Str);
result := HashSHA.GetHashString(Str);
end;
function TryDecimalStrToInt( const S: string; out Value: Integer): Boolean;
begin
result := ( pos( '$', S ) = 0 ) and TryStrToInt( S, Value );
end;
procedure TFormServer.RadioButton1Click(Sender: TObject);
begin
if RadioButton1.Checked then
edit3.Visible := False
else edit3.Visible := True;
end;
procedure TFormServer.RadioButton2Click(Sender: TObject);
begin
if RadioButton2.Checked then begin
edit2.Visible := true;
edit3.Visible := True;
end
else edit3.visible := False;
end;
function TFormServer.RandomPassword(PLen: Integer): string;
var
str: string;
begin
Randomize;
//string with all possible chars
str := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Result := '';
repeat
Result := Result + str[RndGenerate(Length(str)) ];
until (Length(Result) = PLen)
end;
procedure TFormServer.btnKillAllBrainClick(Sender: TObject);
var
i: Integer;
begin
WaitForSingleObject(Mutex,INFINITE);
for I := brainManager.lstBrain.Count -1 downto 0 do begin
brainManager.RemoveBrain ( BrainManager.lstBrain[i].BrainIDS );
end;
ReleaseMutex(Mutex);
end;
procedure TFormServer.SetupRefreshGrid;
var
y: Integer;
begin
StringGrid1.RowCount := 1;
StringGrid1.RowCount := BrainManager.lstBrain.Count;
StringGrid1.ColCount := 10;
StringGrid1.ColWidths[0] := 220;
StringGrid1.ColWidths[1] := 220;
StringGrid1.ColWidths[2] := 50;
StringGrid1.ColWidths[3] := 50;
StringGrid1.ColWidths[4] := 60;
StringGrid1.ColWidths[5] := 60;
StringGrid1.ColWidths[6] := 50;
StringGrid1.ColWidths[7] := 50;
StringGrid1.ColWidths[8] := 70;
StringGrid1.ColWidths[9] := 20;
end;
procedure TFormServer.btnStartAllBrainClick(Sender: TObject);
var
i: Integer;
begin
WaitForSingleObject(Mutex,INFINITE);
for I := brainManager.lstBrain.Count -1 downto 0 do begin
brainManager.lstBrain[i].Paused := false;
end;
ReleaseMutex(Mutex);
end;
procedure TFormServer.btnStopAllBrainClick(Sender: TObject);
var
i: Integer;
begin
WaitForSingleObject(Mutex,INFINITE);
for I := brainManager.lstBrain.Count -1 downto 0 do begin
brainManager.lstBrain[i].Paused := True;
end;
ReleaseMutex(Mutex);
end;
procedure TFormServer.Button10Click(Sender: TObject);
var
mValue,T,G : Integer;
price: Integer;
ConnGame : TMyConnection ;
qTeams, qPlayers,qMarket,qPlayersGK: TMyQuery ;
label NextTeam;
begin
ConnGame := TMyConnection.Create(nil);
Conngame.Server := MySqlServerGame;
Conngame.Username:='root';
Conngame.Password:='root';
Conngame.Database:= 'f_game';
Conngame.Connected := True;
qTeams := TMyQuery.Create(nil);
qTeams.Connection := ConnGame; // game
qPlayers := TMyQuery.Create(nil);
qPlayers.Connection := ConnGame; // game
qPlayersGK := TMyQuery.Create(nil);
qPlayersGK.Connection := ConnGame; // game
qMarket := TMyQuery.Create(nil);
qMarket.Connection := ConnGame; // game
ProgressBar1.Position := 0 ;
for G := 1 to 2 do begin
qTeams.SQL.text := 'SELECT guid from ' + Gender[G]+ '_game.teams';
qTeams.Execute ;
for T := 0 to qTeams.RecordCount -1 do begin
qPlayers.SQL.text := 'SELECT * from ' + Gender[G]+ '_game.players WHERE onmarket=0 and team=' +
qTeams.FieldByName('guid').AsString +' and young=0 order by rand() limit 1';
qPlayers.Execute ;
// non deve essere presente sul mercato
qMarket.SQL.text := 'SELECT guid from '+Gender[G]+'_game.market WHERE guid =' + qPlayers.FieldByName('guid').AsString ;
qMarket.Execute ;
if qMarket.RecordCount > 0 then goto NextTeam; // non posso venderlo, non faccio nulla
// sul mercato massimo 3 player
qMarket.SQL.text := 'SELECT guid from '+Gender[G]+'_game.market WHERE guidteam =' + qTeams.FieldByName('guid').AsString;
qMarket.Execute ;
if qMarket.RecordCount >= 3 then goto NextTeam; // non posso venderlo, non faccio nulla
if qPlayers.FieldByName('talentid1').AsInteger <> TALENT_ID_GOALKEEPER then // non un goalkeeper (portiere) o senza talento o con talento
mValue := Trunc ( qPlayers.FieldByName('speed').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('speed').AsInteger] +
qPlayers.FieldByName('defense').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('defense').AsInteger] +
qPlayers.FieldByName('passing').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('passing').AsInteger] +
qPlayers.FieldByName('ballcontrol').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('ballcontrol').AsInteger] +
qPlayers.FieldByName('shot').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('shot').AsInteger] +
qPlayers.FieldByName('heading').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('heading').AsInteger])
else if qPlayers.FieldByName('talentid1').AsInteger = TALENT_ID_GOALKEEPER then begin // un portiere
mValue := Trunc ((qPlayers.FieldByName('defense').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('defense').AsInteger] * MARKET_VALUE_ATTRIBUTE_DEFENSE_GK) +
qPlayers.FieldByName('passing').AsInteger * MARKET_VALUE_ATTRIBUTE [qPlayers.FieldByName('passing').AsInteger] );
// è un goalkeeper, se è l'unico non posso venderlo . se ce nes sono di più, ce ne deve essere almeno 1 non sul mercato
qPlayersGK.SQL.text := 'SELECT * from ' + Gender[G]+'_game.players WHERE talentid1=1 ' +
'and guid <>' + qPlayers.FieldByName('guid').AsString +
' and onmarket=0 and team=' + qTeams.FieldByName('guid').AsString + ' and young=0';
qPlayersGK.Execute ;
if qPlayersGK.RecordCount = 0 then goto NextTeam; // non posso venderlo, non faccio nulla
end;
if qPlayers.FieldByName('talentid1').AsInteger <> 0 then mValue := Trunc (mValue * MARKET_VALUE_TALENT1) ; //se c'è un talento, anche goalkeeper
if qPlayers.FieldByName('talentid2').AsInteger <> 0 then mValue := mValue + Trunc (mValue * MARKET_VALUE_TALENT2) ;
// update f_game.players onmarket e market con tutti i dati attuali e congelati qui
qMarket.SQL.text := 'INSERT INTO '+Gender[G]+'_game.market (speed,defense,passing,ballcontrol,shot,heading,talentid1,talentid2,'+
'matches_played,matches_left,name,guidteam,guidplayer,face,sellprice,history,xp,country,fitness,morale) VALUES ('+
qPlayers.FieldByName('speed').AsString +
',' + qPlayers.FieldByName('defense').AsString +
',' + qPlayers.FieldByName('passing').AsString +
',' + qPlayers.FieldByName('ballcontrol').AsString +
',' + qPlayers.FieldByName('shot').AsString +
',' + qPlayers.FieldByName('heading').AsString +
',' + qPlayers.FieldByName('talentid1').AsString +
',' + qPlayers.FieldByName('talentid2').AsString +
',' + qPlayers.FieldByName('matches_played').AsString +
',' + qPlayers.FieldByName('matches_left').AsString +
',"' + qPlayers.FieldByName('name').AsString + '"'+
',' + qPlayers.FieldByName('team').AsString + // guidteam
',' + qPlayers.FieldByName('guid').AsString + // guidplayer
',' + qPlayers.FieldByName('face').AsString + // face
',' + IntToStr(mValue) + // price
',"' + qPlayers.FieldByName('history').AsString + '"'+
',"' + qPlayers.FieldByName('xp').AsString + '"'+
',' + qPlayers.FieldByName('country').AsString +
',' + qPlayers.FieldByName('fitness').AsString +
',' + qPlayers.FieldByName('morale').AsString
+ ')';
qMarket.Execute ;
qPlayers.SQL.text := 'UPDATE '+Gender[G]+'_game.players set onmarket=1 WHERE guid =' + qPlayers.FieldByName('guid').AsString +
' and team=' + qTeams.FieldByName('guid').AsString ; // per essere sicuri anche cli.guidteam
qPlayers.Execute ;
NextTeam:
qTeams.Next;
ProgressBar1.Position := (100* t) div qTeams.RecordCount ;
end;
end;
qTeams.Free;
qPlayers.Free;
qPlayersGK.Free;
qMarket.Free;
Conngame.Connected := False;
Conngame.Free;
ProgressBar1.Position := 0 ;
ShowMessage ('Done!');
end;
procedure TFormServer.Button1Click(Sender: TObject);
var
MyQueryAccount: TMyQuery ;
sha_pass_hash: string;
i: Integer;
UserName,password : string;
cli: TWSocketThrdClient;
ConnAccount : TMyConnection ;
label createteam;
begin
ConnAccount := TMyConnection.Create(nil);
ConnAccount.Server := MySqlServerAccount;
ConnAccount.Username:='root';
ConnAccount.Password:='root';
ConnAccount.Database:='realmd';
ConnAccount.Connected := True;
MyQueryAccount := TMyQuery.Create(nil);
MyQueryAccount.Connection := ConnAccount; // realmd
// genero test1, test2, test3 ecc....
for I := 1 to 300 do begin
username := Uppercase('TEST' + IntTostr(i));
password := UserName;
sha_pass_hash := GetStrHashSHA1 ( username + ':' + Password );
MyQueryAccount.SQL.Text := 'insert into realmd.account (username, sha_pass_hash, email) values (' +
'"' + username + '","' + sha_pass_hash + '","' + UserName +'.GMAIL.COM")';
MyQueryAccount.Execute;
ProgressBar1.Position := (100* i) div 300 ;
application.ProcessMessages;
end;
MyQueryAccount.free;
ConnAccount.Connected:= False;
ConnAccount.Free;
ShowMessage ('Done!');
ProgressBar1.Position := 0;
end;
Function TFormServer.CheckAuth ( UserName, Password: string): TAuthInfo;
var
MyQueryAccount,MyQueryTeam: TMyQuery ;
sha_pass_hash: string;
AccountID: string;
GmLevel: Integer;
ConnAccount,ConnGame : TMyConnection ;
begin
sha_pass_hash := GetStrHashSHA1 ( Uppercase(UserName) + ':' + Uppercase(Password));
ConnAccount := TMyConnection.Create(nil);
ConnAccount.Server := MySqlServerAccount;
ConnAccount.Username:='root';
ConnAccount.Password:='root';
ConnAccount.Database:='realmd';
ConnAccount.Connected := True;
ConnGame := TMyConnection.Create(nil);
Conngame.Server := MySqlServerGame;
Conngame.Username:='root';
Conngame.Password:='root';
Conngame.Database:='f_game';
Conngame.Connected := True;
MyQueryAccount := TMyQuery.Create(nil);
MyQueryAccount.Connection := ConnAccount; // realmd
MyQueryAccount.SQL.Text := 'SELECT id, username, gmlevel, flags FROM realmd.account where username = "' + UserName +
'" AND sha_pass_hash = "' + sha_pass_hash +'"';
MyQueryAccount.Execute;
if MyQueryAccount.RecordCount = 1 then begin
AccountID := MyQueryAccount.FieldByName('id').AsString ;
GmLevel:= MyQueryAccount.FieldByName('gmLevel').AsInteger;
MyQueryTeam := TMyQuery.Create(nil);
MyQueryTeam.Connection := Conngame; // game
MyQueryTeam.SQL.Text := 'SELECT guid, worldteam, teamname, nextha, mi FROM f_game.teams where account = ' + AccountID ; // teamid punta a world.team (e country in join)
MyQueryTeam.Execute;
if MyQueryTeam.RecordCount = 1 then begin // ho già il team
Result.Account := StrToInt(AccountId);
Result.AccountStatus := 2;
Result.GuidTeams[1] := MyQueryTeam.FieldByName ('guid').AsInteger ;
Result.WorldTeam := MyQueryTeam.FieldByName ('worldteam').AsInteger ;
Result.TeamName := MyQueryTeam.FieldByName ('teamname').AsString ;
Result.username := MyQueryAccount.FieldByName ('username').AsString ;
Result.flags := MyQueryAccount.FieldByName ('flags').AsInteger ;
Result.nextha := MyQueryTeam.FieldByName ('nextha').AsInteger ;
Result.mi := MyQueryTeam.FieldByName ('mi').AsInteger ;
Result.Password := Password;
Result.GmLevel := GmLevel;
end
else if MyQueryTeam.RecordCount = 0 then begin // ok login, ma senza team --> selezione team
Result.Account := StrToInt(AccountId);
Result.AccountStatus := 1;
Result.GuidTeams[1] := 0;
Result.Password := Password;
Result.username := MyQueryAccount.FieldByName ('username').AsString ;
Result.flags := MyQueryAccount.FieldByName ('flags').AsInteger ;
Result.GmLevel := GmLevel;
end;
MyQueryTeam.Free;
end
else if MyQueryAccount.RecordCount = 0 then begin // login incorrect
Result.Account := 0;
Result.GuidTeams[1] := 0;
Result.AccountStatus := 0;
Result.Password := '';
Result.username := '';
Result.GmLevel := 0;
end;
// ripero per reparto maschile
ConnGame := TMyConnection.Create(nil);
Conngame.Server := MySqlServerGame;
Conngame.Username:='root';
Conngame.Password:='root';
Conngame.Database:='m_game';
Conngame.Connected := True;
if MyQueryAccount.RecordCount = 1 then begin
AccountID := MyQueryAccount.FieldByName('id').AsString ;
GmLevel:= MyQueryAccount.FieldByName('gmLevel').AsInteger;
MyQueryTeam := TMyQuery.Create(nil);
MyQueryTeam.Connection := Conngame; // game
MyQueryTeam.SQL.Text := 'SELECT guid, worldteam, teamname, nextha, mi FROM m_game.teams where account = ' + AccountID ; // teamid punta a world.team (e country in join)
MyQueryTeam.Execute;
if MyQueryTeam.RecordCount = 1 then begin // ho già il team
Result.Account := StrToInt(AccountId);
Result.AccountStatus := 2;
Result.GuidTeams[2] := MyQueryTeam.FieldByName ('guid').AsInteger ;
Result.WorldTeam := MyQueryTeam.FieldByName ('worldteam').AsInteger ;
Result.TeamName := MyQueryTeam.FieldByName ('teamname').AsString ;
Result.username := MyQueryAccount.FieldByName ('username').AsString ;
Result.flags := MyQueryAccount.FieldByName ('flags').AsInteger ;
Result.nextha := MyQueryTeam.FieldByName ('nextha').AsInteger ;
Result.mi := MyQueryTeam.FieldByName ('mi').AsInteger ;
Result.Password := Password;
Result.GmLevel := GmLevel;
end
else if MyQueryTeam.RecordCount = 0 then begin // ok login, ma senza team --> selezione team
Result.Account := StrToInt(AccountId);
Result.AccountStatus := 1;
Result.GuidTeams[2] := 0;
Result.Password := Password;
Result.username := MyQueryAccount.FieldByName ('username').AsString ;
Result.flags := MyQueryAccount.FieldByName ('flags').AsInteger ;
Result.GmLevel := GmLevel;
end;
MyQueryTeam.Free;
end
else if MyQueryAccount.RecordCount = 0 then begin // login incorrect
Result.Account := 0;
Result.GuidTeams[2] := 0;
Result.AccountStatus := 0;
Result.Password := '';
Result.username := '';
Result.GmLevel := 0;
end;
MyQueryAccount.Free;
ConnAccount.Connected:= False;
ConnAccount.Free;
Conngame.Connected:= False;
Conngame.Free;
end;
procedure TFormServer.CheckBox2Click(Sender: TObject);
var
I: Integer;
begin
WaitForSingleObject(Mutex,INFINITE);
for I := brainManager.lstBrain.Count -1 downto 0 do begin
brainManager.lstBrain[i].LogUser [0]:= 1;
brainManager.lstBrain[i].LogUser [1]:= 1;
end;
ReleaseMutex(Mutex);
end;
constructor TBrainManager.Create( Server: TWSocketThrdServer );
begin
lstBrain:= TObjectList<TSoccerBrain>.Create(true);
{ ShotCells := CreateShotCells;
AIField := createAIfield;
TVCrossingAreaCells:= TVCreateCrossingAreaCells;
AICrossingAreaCells:= AICreateCrossingAreaCells; }
// CreateShotCells;
// createAIfield;
// TVCreateCrossingAreaCells;
// AICreateCrossingAreaCells;
end;
destructor TBrainManager.Destroy;
begin
// ShotCells.Free;
lstbrain.free;
inherited;
end;
procedure TBrainManager.input ( brain: TSoccerBrain; data: string );
var
i,ii,SpectatorCliId: Integer;
NewData: string;
MyQueryCheat: TMyQuery;
ConnAccount : TMyConnection;
begin
if LeftStr(Data,6) = 'cheat:' then begin
// uguale al primo check validate
ConnAccount := TMyConnection.Create(nil);
ConnAccount.Server := MySqlServerAccount;
ConnAccount.Username:='root';
ConnAccount.Password:='root';
ConnAccount.Database:='realmd';
ConnAccount.Connected := True;
MyQueryCheat := TMyQuery.Create(nil);
MyQueryCheat.Connection := ConnAccount;
MyQueryCheat.SQL.Text :='INSERT into cheat_detected (reason,minute,brainids) values ("' + data + '","' +
IntToStr(brain.Minute )+'","' + brain.brainIds +'")' ;
MyQueryCheat.Execute;
MyQueryCheat.Free;
ConnAccount.Connected:= False;
ConnAccount.Free;
end
else if Data = 'FINALIZE' then begin
Finalizebrain ( brain );
// RemoveBrain( brain.brainIds ); { se lo faccio bug, c'era PASS o altri comandi in essere. il brain esegue ancora tsscript, lo faccio dopo 30 secondi }
end // lo marco per il delete successivo
else begin
// prima i client che giocano
try
for I := 0 to FormServer.Tcpserver.ClientCount -1 do begin
if FormServer.TcpServer.Client [i].CliId = brain.Score.CliId [0] then begin
NewData := 'BEGINBRAIN' + AnsiChar( StrToInt(data) ) + GetBrainStream ( brain );
FormServer.TcpServer.Client [i].SendStr ( NewData + EndofLine);
FormServer.Memo1.Lines.Add( '> BEGINBRAIN ' +IntToStr(brain.incMove) );
end
else if FormServer.TcpServer.Client [i].CliId = brain.Score.CliId [1] then begin
NewData := 'BEGINBRAIN' + AnsiChar( StrToInt(data) ) + GetBrainStream ( brain );
FormServer.TcpServer.Client [i].SendStr ( NewData + EndofLine);
FormServer.Memo1.Lines.Add( '> BEGINBRAIN ' +IntToStr(brain.incMove) );
end;
end;
// poi gli spettatori
for I := 0 to brain.lstSpectator.Count -1 do begin
(* Per ogni spettatore ricerco nei TcpClient lo stesso CliID*)
SpectatorCliId := brain.lstSpectator[i];
for ii := 0 to FormServer.Tcpserver.ClientCount -1 do begin
if FormServer.TcpServer.Client [ii].CliId = SpectatorCliId then begin
NewData := 'BEGINBRAIN' + AnsiChar( StrToInt(data) ) + GetBrainStream ( brain );
FormServer.TcpServer.Client [ii].SendStr ( NewData + EndofLine);
end;
end;
end;
except
on E: Exception do Begin
// brain.RemoveSpectator ( TcpServer.Client [ii].CliId ); { TODO -cverifica : sarà dura debuggare qui }
ConnAccount := TMyConnection.Create(nil);
ConnAccount.Server := MySqlServerAccount;
ConnAccount.Username:='root';
ConnAccount.Password:='root';
ConnAccount.Database:='realmd';
ConnAccount.Connected := True;
MyQueryCheat := TMyQuery.Create(nil);
MyQueryCheat.Connection := ConnAccount ;
MyQueryCheat.SQL.Text := ' INSERT into cheat_detected (reason) values ("' + E.ToString + ' TBrainManager.input ' + '")';
MyQueryCheat.Execute ;
MyQueryCheat.Free;
ConnAccount.Connected:= False;
ConnAccount.Free;
Exit;
end;
end;
end;
end;
function TBrainmanager.GetbrainStream ( brain: TSoccerBrain) : string;
var
CompressedStream: TZCompressionStream;
SS: TStringStream;
begin
// senza compressione
{SS := TStringStream.Create('');
SS.CopyFrom( brain.MMbraindata, 0);
NewData := SS.DataString;
SS.Free; }
// con compressione
CompressedStream := TZCompressionStream.Create(brain.MMbraindataZIP, zcDefault); // create the compression stream
CompressedStream.Write( brain.MMbraindata.Memory , brain.MMbraindata.size); // move and compress the InBuffer string -> destination stream (MyStream)
CompressedStream.Free;
SS := TStringStream.Create('');
SS.CopyFrom( brain.MMbraindataZIP, 0);
Result := SS.DataString;
SS.Free;
end;
{ brain Manager }
procedure TBrainManager.DecodeBrainIds ( brainIds: string; var MyYear, MyMonth, MyDay, MyHour, MyMin, MySec: string );
begin
// così lo creo: f o m
// BrainIDS:= 'f_' + IntToStr(myYear) + Format('%.*d',[2, myMonth]) + Format('%.*d',[2, myDay]) + '_' +
// Format('%.*d',[2, myHour]) + '.' + Format('%.*d',[2, myMin]) + '.' + Format('%.*d',[2, mySec])+ '_' +
// GuidTeam0 + '.' + GuidTeam1 ;
brainIds := RightStr(brainIds, Length(BrainIds)-2); // elimino f_ o m_
MyYear := LeftStr( brainIds, 4 );
myMonth := MidStr( brainIds, 5, 2 );
myDay := MidStr( brainIds, 7, 2 );
myHour := MidStr( brainIds, 10, 2 ); // a 9 _
myMin := MidStr( brainIds, 13, 2 ); // a 12 .
mySec := MidStr( brainIds, 16, 2 ); // a 15 .
end;
procedure TBrainManager.FinalizeBrain ( brain: TSoccerBrain);
var
i,indexTal,T,P,aGuidTeam,matches_Played,matches_Left, disqualified, injured,TotYellowCard,aRnd,newStamina,FreeSlot,n,NewMorale: Integer;
TextHistory,TextXP: string;
aPlayer: TSoccerPlayer;
tsXP, tsHistory: TStringList;
MatchesplayedTeam,Points,Season,SeasonRound,Money,Rank,WorldTeam,Protect,Nextha: array [0..1] of Integer;
myYear, myMonth, myDay, myHour, myMin, mySec, young : string;
aBasePlayer: TBasePlayer;
MatchesPlayed,MatchesLeft: Integer;
GKpresent: Boolean;
aReserveSlot: TPoint;
ValidPlayer: TValidPlayer;
ConnGame : TMyConnection;
qTeams,qPlayers, MyQueryUpdate, MyQueryArchive,qTransfers,qlast: TMyQuery;
Start: Integer;
label skip,MyStoreDone;
begin
// adesso il match è finito
// prima aggiorno i disqualified e gli injured ( tutti i giocatori delle due squadre ). anche Mathcheslayed riguarda tutti.
// Singoli players
//fine partita
WaitforSingleObject ( MutexMarket, INFINITE ); // devo bloccare il mercato
WaitForSingleObject(Mutex,INFINITE);
WaitForSingleObject(MutexLockBrain,INFINITE);
ConnGame := TMyConnection.Create(nil);
Conngame.Server := MySqlServerGame;
Conngame.Username:='root';
Conngame.Password:='root';
Conngame.Database:= brain.Gender + '_game';
Conngame.Connected := True;
qPlayers := TMyQuery.Create(nil);
MyQueryUpdate := TMyQuery.Create(nil);
qPlayers.Connection := ConnGame; // game
MyQueryUpdate.Connection := ConnGame; // game
for T := 0 to 1 do begin
qPlayers.SQL.Text := 'SELECT * from ' +brain.Gender + '_game.players WHERE team =' + IntToStr(brain.Score.TeamGuid [T] ) + ' and young =0' ;
qPlayers.Execute ;
for I := 0 to qPlayers.RecordCount -1 do begin
// nota: se un player è stato comprato sul mercato non crea problemi se non al valore di mercato
aGuidTeam := qPlayers.FieldByName('team').asinteger;
matches_Played := qPlayers.FieldByName('matches_played').asinteger; // il tempo passa per tutti. invecchiano tutti.
matches_left := qPlayers.FieldByName('matches_left').asinteger;
Inc(matches_Played);
Dec(matches_left);
//
// CASO FINE CARRIERA
//
if matches_left <= 0 then begin // fine carriera
aGuidTeam := 0; // i player con Guidteam 0 sono da gestire poi sul DB
MyQueryUpdate.SQL.text := 'UPDATE ' +brain.Gender + '_game.players SET team = 0'+ // 0 se a fine carriera
' WHERE guid = ' + qPlayers.FieldByName('guid').asstring ;
MyQueryUpdate.Execute;
// questo è il LOG
qTransfers := TMyQuery.Create(nil);
qTransfers.Connection := ConnGame; // game
qTransfers.SQL.text := 'INSERT INTO '+brain.Gender +'_game.transfers SET action="e", seller=' + IntToStr(brain.Score.TeamGuid [T]) +
' , buyer=' + IntToStr(brain.Score.TeamGuid [T]) +
' , playerguid=' + qPlayers.FieldByName('guid').asstring + ' , price=0';
qTransfers.Execute;
goto MyStoreDone;
end;
//
//
disqualified := qPlayers.FieldByName('disqualified').asinteger;
if disqualified > 0 then
Dec( disqualified );
injured := qPlayers.FieldByName('injured').asinteger;
if injured > 0 then
Dec( injured );
if qPlayers.FieldByName('disqualified').asinteger > 0 then begin // se sul db è diqualified non lo posso trovare in getsoccerALL
if (injured <= 0) then begin
NewStamina := NewStamina + REGEN_STAMINA + GetFitnessModifier (qPlayers.FieldByName('fitness').asinteger );
if NewStamina > 120 then NewStamina := 120;
end;
if Injured > 0 then
newStamina:=0;
MyQueryUpdate.SQL.text := 'UPDATE ' +brain.Gender + '_game.players SET matches_played = ' + IntTostr(matches_played) +
', matches_left = ' + IntTostr(matches_Left) +
', team = ' + IntTostr(aGuidTeam) + // 0 se a fine carriera ma non è stato calcolato sopra nem valore market
', disqualified = ' + IntTostr(disqualified) +
', Stamina = ' + IntToStr (NewStamina) +
' WHERE guid = ' + qPlayers.FieldByName('guid').asstring ;
MyQueryUpdate.Execute ;
goto MyStoreDone;
end;
NewMorale := 0;
if qPlayers.FieldByName('talentid1').AsInteger <> 1 then begin // il morale non funziona sui GK
if brain.GetSoccerPlayer3(qPlayers.FieldByName('guid').AsString ) <> nil then begin // HA GIOCATO LA PARTITA
if RndGenerate(100) <= 25 then
NewMorale := +1;
end
else begin // NON HA GIOCATO LA PARTITA
if RndGenerate(100) <= 33 then
NewMorale := -1;
end;
end;
// da qui in poi le variabili del brain possono modificare anche disqualified e injured ecc...
// gestione cartellini 2 gialli 1 rosso. slo 1 rosso. se rosso 1,2,3 turni
// dopo disqualified e injured vengono aggiornati solo da chi ha giocato in lstSoccerPlayer
// lstSoccerPlayer contiene tutti i giocatori che hanno giocato (espulsi , infortunati, sostituiti ecc..) la lstReserve non mi serve
TotYellowCard := qPlayers.FieldByName('totyellowcard').asinteger;
aPlayer := brain.GetSoccerPlayerALL ( qPlayers.FieldByName('guid').asstring ); // tutti! ... player, reserve e gameover
TotYellowCard := TotYellowCard + aPlayer.YellowCard;
if TotYellowCard >= YELLOW_DISQUALIFIED then begin
// genero 1 turno di squalifica
disqualified := 1;