game_control.pas 43.7 KB
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
{
  Free-mtrix - Free cultural selection and social behavior experiments.
  Copyright (C) 2016-2017 Carlos Rafael Fernandes Picanço, Universidade Federal do Pará.

  The present file is distributed under the terms of the GNU General Public License (GPL v3.0).

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit game_control;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Graphics, Grids
  , game_zmq_actors
  , game_experiment
  , game_actors
  , game_visual_elements
  ;

type


  { TGameControl }

  TGameControl = class(TComponent)
  private
    FID: UTF8string;
    FMustDrawDots: Boolean;
    FMustDrawDotsClear: Boolean;
    FRowBase : integer;
    FActor : TGameActor;
    FZMQActor : TZMQActor;
    FExperiment : TExperiment;
    function GetPlayerBox(AID:UTF8string) : TPlayerBox;
    function GetActorNicname(AID:UTF8string) : UTF8string;
    function GetSelectedColorF(AStringGrid : TStringGrid) : UTF8string;
    function GetSelectedRowF(AStringGrid : TStringGrid) : UTF8string;
    function MessageHas(const A_CONST : UTF8string; AMessage : TStringList; I:ShortInt=0): Boolean;
    procedure CreatePlayerBox(P:TPlayer; Me:Boolean;Admin:Boolean = False);
    procedure DeletePlayerBox(AID : string);
    procedure SetMatrixType(AStringGrid : TStringGrid; AMatrixType:TGameMatrixType;
      var ARowBase:integer; var ADrawDots, ADrawClear : Boolean);
    procedure ReceiveMessage(AMessage : TStringList);
    procedure ReceiveRequest(var ARequest : TStringList);
    procedure ReceiveReply(AReply : TStringList);
    procedure SetMustDrawDots(AValue: Boolean);
    procedure SetMustDrawDotsClear(AValue: Boolean);
    procedure SetRowBase(AValue: integer);
  private
    function AskQuestion(AQuestion:string):UTF8string;
    function ShowConsequence(AID,S:string;ForGroup:Boolean;ShowPopUp : Boolean = True) : string;
    procedure ShowPopUp(AText:string;AInterval : integer = 15000);
    procedure DisableConfirmationButton;
    procedure CleanMatrix(AEnabled : Boolean);
    procedure NextConditionSetup(S : string);
    procedure EnablePlayerMatrix(AID:UTF8string; ATurn:integer; AEnabled:Boolean);
  private
    function IsLastCondition : Boolean;
    function ShouldStartExperiment: Boolean;
    function ShouldEndCycle : Boolean;
    function ShouldEndCondition : Boolean;
    //function ShouldEndGeneration : Boolean;
    function ShouldAskQuestion : Boolean;
    procedure NextTurn(Sender: TObject);
    procedure NextCycle(Sender: TObject);
    procedure NextLineage(Sender: TObject);
    procedure NextCondition(Sender: TObject);
    procedure Interlocking(Sender: TObject);
    procedure TargetInterlocking(Sender: TObject);
    procedure Consequence(Sender: TObject);
    procedure EndExperiment(Sender: TObject);
    procedure StartExperiment;
  public
    constructor Create(AOwner : TComponent;AppPath:string);overload;
    destructor Destroy; override;
    procedure SetMatrix;
    procedure SendRequest(ARequest : UTF8string);
    procedure SendMessage(AMessage : UTF8string);
    procedure Cancel;
    procedure Start;
    procedure Pause;
    procedure Resume;
    procedure Stop;
    property Experiment : TExperiment read FExperiment write FExperiment;
    property ID : UTF8string read FID;
    property RowBase : integer read FRowBase write SetRowBase;
    property MustDrawDots: Boolean read FMustDrawDots write SetMustDrawDots;
    property MustDrawDotsClear:Boolean read FMustDrawDotsClear write SetMustDrawDotsClear;
  end;

  function GetRowColor(ARow : integer;ARowBase:integer) : TColor;

// TODO: PUT NORMAL STRING MESSAGES IN RESOURCESTRING INSTEAD

const
  K_ARRIVED  = '.Arrived';
  K_CHAT_M   = '.ChatM';
  K_CHOICE   = '.Choice';
  K_MESSAGE  = '.Message';
  K_START    = '.Start';
  K_RESUME   = '.Resume';
  K_LOGIN    = '.Login';
  K_QUESTION = '.Question';
  K_QMESSAGE = '.QMessage';
  K_MOVQUEUE = '.Queue';
  K_END      = '.EndX';
  K_NXTCND   = '.NextCond';

  //
  K_STATUS   = '.Status';
  K_LEFT     = '.Left';
  K_WAIT     = '.Wait';
  K_FULLROOM = '.Full';
  K_PLAYING  = '.Playing';
  K_REFUSED  = '.Refused';

implementation

uses ButtonPanel,Controls,ExtCtrls,StdCtrls,LazUTF8, Forms, Dialogs, strutils
     , form_matrixgame
     , presentation_classes
     , form_chooseactor
     , game_resources
     , game_actors_helpers
     , string_methods
     ;

const
  GA_ADMIN = 'Admin';
  GA_PLAYER = 'Player';
  //GA_WATCHER = 'Watcher';

function GetRowColor(ARow: integer; ARowBase:integer): TColor;
var LRow : integer;
begin
  Result := 0;
  if ARowBase = 1 then
    LRow := aRow -1
  else LRow := aRow;

  case LRow of
    0,5 :Result := ccYellow;
    1,6 :Result := ccGreen;
    2,7 :Result := ccRed;
    3,8 :Result := ccBlue;
    4,9 :Result := ccMagenta;
  end;
end;

{ TGameControl }

function TGameControl.ShouldStartExperiment: Boolean;
begin
  Result := FExperiment.PlayersCount = FExperiment.Condition[FExperiment.CurrentCondition].Turn.Value;
end;

function TGameControl.ShouldEndCycle: Boolean; //CAUTION: MUST BE CALLED BEFORE EXPERIMENT.NEXTCYCLE
begin
  Result := FExperiment.Condition[FExperiment.CurrentCondition].Turn.Count = FExperiment.Condition[FExperiment.CurrentCondition].Turn.Value-1;
end;

function TGameControl.IsLastCondition: Boolean;
begin
  Result := FExperiment.CurrentCondition = FExperiment.ConditionsCount-1;
end;

function TGameControl.ShouldEndCondition: Boolean;
begin
  Result := FExperiment.ShouldEndCondition;
end;

//function TGameControl.ShouldEndGeneration: Boolean;
//begin
//  Result := FExperiment.Condition[FExperiment.CurrentCondition].Cycles.Count = FExperiment.Condition[FExperiment.CurrentCondition].Cycles.Value-1;
//end;

function TGameControl.ShouldAskQuestion: Boolean;
begin
  Result := Assigned(FExperiment.Condition[FExperiment.CurrentCondition].Prompt) and FExperiment.TargetIntelockingFired;
end;

procedure TGameControl.EndExperiment(Sender: TObject);
begin
  ShowPopUp('O Experimento terminou.');
end;

procedure TGameControl.NextTurn(Sender: TObject);
begin
  // update admin view
  FormMatrixGame.LabelExpCountTurn.Caption:=IntToStr(FExperiment.Condition[FExperiment.CurrentCondition].Turn.Count+1);

end;

procedure TGameControl.NextCycle(Sender: TObject);
begin
  FormMatrixGame.LabelExpCountCycle.Caption:= IntToStr(FExperiment.Cycles+1);
  {$IFDEF DEBUG}
  WriteLn('cycle:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
  {$ENDIF}
end;

procedure TGameControl.NextLineage(Sender: TObject);
begin
  // pause, kick older player, wait for new player, resume
  FormMatrixGame.LabelExpCountGeneration.Caption:=IntToStr(FExperiment.Condition[FExperiment.CurrentCondition].Cycles.Generation+1);
end;

procedure TGameControl.NextCondition(Sender: TObject);
begin
  FormMatrixGame.LabelExpCountCondition.Caption:= FExperiment.Condition[FExperiment.CurrentCondition].ConditionName;

  // append OnStart data
  NextConditionSetup(FExperiment.CurrentConditionAsString);
end;

procedure TGameControl.Interlocking(Sender: TObject);
var i : integer;
begin
  i := StrToInt(FormMatrixGame.LabelExpCountInterlocks.Caption);
  FormMatrixGame.LabelExpCountInterlocks.Caption:= IntToStr(i+1);
end;

procedure TGameControl.TargetInterlocking(Sender: TObject);
var i : integer;
begin
  i := StrToInt(FormMatrixGame.LabelExpCountTInterlocks.Caption);
  FormMatrixGame.LabelExpCounTtInterlocks.Caption:= IntToStr(i+1);
end;

procedure TGameControl.Consequence(Sender: TObject);
begin
{$IFDEF DEBUG}
  if Sender is TConsequence then
    FormMatrixGame.ChatMemoRecv.Lines.Append(('['+TConsequence(Sender).PlayerNicname+']: ')+TConsequence(Sender).AsString(''));
{$ENDIF}
end;

procedure TGameControl.StartExperiment;
begin
  // all players arrived, lets begin
  FExperiment.Play;

  // wait some time, we just sent a message earlier
  Sleep(5);

  // gui setup
  // enable matrix grid for the first player
  FZMQActor.SendMessage([K_START]);

  // points
  //FormMatrixGame.GBIndividualAB.Visible := FExperiment.ABPoints;
  //FormMatrixGame.GBIndividual.Visible:= not FormMatrixGame.GBIndividualAB.Visible;

  // turns
  FormMatrixGame.LabelExpCountTurn.Caption:=IntToStr(FExperiment.Condition[FExperiment.CurrentCondition].Turn.Count+1);

  // cycle
  FormMatrixGame.LabelExpCountCycle.Caption := IntToStr(FExperiment.Cycles+1);

  // generation
  FormMatrixGame.LabelExpCountGeneration.Caption:=IntToStr(FExperiment.Condition[FExperiment.CurrentCondition].Cycles.Generation+1);

  // condition
  FormMatrixGame.LabelExpCountCondition.Caption:= FExperiment.Condition[FExperiment.CurrentCondition].ConditionName;

  // interlocks
  FormMatrixGame.LabelExpCountInterlocks.Caption:= '0';

  // target interlocks
  FormMatrixGame.LabelExpCountTInterlocks.Caption:= '0';

  // wait for players
end;

procedure TGameControl.Start;
begin
  // check if experiment is running
end;

procedure TGameControl.Pause;
begin
  //FExperiment.State:=xsPaused;
  // save to file

  // inform players
end;

procedure TGameControl.Resume;
begin
  //FExperiment.State:=xsRunning;
  // load from file

  // wait for players
end;

procedure TGameControl.Stop;
begin
  // cleaning
  FExperiment.Clean;
end;

function TGameControl.GetPlayerBox(AID: UTF8string): TPlayerBox;
var i : integer;
begin
  Result := nil;
  for i := 0 to FormMatrixGame.GBLastChoice.ComponentCount-1 do
    if TPlayerBox(FormMatrixGame.GBLastChoice.Components[i]).ID = AID then
      begin
        Result := TPlayerBox(FormMatrixGame.GBLastChoice.Components[i]);
        Break;
      end;
end;

function TGameControl.GetActorNicname(AID: UTF8string): UTF8string;
begin
  Result := '';
  case FActor of
    gaPlayer: begin
      Result := 'UNKNOWN';
      if FExperiment.Player[AID].ID <> '' then
        Result := FExperiment.Player[AID].Nicname;
    end;

    gaAdmin: Result := FExperiment.Researcher;
  end;
end;

function TGameControl.MessageHas(const A_CONST: UTF8string; AMessage: TStringList;
  I: ShortInt): Boolean;
begin
  Result:= False;
  if not Assigned(AMessage) then Exit;
  Result := Pos(A_CONST,AMessage[I])>0;
end;

procedure TGameControl.CreatePlayerBox(P: TPlayer; Me: Boolean; Admin: Boolean);
var i1 : integer;
begin
  with TPlayerBox.Create(FormMatrixGame.GBLastChoice,P.ID,Admin) do
    begin
      if Me then
        Caption := P.Nicname+SysToUtf8(' (Você)' )
      else
        Caption := P.Nicname;
      i1 := Integer(P.Choice.Row);
      if i1 > 0 then
        LabelLastRowCount.Caption := Format('%-*.*d', [1,2,i1])
      else
        LabelLastRowCount.Caption := 'NA';
      PanelLastColor.Color := GetColorFromCode(P.Choice.Color);
      Enabled := True;
      Parent := FormMatrixGame.GBLastChoice;
    end;
end;

procedure TGameControl.DeletePlayerBox(AID: string);
var i : integer;
begin
  for i := 0 to FormMatrixGame.GBLastChoice.ComponentCount -1 do
    if FormMatrixGame.GBLastChoice.Components[i] is TPlayerBox then
      if TPlayerBox(FormMatrixGame.GBLastChoice.Components[i]).ID = AID then
        begin
          TPlayerBox(FormMatrixGame.GBLastChoice.Components[i]).Free;
          Break;
        end;
end;

procedure TGameControl.SetMatrixType(AStringGrid: TStringGrid;
  AMatrixType: TGameMatrixType; var ARowBase: integer; var ADrawDots,
  ADrawClear: Boolean);

  procedure WriteGridFixedNames(ASGrid: TStringGrid; WriteCols: boolean);
  var
    i: integer;
  begin
    with ASGrid do
      for i := 0 to 9 do
      begin
        Cells[0, i + ARowBase] := IntToStr(i + 1);
        if WriteCols then
          Cells[i + 1, 0] := chr(65 + i);
      end;
  end;

begin
  AStringGrid.Clean;
  if gmRows in AMatrixType then
    begin
      ARowBase := 0;
      AStringGrid.FixedRows := 0;
      AStringGrid.RowCount := 10;
      AStringGrid.Height:=305;
      AStringGrid.Options := [goFixedHorzLine, goHorzLine];
      WriteGridFixedNames(AStringGrid, False);
    end;

  if gmColumns in AMatrixType then
    begin
      ARowBase := 1;
      AStringGrid.Clean;
      AStringGrid.FixedRows := 1;
      AStringGrid.RowCount := 11;
      AStringGrid.Height:=335;
      AStringGrid.Options := [goFixedHorzLine, goHorzLine, goVertLine];
      WriteGridFixedNames(AStringGrid, True);
    end;

  ADrawDots := gmDots in AMatrixType;
  ADrawClear:= gmClearDots in AMatrixType;
end;

function TGameControl.GetSelectedColorF(AStringGrid: TStringGrid): UTF8string;
begin
  Result := GetColorString(GetRowColor(AStringGrid.Selection.Top,RowBase));
end;

function TGameControl.GetSelectedRowF(AStringGrid: TStringGrid): UTF8string;
var i : integer;
begin
  i := AStringGrid.Selection.Top;
  if RowBase = 0 then
    Inc(i);
  Result := Format('%-*.*d', [1,2,i]);
end;

procedure TGameControl.SetMustDrawDots(AValue: Boolean);
begin
  if FMustDrawDots=AValue then Exit;
  FMustDrawDots:=AValue;
end;

procedure TGameControl.SetMustDrawDotsClear(AValue: Boolean);
begin
  if FMustDrawDotsClear=AValue then Exit;
  FMustDrawDotsClear:=AValue;
end;

procedure TGameControl.SetRowBase(AValue: integer);
begin
  if FRowBase=AValue then Exit;
  case AValue of
    0 : FExperiment.MatrixType := [gmRows];
    1 : FExperiment.MatrixType := [gmRows,gmColumns];
  end;
  FRowBase:=AValue;
end;

// many thanks to howardpc for this:
// http://forum.lazarus.freepascal.org/index.php/topic,34559.msg227585.html#msg227585
function TGameControl.AskQuestion(AQuestion: string): UTF8string;
var
  Prompt: TForm;
  ButtonPanel: TButtonPanel;
  LabelQuestion: TLabel;
  mr: TModalResult;
begin
  Prompt:=TForm.CreateNew(nil);
  try
    with Prompt do
      begin
        BorderStyle:=bsNone;
        Position:=poScreenCenter;
        ButtonPanel:=TButtonPanel.Create(Prompt);
        with ButtonPanel do
          begin
            ButtonOrder:=boCloseOKCancel;
            OKButton.Caption:='Sim';
            CancelButton.Caption:='Não';
            ShowButtons:=[pbOK, pbCancel];
            ShowBevel:=True;
            ShowGlyphs:=[];
            Parent:=Prompt;
          end;

        LabelQuestion:=TLabel.Create(Prompt);
        with LabelQuestion do
          begin
            Align:=alClient;
            Caption:= AQuestion;
            Alignment := taCenter;
            Anchors := [akLeft,akRight];
            Layout := tlCenter;
            WordWrap := True;
            Parent:=Prompt;
          end;

        mr:=ShowModal;
        if mr = mrOK then
          Result := 'S'
        else
          Result := 'N';
      end;
  finally
    Prompt.Free;
  end;
end;

procedure TGameControl.ShowPopUp(AText: string; AInterval: integer);
var PopUpPos : TPoint;
begin
  PopUpPos.X := (FormMatrixGame.StringGridMatrix.Width div 2) - (FormMatrixGame.PopupNotifier.vNotifierForm.Width div 2);
  PopUpPos.Y := (FormMatrixGame.StringGridMatrix.Height div 2) - (FormMatrixGame.PopupNotifier.vNotifierForm.Height div 2);
  PopUpPos := FormMatrixGame.ClientToScreen(PopUpPos);
  FormMatrixGame.PopupNotifier.Title:='';
  FormMatrixGame.PopupNotifier.Text:=AText;
  FormMatrixGame.PopupNotifier.ShowAtPos(PopUpPos.X,PopUpPos.Y);
  FormMatrixGame.Timer.OnTimer:=@FormMatrixGame.TimerTimer;
  FormMatrixGame.Timer.Interval:=AInterval;
  FormMatrixGame.Timer.Enabled:=True;
end;

function TGameControl.ShowConsequence(AID, S: string;
  ForGroup: Boolean; ShowPopUp: Boolean):string;
var
  LConsequence : TConsequence;
begin
  Result := '';
  LConsequence := TConsequence.Create(nil,S);
  Result := LConsequence.GenerateMessage(ForGroup);
  if ShowPopUp then
    LConsequence.PresentMessage(FormMatrixGame.GBIndividualAB);
  case FActor of
    gaPlayer:
      if ForGroup then
        LConsequence.PresentPoints(FormMatrixGame.LabelIndACount,FormMatrixGame.LabelIndBCount,
          FormMatrixGame.LabelIndCount,FormMatrixGame.LabelGroupCount)
      else
        if Self.ID = AID then
          LConsequence.PresentPoints(FormMatrixGame.LabelIndACount,FormMatrixGame.LabelIndBCount,
            FormMatrixGame.LabelIndCount,FormMatrixGame.LabelGroupCount);

    gaAdmin:
      begin
        {$IFDEF DEBUG}
        WriteLn(S);
        {$ENDIF}
        // player box is ignored for group points
        // LabelGroupCount is ignored for player points
        LConsequence.PresentPoints(GetPlayerBox(AID), FormMatrixGame.LabelGroupCount);
      end;
  end;
end;

procedure TGameControl.DisableConfirmationButton;
begin
  FormMatrixGame.StringGridMatrix.Enabled:= False;
  FormMatrixGame.btnConfirmRow.Enabled:=False;
  FormMatrixGame.btnConfirmRow.Caption:='OK';
end;

procedure TGameControl.CleanMatrix(AEnabled : Boolean);
begin
  FormMatrixGame.StringGridMatrix.Enabled:=AEnabled;
  FormMatrixGame.StringGridMatrix.Options := FormMatrixGame.StringGridMatrix.Options-[goRowSelect];
  FormMatrixGame.btnConfirmRow.Enabled:=True;
  FormMatrixGame.btnConfirmRow.Caption:='Confirmar';
  FormMatrixGame.btnConfirmRow.Visible := False;
end;

procedure TGameControl.NextConditionSetup(S: string);
var
  A, B, G : integer;
  P : TPlayer;
  PB : TPlayerBox;
begin
  if FExperiment.ABPoints then
    begin
      A := StrToInt(ExtractDelimited(1,S,['|']));
      B := StrToInt(ExtractDelimited(2,S,['|']));
      G := StrToInt(ExtractDelimited(3,S,['|']));

      G += StrToInt(FormMatrixGame.LabelGroupCount.Caption);
      FormMatrixGame.LabelGroupCount.Caption := IntToStr(G);
      case FActor of
        gaPlayer:
          begin
            A += StrToInt(FormMatrixGame.LabelIndACount.Caption);
            B += StrToInt(FormMatrixGame.LabelIndBCount.Caption);

            FormMatrixGame.LabelIndACount.Caption := IntToStr(A);
            FormMatrixGame.LabelIndBCount.Caption := IntToStr(B);
          end;
       gaAdmin:
         for P in FExperiment.Players do
          begin
            PB := GetPlayerBox(P.ID);
            A += StrToInt(PB.LabelPointsCount.Caption) + B;
            PB.LabelPointsCount.Caption := IntToStr(A);
          end;
      end;
    end
  else
    begin
      A := StrToInt(ExtractDelimited(1,S,['|']));
      G := StrToInt(ExtractDelimited(2,S,['|']));
      G += StrToInt(FormMatrixGame.LabelGroupCount.Caption);
      FormMatrixGame.LabelGroupCount.Caption := IntToStr(G);
      case FActor of
        gaPlayer:
          begin
            A += StrToInt(FormMatrixGame.LabelIndACount.Caption);
            FormMatrixGame.LabelIndCount.Caption := IntToStr(A);
          end;

       gaAdmin:
         for P in FExperiment.Players do
          begin
            PB := GetPlayerBox(P.ID);
            A += StrToInt(PB.LabelPointsCount.Caption);
            PB.LabelPointsCount.Caption := IntToStr(A);
          end;
       end;
    end;
end;

procedure TGameControl.EnablePlayerMatrix(AID:UTF8string; ATurn:integer; AEnabled:Boolean);
begin
  if FExperiment.PlayerFromID[AID].Turn = ATurn then
    begin
      CleanMatrix(AEnabled);

      if AEnabled then
        ShowPopUp('É sua vez! Clique sobre uma linha da matrix e confirme sua escolha.');
    end;
end;

constructor TGameControl.Create(AOwner: TComponent;AppPath:string);
begin
  inherited Create(AOwner);
  FZMQActor := TZMQActor(AOwner);
  FID := FZMQActor.ID;
  FZMQActor.OnMessageReceived:=@ReceiveMessage;
  FZMQActor.OnRequestReceived:=@ReceiveRequest;
  FZMQActor.OnReplyReceived:=@ReceiveReply;
  FZMQActor.Start;

  if FZMQActor.ClassType = TZMQAdmin then
    FActor := gaAdmin;
  if FZMQActor.ClassType = TZMQPlayer then
    FActor := gaPlayer;
  if FZMQActor.ClassType = TZMQWatcher then
    FActor := gaWatcher;

  RowBase:= 0;
  MustDrawDots:=False;
  MustDrawDotsClear:=False;
  case FActor of
    gaAdmin:FExperiment := TExperiment.Create(FZMQActor.Owner,AppPath);
    gaPlayer:FExperiment := TExperiment.Create(FZMQActor.Owner);
    gaWatcher:FExperiment := TExperiment.Create(FZMQActor.Owner);
  end;
  FExperiment.OnEndTurn := @NextTurn;
  FExperiment.OnEndCycle := @NextCycle;
  FExperiment.OnEndCondition:= @NextCondition;
  FExperiment.OnEndGeneration:=@NextLineage;
  FExperiment.OnEndExperiment:= @EndExperiment;
  FExperiment.OnInterlocking:=@Interlocking;
  FExperiment.OnConsequence:=@Consequence;
  FExperiment.OnTargetInterlocking:=@TargetInterlocking;

  SendRequest(K_LOGIN); // admin cannot send requests
end;

destructor TGameControl.Destroy;
begin
  inherited Destroy;
end;

procedure TGameControl.SetMatrix;
begin
  SetMatrixType(FormMatrixGame.StringGridMatrix, FExperiment.MatrixType,FRowBase,FMustDrawDots,FMustDrawDotsClear);
end;

procedure TGameControl.SendRequest(ARequest: UTF8string);
var
  M : array of UTF8string;

  procedure SetM(A : array of UTF8string);
  var i : integer;
  begin
    SetLength(M,Length(A));
    for i := 0 to Length(A) -1 do
      M[i] := A[i];
  end;
begin
  SetLength(M,0);
  case ARequest of
    K_LOGIN :SetM([
        FZMQActor.ID
        , ' '
        , ARequest
      ]);

    K_CHOICE  : SetM([
        FZMQActor.ID
        , ' '
        , ARequest
        , GetSelectedRowF(FormMatrixGame.StringGridMatrix)
        , GetSelectedColorF(FormMatrixGame.StringGridMatrix)
      ]);

  end;
  case FActor of
    gaAdmin: begin
      //M[2] := GA_ADMIN+M[2];// for now cannot Requests
    end;
    gaPlayer:begin
      M[2] := GA_PLAYER+M[2];
    end;
    //gaWatcher:begin
    //  M[0] := GA_WATCHER+M[0];
  end;
  FZMQActor.Request(M);
end;

// called from outside
procedure TGameControl.SendMessage(AMessage: UTF8string);
var
  M : array of UTF8string;

  procedure SetM(A : array of UTF8string);
  var i : integer;
  begin
    SetLength(M,Length(A));
    for i := 0 to Length(A) -1 do
      M[i] := A[i];
  end;
begin
  case AMessage of

    K_CHAT_M  : begin
      //if (FActor = gaAdmin) and (not FExperiment.ResearcherCanChat) then Exit;
      SetM([
        AMessage
        , GetActorNicname(FZMQActor.ID)
        , FormMatrixGame.ChatMemoSend.Lines.Text
      ]);
    end;
    K_CHOICE  : SetM([
        AMessage
        , FZMQActor.ID
        , GetSelectedRowF(FormMatrixGame.StringGridMatrix)
        , GetSelectedColorF(FormMatrixGame.StringGridMatrix)
      ]);
  end;

  case FActor of
    gaAdmin: begin
      M[0] := GA_ADMIN+M[0];
    end;
    gaPlayer:begin
      M[0] := GA_PLAYER+M[0];
    end;
    //gaWatcher:begin
    //  M[0] := GA_WATCHER+M[0];
  end;
  FZMQActor.SendMessage(M);
end;

procedure TGameControl.Cancel;
begin
  FormMatrixGame.StringGridMatrix.Clean;
  FormMatrixGame.StringGridMatrix.Options := [];
  FZMQActor.SendMessage(K_END);
end;

// Here FActor is garanted to be a TZMQPlayer
procedure TGameControl.ReceiveMessage(AMessage: TStringList);
  function MHas(const C : UTF8string) : Boolean;
  begin
    Result := MessageHas(C,AMessage);
  end;

  procedure ReceiveActor;
  var P : TPlayer;
  begin
    case FActor of
      gaPlayer:
        begin
          P := FExperiment.PlayerFromString[AMessage[1]];
          FExperiment.AppendPlayer(P);
          CreatePlayerBox(P, Self.ID = P.ID)
        end;
    end;
  end;

  procedure ShowQuestion;
  begin
    case FActor of
      gaPlayer:FZMQActor.Request([
        FZMQActor.ID
        , ' '
        , GA_PLAYER+K_QUESTION
        , AskQuestion(AMessage[1])
        , AMessage[2] // generation
        , AMessage[3] // conditions
      ]);
    end;

  end;

  procedure ReceiveChoice;
  var
    P : TPlayer;
  begin
    P := FExperiment.PlayerFromID[AMessage[1]];
    // add last responses to player box
    with GetPlayerBox(P.ID) do
      begin
        LabelLastRowCount.Caption := AMessage[2];
        PanelLastColor.Color := GetColorFromString(AMessage[3]);
        PanelLastColor.Caption:='';
      end;

    case FActor of
      gaPlayer:begin

       // last turn// end cycle
       if P.Turn = FExperiment.PlayersCount-1  then
        begin
          // update next turn
          if Self.ID = P.ID then
           begin
             P.Turn := StrToInt(AMessage[4]);
             FExperiment.Player[Self.ID] := P;
           end;

          CleanMatrix(False);


          // no wait turns
          // if should continue then
          //if StrToBool(AMessage[6]) then
          //EnablePlayerMatrix(Self.ID,0, True)


          // wait for server
          Exit;
        end;

        // else
        if Self.ID = P.ID then
          begin
            // update confirmation button
            DisableConfirmationButton;

            // update next turn
            P.Turn := StrToInt(AMessage[4]);
            FExperiment.Player[Self.ID] := P;
          end
        else
          EnablePlayerMatrix(Self.ID,P.Turn+1, True);
      end;
    end;
  end;

  procedure NotifyPlayers;
  begin
    case FActor of
      gaPlayer:
          if FExperiment.PlayerFromID[Self.ID].Turn = 0 then
              EnablePlayerMatrix(Self.ID, 0, True)
          else
              ShowPopUp('Começou! Aguarde sua vez.');

    end;
  end;

  procedure ReceiveChat;
  var
    ALn: string;
  begin
    ALn := '['+AMessage[1]+']: '+AMessage[2];
    FormMatrixGame.ChatMemoRecv.Lines.Append(ALn);
    if FActor = gaAdmin then
      FExperiment.WriteChatLn(ALn);
  end;

  procedure MovePlayerQueue;
  var
    P : TPlayer;
  begin
    P := FExperiment.PlayerFromString[AMessage[1]]; // new
    CreatePlayerBox(P,Self.ID = P.ID, FActor=gaAdmin);
    if FActor=gaPlayer then
      begin
        FExperiment.Player[FExperiment.PlayerIndexFromID[AMessage[2]]] := P;
        EnablePlayerMatrix(Self.ID,0, True);
      end;
  end;

  procedure SayGoodBye(AID:string);
  var Pts : string;
  begin
    DeletePlayerBox(AID); // old player
    case FActor of
      gaPlayer:begin
        if Self.ID = AID then
          begin
            if FExperiment.ABPoints then
              begin
                Pts := IntToStr(StrToInt(FormMatrixGame.LabelIndACount.Caption)+StrToInt(FormMatrixGame.LabelIndBCount.Caption));
                FormMatrixGame.LabelIndACount.Caption := '0';
                FormMatrixGame.LabelIndBCount.Caption := '0';
              end
            else
              begin
                Pts := FormMatrixGame.LabelIndCount.Caption;
                FormMatrixGame.LabelIndCount.Caption := '0';
              end;

            FormMatrixGame.Visible := False;
            FormChooseActor := TFormChooseActor.Create(nil);
            FormChooseActor.Style := K_LEFT;
            FormChooseActor.ShowPoints(
            'A tarefa terminou, obrigado por sua participação! Você produziu ' +
            Pts + ' pontos e ' +
            FormMatrixGame.LabelGroupCount.Caption + ' itens escolares serão doados!');

            if FormChooseActor.ShowModal = 1 then
              begin
                FZMQActor.Request([AID,' ',K_RESUME]);
                FormMatrixGame.Visible := True;
              end
            else;
            FormChooseActor.Free;
          end
        else
          ShowPopUp(FExperiment.PlayerFromID[AID].Nicname+ ' saiu. Por favor, aguarde a chegada de alguém para ocupar o lugar.');
      end;
    end;
  end;

  procedure EndExperimentMessage;
  var Pts : string;
  begin
    case FActor of
      gaPlayer:
        begin
          CleanMatrix(False);
          FormChooseActor := TFormChooseActor.Create(FormMatrixGame);
          FormChooseActor.Style := K_END;

          if FExperiment.ABPoints then
            Pts := IntToStr(StrToInt(FormMatrixGame.LabelIndACount.Caption)+StrToInt(FormMatrixGame.LabelIndBCount.Caption))
          else
            Pts := FormMatrixGame.LabelIndCount.Caption;

          FormChooseActor.ShowPoints(
          'A tarefa terminou, obrigado por sua participação! Você produziu ' +
          Pts + ' pontos e ' +
          FormMatrixGame.LabelGroupCount.Caption + 'itens escolares serão doados! Parabéns!');
          FormChooseActor.ShowModal;
          FormChooseActor.Free;
          FormMatrixGame.Close;
        end;
      gaAdmin:Stop;
    end;
  end;

  procedure ResumeNextTurn;
  begin
    if AMessage[2] <> #27 then
      begin
        case FActor of
          gaPlayer:
            begin
              if AMessage[1] <> #32 then
                SayGoodBye(AMessage[1])
              else
                EnablePlayerMatrix(Self.ID,0, True);
            end;

          gaAdmin:
            begin
              if AMessage[1] <> #32 then
                begin
                  DeletePlayerBox(AMessage[1]); // old player
                  ShowPopUp(
                          'O participante '+
                          FExperiment.PlayerFromID[AMessage[1]].Nicname+
                          ' saiu. Aguardando a entrada do próximo participante.'
                        );
                end;
            end;

        end;
        if AMessage[2] <> #32 then
          NextConditionSetup(AMessage[2]);
      end
    else EndExperimentMessage;
  end;

  procedure QuestionMessages;
  var
    i : integer;
    MID : string;
    LQConsequence : string;
  begin
    if AMessage[2] <> #27 then
      begin
        if AMessage.Count > 1 then
          begin
            // present only one popup with all messages
            LQConsequence := '';
            for i := 3 to AMessage.Count -1 do
              begin
                MID := ExtractDelimited(1,AMessage[i],['+']);
                LQConsequence += ShowConsequence(MID, ExtractDelimited(2,AMessage[i],['+']),MID = 'M',False)+' ';

                {$IFDEF DEBUG}
                WriteLn('A Prompt consequence should have shown.');
                {$ENDIF}
              end;

            if LQConsequence <> '' then
               ShowPopUp(LQConsequence);
          end;
        ResumeNextTurn;
        if AMessage[2] <> #32 then
          NextConditionSetup(AMessage[2]);
      end
    else EndExperimentMessage;
  end;

begin
  if MHas(K_ARRIVED) then ReceiveActor;
  if MHas(K_CHAT_M)  then ReceiveChat;
  if MHas(K_CHOICE)  then ReceiveChoice;
  if MHas(K_MESSAGE) then ShowConsequence(AMessage[1],AMessage[2],StrToBool(AMessage[3]));
  if MHas(K_START) then NotifyPlayers;
  if MHas(K_QUESTION) then ShowQuestion;
  if MHas(K_MOVQUEUE) then MovePlayerQueue;
  if MHas(K_QMESSAGE) then QuestionMessages;
  if MHas(K_RESUME) then ResumeNextTurn;
  if MHas(K_NXTCND) then NextConditionSetup(AMessage[1]);
  if MHAs(K_END) then EndExperimentMessage;
end;

// Here FActor is garanted to be a TZMQAdmin
procedure TGameControl.ReceiveRequest(var ARequest: TStringList);
  function MHas(const C : UTF8string) : Boolean;
  begin
    Result := MessageHas(C,ARequest, 2);
  end;

  procedure ReplyLoginRequest;
  var i : integer;
      P : TPlayer;
      TS,
      PS : string;
  begin
    if not FExperiment.PlayerIsPlaying[ARequest[0]] then
      begin
        if FExperiment.PlayersCount < FExperiment.Condition[FExperiment.CurrentCondition].Turn.Value then
          begin
            // ok, let player login
            P.ID := ARequest[0];

            // check if we already know this player
            i := FExperiment.PlayerIndexFromID[P.ID];
            if i > -1 then
              begin
                // then load p data
                P := FExperiment.Player[i]
              end
            else
              begin
                // if not then generate and save p data
                i := FExperiment.AppendPlayer;
                if FExperiment.GenPlayersAsNeeded then
                  P.Nicname := GenResourceName(i)
                else
                  P.Nicname := InputBox
                    (
                      'Um participante entrou no experimento.',
                      'Qual o apelido do novo participante?',
                      GenResourceName(i)
                    );
                P.Points.A:=0;
                P.Points.B:=0;
                P.Status:=gpsPlaying;
                P.Choice.Color:=gcNone;
                P.Choice.Row:=grNone;
                // first turn always by entrance order
                P.Turn := i;
                FExperiment.Player[i] := P;
              end;

            // create/config playerbox
            CreatePlayerBox(P,False,True);

            // Request is now a reply with the following standard:
            // [Requester.ID 0, ' ' 1, ReplyTag 2, PlayerData 3, PlayersPlaying 4 .. n, ChatData Last]
            ARequest[2] := GA_ADMIN+ARequest[2]+K_ARRIVED;

            // player
            PS := FExperiment.PlayerAsString[P];
            //ARequest.Append(PS);

            // append current players playing
            if FExperiment.PlayersCount > 0 then
              for i:=0 to FExperiment.PlayersCount -1 do
                if FExperiment.Player[i].ID <> P.ID then
                  begin
                    TS := FExperiment.PlayerAsString[FEXperiment.Player[i]];
                    ARequest.Append(TS);  // FROM 3 to COUNT-5
                  end;
            // appen matrix type
            ARequest.Append(FExperiment.MatrixTypeAsString); // COUNT-4

            // append chat data
            if FExperiment.ShowChat then
              begin
                if FExperiment.SendChatHistoryForNewPlayers then
                  ARequest.Append(FormMatrixGame.ChatMemoRecv.Lines.Text) // COUNT-3
                else
                  ARequest.Append('[CHAT]'); // must append something to keep the message envelop with standard size
              end
            else
              ARequest.Append('[NOCHAT]'); // must append something to keep the message envelop with standard size

            // append global configs.
            ARequest.Append(BoolToStr(FExperiment.ABPoints)); // COUNT-2

            // append condition global data
            ARequest.Append(FExperiment.CurrentConditionAsString);

            // inform all players about the new player, including itself
            FZMQActor.SendMessage([K_ARRIVED,PS]);

            // start Experiment
            if ShouldStartExperiment then
              StartExperiment;

          end
        else
          begin
            ARequest[2] := GA_ADMIN+ARequest[2]+K_REFUSED+K_FULLROOM;
          end;
      end
    else
      begin
        ARequest[2] := GA_ADMIN+ARequest[2]+K_REFUSED+K_PLAYING;
      end;
  end;

  procedure ValidateChoice;
  var
    LConsequences : string;
    P : TPlayer;
    S : string;
    LEndCondition,
    LEndCycle : Boolean;
    LEndGeneration: string;
  begin
    LConsequences := '';
    {$IFDEF DEBUG}
    WriteLn('Count:',FExperiment.Condition[FExperiment.CurrentCondition].Turn.Count, '<', FExperiment.Condition[FExperiment.CurrentCondition].Turn.Value);
    {$ENDIF}
    P := FExperiment.PlayerFromID[ARequest[0]];
    P.Choice.Row:= GetRowFromString(ARequest[3]); // row
    P.Choice.Color:= GetGameColorFromString(ARequest[4]); // color
    ARequest[2] := K_CHOICE+K_ARRIVED;

    //individual consequences
    S := FExperiment.ConsequenceStringFromChoice[P];
    {$IFDEF DEBUG}
    WriteLn('ValidateChoice:',s);
    {$ENDIF}

    if Pos('$NICNAME',S) > 0 then
      S := ReplaceStr(S,'$NICNAME',P.Nicname);

    // "NextGeneration" and "ShouldEndCycle" methods must be called before Experiment.NextTurn
    LEndCycle := ShouldEndCycle;
    LEndGeneration := FExperiment.NextGeneration;
    if LEndCycle then
      LConsequences := FExperiment.ConsequenceStringFromChoices;

    // update turn
    P.Turn := FExperiment.NextTurn;
    FExperiment.Player[FExperiment.PlayerIndexFromID[P.ID]] := P;

    // append results
    ARequest.Append(IntToStr(P.Turn)); //5
    ARequest.Append(S);                //6
    if LEndCycle then // >7 = EndCycle
      begin
        ARequest.Append(LConsequences); //7

        if ShouldAskQuestion then  // DONE: prompt only when an odd row was selected
           ARequest.Append(FExperiment.Condition[FExperiment.CurrentCondition].Prompt.Question) //8
        else
          begin
            ARequest.Append(#32); // 8
            if Assigned(FExperiment.Condition[FExperiment.CurrentCondition].Prompt) then
              FExperiment.WriteReportRowPrompt; //TODO: FIND WHY OPTIMIZATION 3 GENERATES BUG HERE
            FExperiment.Clean;
          end;

        ARequest.Append(LEndGeneration); // 9, #32 resume, else NextGeneration = PlayerToKick AID
        LEndCondition := ShouldEndCondition;
        if IsLastCondition and LEndCondition then // 10
          // end experiment envelop item
          ARequest.Append(#27)
        else
          if LEndCondition then
            begin
              FExperiment.NextCondition;
              // end condition envelop item
              ARequest.Append(FExperiment.CurrentConditionAsString);
            end
          else
            // do nothing envelop item
            ARequest.Append(#32);
      end;
  end;

  procedure ValidateQuestionResponse;
  var
    P : TPlayer;
    M : array of UTF8string;
    i : integer;
    LPromptConsequences : TStringList;
  begin
    P := FExperiment.PlayerFromID[ARequest[0]];
    ARequest[2] := K_QUESTION+K_ARRIVED;

    // append response of each player
    FExperiment.Condition[FExperiment.CurrentCondition].Prompt.AppendResponse(P.ID,ARequest[3]);

    // return to experiment and present the prompt consequence, if any
    if FExperiment.Condition[FExperiment.CurrentCondition].Prompt.ResponsesCount = FExperiment.PlayersCount then
      begin
        // generate messages
        LPromptConsequences := FExperiment.Condition[FExperiment.CurrentCondition].Prompt.AsString;
        SetLength(M, 3+LPromptConsequences.Count);
        M[0] := K_QMESSAGE;
        M[1] := ARequest[4]; // generation envelop
        M[2] := ARequest[5]; // conditions
        if LPromptConsequences.Count > 0 then
          begin
            for i := 0 to LPromptConsequences.Count-1 do
              if Pos('$NICNAME',LPromptConsequences[i]) > 0 then
                begin
                  P := FExperiment.PlayerFromID[ExtractDelimited(1,LPromptConsequences[i],['+'])];
                  LPromptConsequences[i] := ReplaceStr(LPromptConsequences[i],'$NICNAME', P.Nicname);
                end;
            for i := 0 to LPromptConsequences.Count -1 do
              M[i+3] := LPromptConsequences[i]; // messages envelop
          end
        else;

        // send identified messages; each player takes only its own message and ignore the rest
        FZMQActor.SendMessage(M);
        FExperiment.WriteReportRowPrompt;
        FExperiment.Clean;
      end;
  end;

  procedure ReplyResume;// old player becomes a new player
  var
    P : TPlayer;
    S : string;
  begin
    P := FExperiment.PlayerFromID[ARequest[0]];
    ARequest[2] := K_RESUME+K_ARRIVED;
    if FExperiment.GenPlayersAsNeeded then
      P.Nicname := GenResourceName(-1)
    else
      P.Nicname := InputBox
        (
          'Mudança de geração',
          'Um novo participante entrou no lugar do participante mais antigo. Qual o apelido do novo participante?',
          GenResourceName(-1)
        );

    S := FExperiment.PlayerAsString[P];
    ARequest.Append(S); // 3
    FExperiment.NextGeneration := S;
  end;

begin
  if FExperiment.State = xsWaiting then
    begin
      if MHas(K_LOGIN) then ReplyLoginRequest;
    end;

  if FExperiment.State = xsRunning then
    begin
      if MHas(K_RESUME) then ReplyResume;
      if MHas(K_CHOICE) then ValidateChoice;
      if MHas(K_QUESTION) then ValidateQuestionResponse;
    end;
end;

// Here FActor is garanted to be a TZMQPlayer, replying by:
// - sending private data to player
// - sending data from early history to income players
procedure TGameControl.ReceiveReply(AReply: TStringList);
  function MHas(const C : UTF8string) : Boolean;
  begin
    Result := MessageHas(C,AReply,2);
  end;

  procedure LoginAccepted;
  var
    i: integer;
    P : TPlayer;
  begin
    if Self.ID = AReply[0] then
      begin
        for i:= 3 to AReply.Count -5 do
          begin
            P := FExperiment.PlayerFromString[AReply[i]];
            FExperiment.AppendPlayer(P);
            CreatePlayerBox(P, False);
          end;

        // set matrix type/ stringgrid
        FExperiment.MatrixTypeAsString:=AReply[AReply.Count-4];

        // enable chat
        if AReply[AReply.Count-3] = '[NOCHAT]' then
          FormMatrixGame.ChatPanel.Visible := False
        else
          begin
            FormMatrixGame.ChatPanel.Visible := True;
            FormMatrixGame.ChatMemoRecv.Lines.Clear;
            FormMatrixGame.ChatMemoRecv.Lines.Append(AReply[AReply.Count-3]);
          end;

        // set global configs
        FExperiment.ABPoints := StrToBool(AReply[AReply.Count-2]);
        FormMatrixGame.GBIndividualAB.Visible := FExperiment.ABPoints;
        FormMatrixGame.GBIndividual.Visible:= not FormMatrixGame.GBIndividualAB.Visible;

        // set condition specific configurations
        NextConditionSetup(AReply[AReply.Count-1]);

        // set fullscreen
        FormMatrixGame.SetFullscreen;
      end
    else
      begin
      {$IFDEF DEBUG}
        WriteLn(Self.ID + ' sent but' + AReply[0] +
          ' received. <<<<<<<<<<<<<<<<<<<<<<< This must never occur >>>>>>>>>>>>>>>>>>>>>>>>>>');
      {$ENDIF}
      end;
  end;

  procedure ChoiceValidated;
  var
    LConsequence : TConsequence;
    LCount,
    i : integer;
    LAnnouncer : TIntervalarAnnouncer;
    //P : TPlayer;
  begin
    if Self.ID = AReply[0] then
      begin
        //P := FExperiment.PlayerFromID[Self.ID];
        {$IFDEF DEBUG}
        WriteLn('LCount:',LCount);
        {$ENDIF}

        // inform other players about self.id choice
        FZMQActor.SendMessage([K_CHOICE,AReply[0],AReply[3],AReply[4],AReply[5]]);

        // The Announcer sends a message, waits interval time until all messages have been sent and then destroys itself.
        LAnnouncer := TIntervalarAnnouncer.Create(nil);
        LAnnouncer.OnStart := @FZMQActor.SendMessage;
        LAnnouncer.Interval := 5000;
        LCount := WordCount(AReply[6],['+']);

        // individual consequences
        if LCount > 0 then
          for i := 1 to LCount do
            begin
              LConsequence := TConsequence.Create(nil,ExtractDelimited(i,AReply[6],['+']));
              LConsequence.GenerateMessage(False);
              LAnnouncer.Append([K_MESSAGE,
                                 Self.ID,
                                 ExtractDelimited(i,AReply[6],['+']),
                                 BoolToStr(LConsequence.ShouldPublishMessage)]);
              //if LConsequence.ShouldPublishMessage then
              //  //FZMQActor.SendMessage([K_MESSAGE,Self.ID,ExtractDelimited(i,AReply[6],['+']),BoolToStr(False)])
              //  LAnnouncer.Append([K_MESSAGE,Self.ID,ExtractDelimited(i,AReply[6],['+']),BoolToStr(False)])
              //else
              //  begin
              //    LConsequence.PresentMessage(FormMatrixGame.GBIndividualAB);
              //    LConsequence.PresentPoints(FormMatrixGame.LabelIndACount,FormMatrixGame.LabelIndBCount,
              //      FormMatrixGame.LabelIndCount,FormMatrixGame.LabelGroupCount);
              //  end;
              {$IFDEF DEBUG}
              WriteLn('A consequence should have shown.');
              {$ENDIF}
            end;

        // group consequence
        if AReply.Count > 7 then
          begin
            LCount := WordCount(AReply[7],['+']);
            if LCount > 0 then
              for i := 1 to LCount do
                begin
                  LConsequence := TConsequence.Create(nil,ExtractDelimited(i,AReply[7],['+']));
                  LConsequence.GenerateMessage(True);
                  //FZMQActor.SendMessage([K_MESSAGE,'',ExtractDelimited(i,AReply[7],['+']),BoolToStr(True)]);
                  LAnnouncer.Append([K_MESSAGE,'',ExtractDelimited(i,AReply[7],['+']),BoolToStr(True)]);
                  {$IFDEF DEBUG}
                  WriteLn('A metaconsequence should have shown.');
                  {$ENDIF}
                end;

            // should ask question or just resume (going to the next turn)?
            if AReply[8] <> #32 then
              //FZMQActor.SendMessage([K_QUESTION,AReply[8],AReply[9]])
              LAnnouncer.Append([K_QUESTION,AReply[8],AReply[9],AReply[10]])
            else
              //FZMQActor.SendMessage([K_RESUME,AReply[9]]);
              LAnnouncer.Append([K_RESUME,AReply[9],AReply[10]]);

            // should end experiment or go to the next condition?
            if (AReply[10] = #27) and (AReply[8] = #32) then
              LAnnouncer.Append([K_END])
            else
              if (AReply[10] <> #32) then
                LAnnouncer.Append([K_NXTCND,AReply[10]])

          end;

        LAnnouncer.Reversed;
        LAnnouncer.Enabled := True;
      end;
  end;

  procedure ResumePlayer;
  begin
    FZMQActor.SendMessage([K_MOVQUEUE, AReply[3],AReply[0]]); //new player,old player (self.id)
  end;

begin
  if MHas(K_RESUME+K_ARRIVED) then ResumePlayer;
  if MHas(K_LOGIN+K_ARRIVED) then LoginAccepted;
  if MHas(K_CHOICE+K_ARRIVED) then ChoiceValidated;
end;



end.