Repository navigation
Expand file tree
/
Copy pathtest_multiplayer.php
More file actions
6460 lines (5588 loc) · 358 KB
/
Copy pathtest_multiplayer.php
File metadata and controls
6460 lines (5588 loc) · 358 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
<?php
declare(strict_types=1);
/**
* test_multiplayer.php
* Default / core automated test suite for DimensioneY.
* (For the extended full test suite including world3net-specific tests, see test_multiplayer_full.php)
*
* Automated tests for UI hierarchy, GameEngine, UIhtml, UIjson bot API endpoint,
* player database storage, auto-increment numeric ID, and bcrypt password authentication.
*/
require_once __DIR__ . '/autoload.php';
if (!defined('DIMX_TESTING')) {
define('DIMX_TESTING', true);
}
use Dimx\UI;
use Dimx\UIhtml;
use Dimx\UIjson;
use Dimx\UIbot;
use Dimx\GameEngine;
use Dimx\PersistenceManager;
use Dimx\Player;
$sections = [
1 => ['title' => 'Testing UI::detectClientType()...', 'keywords' => ['client', 'detect', 'json', 'format', 'headers', 'ui::detectclienttype']],
2 => ['title' => 'Testing UI::parseInput()...', 'keywords' => ['input', 'parse', 'password', 'cmd', 'param', 'world', 'ui::parseinput']],
3 => ['title' => 'Testing GameEngine initialization and world seeding...', 'keywords' => ['seed', 'engine', 'rooms', 'beach', 'bar', 'apple', 'gameengine', 'loadorseedworld']],
4 => ['title' => 'Testing Player DB Table, Auto-Increment Numeric ID & Bcrypt Passwords...', 'keywords' => ['auth', 'login', 'db', 'player', 'bcrypt', 'password', 'numeric', 'id', 'dimx_players', 'in-memory']],
5 => ['title' => 'Testing Bot Player via UIjson API...', 'keywords' => ['bot', 'uijson', 'snapshot', 'inventory', 'carrying', 'pick', 'drop', 'apple', 'save', 'exit', 'savexit']],
6 => ['title' => 'Testing multiplayer.php entrypoint with bot JSON query...', 'keywords' => ['multiplayer', 'bot', 'json', 'entrypoint', 'login_required', 'numeric_id']],
7 => ['title' => 'Testing multiplayer.php entrypoint with human HTML player...', 'keywords' => ['multiplayer', 'html', 'human', 'entrypoint', 'uihtml', 'score', 'stats']],
8 => ['title' => 'Testing login prompts and form fields...', 'keywords' => ['login', 'prompt', 'fields', 'form', 'bot', 'html', 'auth']],
9 => ['title' => 'Testing Bot Logout & Occupant Removal...', 'keywords' => ['logout', 'disconnect', 'occupants', 'bot', 'room', 'removal']],
10 => ['title' => 'Testing world2.dxw Description Parsing...', 'keywords' => ['world2', 'dxw', 'loader', 'apostrophe', 'description', 'parsing']],
11 => ['title' => 'Testing onStart Event & Chat PANEL Enforcement...', 'keywords' => ['onstart', 'event', 'panel', 'chat', 'commands', 'messages', 'setpanel']],
12 => ['title' => 'Testing UIbot vs UIjson and testBots Configuration...', 'keywords' => ['uibot', 'uijson', 'testbots', 'config', 'fallback', 'evalaction']],
13 => ['title' => 'Testing adminPasswd in config and maint.php authentication...', 'keywords' => ['admin', 'adminpasswd', 'maint', 'maintenance', 'config', 'auth', 'uihtml', 'title', 'console']],
14 => ['title' => 'Testing Event Model Roles ($OWNER, $AGENT, $TARGET, $WORLD) & Return Values...', 'keywords' => ['event', 'roles', '$owner', '$agent', '$target', '$world', 'return', 'cancel', 'action', 'owner', 'agent', 'target']],
15 => ['title' => 'Testing UIhtml Ctrls (#ctrls) Command Buttons & On-Screen Object Targeting...', 'keywords' => ['uihtml', 'ctrls', 'buttons', 'onscreen', 'targeting', 'switch', 'jquery', 'command_defs', 'clickobject', 'identifyobject']],
16 => ['title' => "Testing 'open' and 'close' Commands & actOpen / actClose on 'box' in World 2...", 'keywords' => ['open', 'close', 'box', 'actopen', 'actclose', 'world2', 'cardboard', 'actionsrunner']],
17 => ['title' => 'Testing World 2 Full Flow: Look at Closed Box, Use Switch in Bungalow, Open Box & Pick Apple...', 'keywords' => ['flow', 'box', 'switch', 'bungalow', 'open', 'pick', 'apple', 'goal', 'uibot', 'evaldescription', 'is closed', 'is open', 'containing', 'rocca', 'spiaggia']],
18 => ['title' => 'Testing Speak Instruction Behavior & Inanimate Object Fallback...', 'keywords' => ['speak', 'surfer', 'switch', 'voice', 'system', 'sound', 'sys', 'fallback', 'inanimate', 'bungalow']],
19 => ['title' => 'Testing UIhtml Smartphone Portrait / Vertical Layout (*, 35%, 15%)...', 'keywords' => ['portrait', 'vertical', 'smartphone', 'uihtml', 'layout', '35%', '15%']],
20 => ['title' => 'Testing Messages Box (Msgs / #msgs), popmsg Command & Per-Player Incoming Message Queue...', 'keywords' => ['msgs', 'popmsg', 'messages', 'queue', 'trim', '10', 'dismiss', 'x', 'incoming', 'speak', 'broadcast']],
22 => ['title' => 'Testing Character/Player Default showMode (ONSCREEN=1), UIjson vs UIbot Exposure & UIhtml Rendering...', 'keywords' => ['showmode', 'onscreen', 'offscreen', 'uijson', 'uibot', 'uihtml', 'character', 'player', 'avatar', 'people']],
24 => ['title' => 'Testing Room Description on Link Traversal (go command) & UIhtml Rendering...', 'keywords' => ['go', 'traverse', 'link', 'description', 'room', 'uihtml', 'travel to']],
47 => ['title' => 'Testing SmallBasic Debug Instruction & GameEngine::log() Writing to debug.log...', 'keywords' => ['debug', 'log', 'debug.log', 'gameengine', 'actionsrunner', 'system folder', 'smallbasic']],
48 => ['title' => 'Testing Resolution Handling & Login Form Cleanliness (no screenSizeHelper, non-portrait 640x480/800x600)...', 'keywords' => ['screensize', 'landscape', 'resolution', 'portrait', 'uihtml', 'login']],
49 => ['title' => 'Testing NewImage Function, ImagesFolder Resolution & Image Display/Assignment in SmallBasic...', 'keywords' => ['newimage', 'image', 'smallbasic', 'actionsrunner', 'display', 'imagesfolder']],
50 => ['title' => 'Testing Item Default SHOW_OFFSCREEN (0), Zoom on Click/Look & Fader Backdrop Overlay...', 'keywords' => ['zoom', 'fader', 'showmode', 'offscreen', 'focus', 'click', 'look', 'screwdriver', 'fader_box']],
51 => ['title' => 'Testing SmallBasic DropItems Instruction & Notification (Player, NPC, Container)...', 'keywords' => ['dropitems', 'actionsrunner', 'inventory', 'drop', 'slipped']],
52 => ['title' => 'Testing Put / Insert Command (2-Object OO Model, Capacity, Closed Checks, Events & UIhtml Definitions)...', 'keywords' => ['put', 'insert', 'actput', 'itemput', 'container', 'capacity', 'closed', 'uihtml', 'command_defs']],
53 => ['title' => 'Testing SmallBasic NewItem Function / Instruction & Snapshot Property Recursion Protection...', 'keywords' => ['newitem', 'htmladminsnapshot', 'snapshot', 'recursion', 'actionsrunner', 'smallbasic']],
54 => ['title' => 'Testing SmallBasic SetLen() Function, For .. To ... Next & For Each Constructs with debug.log...', 'keywords' => ['setlen', 'for', 'to', 'next', 'foreach', 'for each', 'loop', 'fourinline', 'smallbasic']],
55 => ['title' => 'Testing Function & Sub Logging (Calling FUNCTION/SUB with varspace) & Indentation (incIndent/decIndent)...', 'keywords' => ['calling function', 'calling', 'indent', 'incindent', 'decindent', 'indentlevel', 'varspace', 'nested']],
56 => ['title' => 'Testing If..Else Construct Logging (IF ..., TRUE/FALSE, nested running & IF executed)...', 'keywords' => ['if', 'else', 'endif', 'executed', 'running', 'true', 'false', 'fourinline', 'onlook']],
57 => ['title' => 'Testing Request Interaction Logging (USER, ROOM, STATUS, COMMAND, VIEW, DATE & input=...)', 'keywords' => ['user', 'room', 'status', 'command', 'view', 'date', 'interaction', 'request']],
58 => ['title' => 'Testing SmallBasic Reset Instruction & GameEngine::resetWorld()...', 'keywords' => ['reset', 'restart', 'smallbasic', 'actionsrunner', 'gameengine', 'reseeding']],
59 => ['title' => 'Testing SmallBasic Array String Representation [key1=val,key2=val,...] & fourinline.dxw line 204...', 'keywords' => ['array', 'formatarray', 'smallbasic', 'fourinline', 'speak', 'representation', 'actionsrunner']],
60 => ['title' => 'Testing WORLD Directives (NAME, VERSION, AUTHOR, SITE, GUI.LOGOSRC) & Login Form Layering...', 'keywords' => ['world', 'directives', 'author', 'site', 'version', 'logosrc', 'gui.logosrc', 'login', 'layers', 'background']],
61 => ['title' => "Testing Who's Online - The players view (multiplayer.php?view=players & format=extended)...", 'keywords' => ['view', 'players', 'view=players', 'format=extended', 'extended', 'online', 'who\'s online']],
62 => ['title' => 'Testing Player Inactivity Timeout (30s) at Tick Event & Nickname Conflict Check at Login...', 'keywords' => ['timeout', 'inactivity', 'tick', 'kill', 'lastactive', 'lastinteraction', 'nickname', 'conflict', 'login']],
63 => ['title' => 'Testing PeopleContainer Object Entry & Scene Refresh Dispatch with Deduplication...', 'keywords' => ['refresh', 'scene', 'refresh!scene', 'peoplecontainer', 'room', 'dedup', 'commands', 'entry', 'queue']],
64 => ['title' => 'Testing SmallBasic Goal Instruction & Database Recording in dimx_goals...', 'keywords' => ['goal', 'smallbasic', 'dimx_goals', 'hall of fame', 'hof', 'mode', 'actionsrunner', 'surfer']],
65 => ['title' => 'Testing Login Attempt Logging to debug.log & Stale Player Pruning Inside Main Loop at Login...', 'keywords' => ['login', 'stale', 'pruning', 'tick', 'debug.log', 'main loop', 'reconnect']],
66 => ['title' => 'Testing UIhtml Sound & Music Support Property Storage, Snapshot Inspection & Audio Rendering...', 'keywords' => ['sound', 'music', 'audiosupport', 'musicsupport', 'uihtml', 'snapshot', 'playbackground', 'session']],
67 => ['title' => 'Testing SmallBasic getItemsIn Function (Objects, Sets, Arrays, $WORLD, $AGENT & loc_relic_vault in world.dxw)...', 'keywords' => ['getitemsin', 'items', 'smallbasic', 'world.dxw', 'loc_relic_vault', 'inventory', 'actionsrunner']],
68 => ['title' => 'Testing SmallBasic SetContainsKey Function (Sets, Dictionaries, Arrays, Case-Insensitivity, Objects, & loc_relic_vault in world.dxw)...', 'keywords' => ['setcontainskey', 'smallbasic', 'set', 'contains', 'talisman', 'loc_relic_vault', 'world.dxw', 'actionsrunner']],
69 => ['title' => 'Testing SmallBasic Expression Error Handling & Custom Functions/Subs (getObjectsType, containsType in world.dxw)...', 'keywords' => ['syntax', 'error', 'function', 'sub', 'custom', 'containstype', 'getobjectstype', 'world.dxw', 'actionsrunner']],
70 => ['title' => 'Testing Character::give() Standard DimX Events (whenPicked, onReceiveItem, onLooseItem, No whenGiven/whenReceived)...', 'keywords' => ['give', 'whenpicked', 'onreceiveitem', 'onlooseitem', 'whengiven', 'whenreceived', 'itemgive', 'character']],
71 => ['title' => 'Testing SmallBasic String Functions (Asc, Chr, LCase, UCase, Left, Right, Mid, Replace, Format, InStr, InStrCount) & test_string_functions.dxw...', 'keywords' => ['asc', 'chr', 'lcase', 'ucase', 'left', 'right', 'mid', 'replace', 'format', 'instr', 'instrcount', 'string', 'test_string_functions.dxw']],
72 => ['title' => 'Testing SmallBasic Math Functions (Abs, Int, Log, Rnd, Round, Sqr) & test_math_functions.dxw...', 'keywords' => ['abs', 'int', 'log', 'rnd', 'round', 'sqr', 'math', 'test_math_functions.dxw']],
73 => ['title' => 'Testing SmallBasic Sets & Arrays Functions (Copy, NewSet, SetIndexOf, SetKey, SetKeys) & test_set_array_functions.dxw...', 'keywords' => ['copy', 'newset', 'setindexof', 'setkey', 'setkeys', 'sets', 'arrays', 'test_set_array_functions.dxw']],
74 => ['title' => 'Testing SmallBasic Dynamic World Entities (NewCharacter, NewLink, NewRoom) & test_dynamic_entities.dxw...', 'keywords' => ['newcharacter', 'newlink', 'newroom', 'character', 'link', 'room', 'dynamic', 'test_dynamic_entities.dxw']],
75 => ['title' => 'Testing SmallBasic World Objects & Inspection Queries & test_world_inspection.dxw...', 'keywords' => ['inspection', 'getcharactersin', 'getlinksfrom', 'getobject', 'getplayerproperties', 'getplayersin', 'getrooms', 'getroomsfrom', 'ischaracter', 'isplayer', 'isroom', 'maintype', 'test_world_inspection.dxw']],
76 => ['title' => 'Testing SmallBasic System, Scripting & Environment Functions & SaveSetting & test_system_env.dxw...', 'keywords' => ['system', 'scripting', 'existscript', 'gettime', 'httpfetch', 'panelhtml', 'getsetting', 'savesetting', 'gameinfo', 'test_system_env.dxw']],
77 => ['title' => 'Testing SmallBasic Kill Instruction (Items, NPCs, Players, Rooms, Default $AGENT) & test_kill.dxw...', 'keywords' => ['kill', 'die', 'removepeople', 'removeroom', 'limbo', 'test_kill.dxw']],
78 => ['title' => 'Testing SmallBasic SetAdd & SetRemove Instructions (Sets, Arrays, World Sets, Object Properties) & test_set_array_functions.dxw...', 'keywords' => ['setadd', 'setremove', 'set', 'array', 'test_set_array_functions.dxw']],
79 => ['title' => 'Testing SmallBasic AttachEvent Instruction (Attach, Detach, Player Restrictions, Items/NPCs) & test_attachevent.dxw...', 'keywords' => ['attachevent', 'event', 'detach', 'vampire', 'test_attachevent.dxw']],
80 => ['title' => 'Testing SmallBasic NOT(), IsItem(), and Urlencode() Functions & test_not_isitem_urlencode.dxw...', 'keywords' => ['not', 'isitem', 'urlencode', 'test_not_isitem_urlencode.dxw']],
81 => ['title' => 'Testing DxwLoader Include Directive (.dxl DimensioneX Libraries, Parallel Line Counting, Panels & it_underworld.dxw)...', 'keywords' => ['include', 'dxl', 'library', 'it_underworld', 'it_uwpanels', 'it_commons', 'initchoice', 'initial', 'dxwloader']],
];
// CLI Options parsing
$opts = getopt('s:f:lh', ['section:', 'filter:', 'list', 'help']);
if (isset($opts['h']) || isset($opts['help'])) {
echo "DimensioneX Multiplayer, Auth & UI Test Suite\n\n";
echo "Usage:\n";
echo " php test_multiplayer.php [options]\n\n";
echo "Options:\n";
echo " -s, --section=<val> Run only specified section(s).\n";
echo " Examples: --section=18, --section=1,2,5, --section=15-18\n";
echo " -f, --filter=<str> Run only sections matching substring or keywords.\n";
echo " Examples: --filter=Speak, --filter=open, --filter=auth\n";
echo " -l, --list List all available test sections and exit.\n";
echo " -h, --help Show this help screen.\n";
exit(0);
}
if (isset($opts['l']) || isset($opts['list'])) {
echo "=== Available Test Sections ===\n";
foreach ($sections as $num => $sec) {
$cleanTitle = trim($sec['title'], " .\n");
printf(" %2d. %s\n", $num, $cleanTitle);
}
echo "\nRun a section with: php test_multiplayer.php --section=<number>\n";
echo "Or filter with: php test_multiplayer.php --filter=<keyword>\n";
exit(0);
}
$rawSection = $opts['section'] ?? $opts['s'] ?? null;
$rawFilter = $opts['filter'] ?? $opts['f'] ?? null;
$selectedSections = null;
if ($rawSection !== null) {
$selectedSections = [];
foreach (explode(',', (string)$rawSection) as $part) {
$part = trim($part);
if (str_contains($part, '-')) {
[$start, $end] = explode('-', $part, 2);
for ($i = (int)$start; $i <= (int)$end; $i++) {
$selectedSections[] = $i;
}
} elseif (is_numeric($part)) {
$selectedSections[] = (int)$part;
}
}
}
$executedSections = [];
function shouldRun(int $num): bool {
global $sections, $selectedSections, $rawFilter, $executedSections;
if ($selectedSections !== null && !in_array($num, $selectedSections, true)) {
return false;
}
if ($rawFilter !== null && $rawFilter !== '') {
$needle = strtolower((string)$rawFilter);
$sec = $sections[$num] ?? null;
if (!$sec) return false;
$matched = false;
if (str_contains(strtolower($sec['title']), $needle)) {
$matched = true;
} else {
foreach ($sec['keywords'] as $kw) {
if (str_contains(strtolower($kw), $needle)) {
$matched = true;
break;
}
}
}
if (!$matched) return false;
}
$executedSections[] = $num;
return true;
}
// Check if any section matches
$anyWillRun = false;
foreach (array_keys($sections) as $num) {
if ($selectedSections !== null && !in_array($num, $selectedSections, true)) continue;
if ($rawFilter !== null && $rawFilter !== '') {
$needle = strtolower((string)$rawFilter);
$sec = $sections[$num];
if (!str_contains(strtolower($sec['title']), $needle)) {
$kwMatch = false;
foreach ($sec['keywords'] as $kw) {
if (str_contains(strtolower($kw), $needle)) { $kwMatch = true; break; }
}
if (!$kwMatch) continue;
}
}
$anyWillRun = true;
break;
}
if (!$anyWillRun) {
echo "No test sections matched criteria: " . ($rawSection ? "--section={$rawSection} " : "") . ($rawFilter ? "--filter={$rawFilter}" : "") . "\n";
echo "Use --list to view all available sections.\n";
exit(0);
}
echo "=== Running DimensioneX Multiplayer, Auth & UI Tests ===\n";
if ($selectedSections !== null) {
echo " [Filtered by Section(s): " . implode(', ', $selectedSections) . "]\n";
}
if ($rawFilter !== null && $rawFilter !== '') {
echo " [Filtered by Keyword: '{$rawFilter}']\n";
}
echo "\n";
$passCount = 0;
$failCount = 0;
function assertTest(bool $condition, string $title): void
{
global $passCount, $failCount;
if ($condition) {
echo " [PASS] {$title}\n";
$passCount++;
} else {
echo " [FAIL] {$title}\n";
$failCount++;
}
}
function runMultiplayer(array $get = [], array $post = [], array $server = [], array $session = []): string
{
if (!isset($server['DIMX_WORLD_FILE'])) {
$server['DIMX_WORLD_FILE'] = __DIR__ . '/../docs/dxw-examples/world2.dxw';
}
if (!isset($server['DIMX_WORLD_ID'])) {
$server['DIMX_WORLD_ID'] = 'test_unit_w2';
}
$runner = sys_get_temp_dir() . '/dimx_run_' . uniqid() . '.php';
$sessionCode = '';
if (!empty($session)) {
$sessionCode = "@session_start();\n"
. "\$_SESSION = " . var_export($session, true) . ";\n";
}
$code = "<?php\n"
. $sessionCode
. '$_GET = ' . var_export($get, true) . ";\n"
. '$_POST = ' . var_export($post, true) . ";\n";
foreach ($server as $k => $v) {
$code .= '$_SERVER[' . var_export($k, true) . '] = ' . var_export($v, true) . ";\n";
}
$code .= "require " . var_export(__DIR__ . '/multiplayer.php', true) . ";\n";
file_put_contents($runner, $code);
$cmd = 'C:\\xampp\\php\\php.exe ' . escapeshellarg($runner);
$output = (string)shell_exec($cmd);
@unlink($runner);
return $output;
}
function runChat(array $get = [], array $post = [], array $server = []): string
{
if (!isset($get['view'])) {
$get['view'] = 'msgs';
}
if (!isset($get['username']) && isset($get['player'])) {
$get['username'] = $get['player'];
}
if (!isset($server['DIMX_WORLD_ID']) && isset($get['world_id'])) {
$server['DIMX_WORLD_ID'] = (string)$get['world_id'];
}
return runMultiplayer($get, $post, $server);
}
// Common test fixtures available to all sections
$config = file_exists(__DIR__ . '/config.php') ? require __DIR__ . '/config.php' : [];
$dbConfig = $config['db'] ?? [];
$baseUrl = $config['base_url'] ?? '';
$pm = new PersistenceManager($dbConfig, __DIR__ . '/data');
$unitWorldId = 'test_unit_' . uniqid();
$engine = new GameEngine($pm, $unitWorldId, null, $baseUrl);
$world = $engine->loadOrSeedWorld();
$dxwFile = dirname(__DIR__) . '/docs/dxw-examples/world2.dxw';
$world2Path = $dxwFile;
$loader = new Dimx\DxwLoader('http://localhost');
$world2 = $loader->load($world2Path);
$w2 = $world2;
$testWorldId = 'test_w2_' . rand(1000, 9999);
$engineW2 = new Dimx\GameEngine($pm, $testWorldId, $world2Path);
$seededWorld = $engineW2->loadOrSeedWorld();
$uiJson = new UIjson();
$uiBot = new UIbot();
// -------------------------------------------------------------
// Test 1: Client Detection
// -------------------------------------------------------------
if (shouldRun(1)) {
echo "1. Testing UI::detectClientType()...\n";
$_GET = ['format' => 'json'];
assertTest(UI::detectClientType() === 'json', "Detects ?format=json as 'json'");
$_GET = ['ui' => 'json'];
assertTest(UI::detectClientType() === 'json', "Detects ?ui=json as 'json'");
$_GET = ['bot' => '1'];
assertTest(UI::detectClientType() === 'json', "Detects ?bot=1 as 'json'");
$_GET = ['api' => '1'];
assertTest(UI::detectClientType() === 'json', "Detects ?api=1 as 'json'");
$_GET = [];
$_SERVER['CONTENT_TYPE'] = 'application/json';
assertTest(UI::detectClientType() === 'json', "Detects Content-Type: application/json as 'json'");
unset($_SERVER['CONTENT_TYPE']);
$_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml';
assertTest(UI::detectClientType() === 'html', "Detects browser Accept header as 'html'");
}
// -------------------------------------------------------------
// Test 2: Input Parsing (Single World enforcement & Password)
// -------------------------------------------------------------
if (shouldRun(2)) {
echo "\n2. Testing UI::parseInput()...\n";
$_GET = ['cmd' => 'go', 'dir' => 'N', 'player' => 'Explorer1', 'password' => 'secret123', 'world' => 'arbitrary_world'];
$input = UI::parseInput();
assertTest($input['username'] === 'Explorer1', "Parsed username 'Explorer1'");
assertTest($input['password'] === 'secret123', "Parsed password 'secret123'");
assertTest($input['cmd'] === 'go', "Parsed cmd 'go'");
assertTest($input['param'] === 'N', "Parsed param 'N' from 'dir'");
assertTest($input['arg0'] === 'N', "Parsed arg0 'N' from 'dir'");
assertTest(!isset($input['world']) && !isset($input['world_file']), "World switching parameters are ignored (single world)");
// Test arg0 and arg1 resolution & single parameter normalization
$_GET = ['cmd' => 'click', 'arg0' => 'key1'];
$inClick = UI::parseInput();
assertTest($inClick['arg0'] === 'key1' && $inClick['arg1'] === '', "Single arg0 parameter is filled and arg1 is empty");
// Legacy target single parameter shifted to arg0
$_GET = ['cmd' => 'click', 'target' => 'door1'];
$inLegacyTarget = UI::parseInput();
assertTest($inLegacyTarget['arg0'] === 'door1' && $inLegacyTarget['arg1'] === '', "Single legacy target parameter shifted into arg0");
// Two parameters passed (e.g. usewith key1 on door1)
$_GET = ['cmd' => 'usewith', 'arg0' => 'key1', 'arg1' => 'door1'];
$inTwoArgs = UI::parseInput();
assertTest($inTwoArgs['arg0'] === 'key1' && $inTwoArgs['arg1'] === 'door1', "Two arguments populate arg0 and arg1");
// txtBox quick speech sets cmd='say', arg0=text, arg1='*'
$_GET = [];
$_POST = ['txtBox' => 'Hello adventurer'];
$inSpeech = UI::parseInput();
assertTest($inSpeech['cmd'] === 'say' && $inSpeech['arg0'] === 'Hello adventurer' && $inSpeech['arg1'] === '*', "txtBox quick speech populates cmd=say, arg0=speech and arg1=*");
$_POST = [];
}
// -------------------------------------------------------------
// Test 3: GameEngine Setup & Core Processing
// -------------------------------------------------------------
if (shouldRun(3)) {
echo "\n3. Testing GameEngine initialization and world seeding...\n";
$config = file_exists(__DIR__ . '/config.php') ? require __DIR__ . '/config.php' : [];
$dbConfig = $config['db'] ?? [];
$baseUrl = $config['base_url'] ?? '';
$pm = new PersistenceManager($dbConfig, __DIR__ . '/data');
$unitWorldId = 'test_unit_' . uniqid();
$engine = new GameEngine($pm, $unitWorldId, null, $baseUrl);
$world = $engine->loadOrSeedWorld();
assertTest($world !== null, "Engine seeded world successfully");
assertTest(isset($world->rooms['beach']), "Seeded world contains 'beach' room");
assertTest(isset($world->rooms['bar']), "Seeded world contains 'bar' room");
assertTest(isset($world->items['apple']), "Seeded world contains 'apple' item");
}
// -------------------------------------------------------------
// Test 4: Database Player Accounts & Password Encryption
// -------------------------------------------------------------
if (shouldRun(4)) {
echo "\n4. Testing Player DB Table, Auto-Increment Numeric ID & Bcrypt Passwords...\n";
$testUser = 'AuthTester_' . rand(1000, 9999);
$testPass = 'p@ssw0rdSecure!';
// Step 4a: Account creation
$auth1 = $pm->authenticateOrCreatePlayer($unitWorldId, $testUser, $testPass, true);
assertTest($auth1['success'] === true, "New player account successfully registered");
assertTest(($auth1['created'] ?? false) === true, "Flags account as newly created");
assertTest(!empty($auth1['numeric_id']) && is_numeric($auth1['numeric_id']), "Account assigned numeric ID: " . ($auth1['numeric_id'] ?? 0));
assertTest(($auth1['is_bot'] ?? false) === true, "Bot player flag stored as true");
// Step 4b: Verify password in DB is encrypted (one-way bcrypt hash, not plaintext)
$pdo = $pm->getPdo();
if ($pdo !== null) {
$stmt = $pdo->prepare("SELECT id, name, password, is_bot FROM dimx_players WHERE world_id = :wid AND LOWER(name) = :pname");
$stmt->execute([':wid' => $unitWorldId, ':pname' => strtolower($testUser)]);
$dbRow = $stmt->fetch();
assertTest($dbRow !== false, "Player record exists in dimx_players table");
assertTest($dbRow['name'] === $testUser, "Nickname is clearly readable: " . $dbRow['name']);
assertTest($dbRow['password'] !== $testPass, "Password is NOT stored in plaintext");
assertTest(str_starts_with($dbRow['password'], '$2y$') || strlen($dbRow['password']) >= 60, "Password encoded with bcrypt hash: " . substr($dbRow['password'], 0, 10) . '...');
assertTest((int)$dbRow['id'] === (int)$auth1['numeric_id'], "Database numeric ID matches returned ID: " . $dbRow['id']);
}
// Step 4c: Existing account login with correct password
$auth2 = $pm->authenticateOrCreatePlayer($unitWorldId, $testUser, $testPass, true);
assertTest($auth2['success'] === true, "Existing account authenticated with correct password");
assertTest(($auth2['created'] ?? false) === false, "Existing account recognized (created = false)");
assertTest((int)$auth2['numeric_id'] === (int)$auth1['numeric_id'], "Numeric ID consistent across logins");
// Step 4d: Existing account login with wrong password
$auth3 = $pm->authenticateOrCreatePlayer($unitWorldId, $testUser, 'wrong_password_here', true);
assertTest($auth3['success'] === false, "Login rejected with incorrect password");
assertTest(($auth3['code'] ?? '') === 'invalid_password', "Error code is 'invalid_password'");
// Step 4e: Verify in-memory player ID changes every time the user logs in
echo "\n Testing that in-memory player ID changes on every login...\n";
$uiJsonTemp = new UIjson();
$resLogin1 = $engine->processCommand($testUser, 'login', '', '', $uiJsonTemp, (int)$auth1['numeric_id'], true, true);
$engineId1 = $resLogin1['player']->id;
assertTest(!empty($engineId1), "Player assigned in-memory ID on login 1: {$engineId1}");
assertTest($engineId1 !== (string)$auth1['numeric_id'], "In-memory ID ({$engineId1}) is NOT the database numeric ID (" . $auth1['numeric_id'] . ")");
assertTest($engineId1 !== $testUser, "In-memory ID ({$engineId1}) is NOT the player nickname ({$testUser})");
assertTest((int)$resLogin1['player']->numericId === (int)$auth1['numeric_id'], "Player numericId matches database ID: " . $auth1['numeric_id']);
// Simulate player logging out
$engine->processCommand($testUser, 'logout', '', '', $uiJsonTemp, (int)$auth1['numeric_id'], true, false, $engineId1);
assertTest($world->getPlayer($engineId1) === null, "Player {$engineId1} cleanly removed from world memory on logout");
// Second login for the SAME user account
$resLogin2 = $engine->processCommand($testUser, 'login', '', '', $uiJsonTemp, (int)$auth1['numeric_id'], true, true);
$engineId2 = $resLogin2['player']->id;
assertTest(!empty($engineId2), "Player assigned in-memory ID on login 2: {$engineId2}");
assertTest($engineId1 !== $engineId2, "In-memory ID CHANGED on second login ({$engineId1} != {$engineId2})");
assertTest((int)$resLogin2['player']->numericId === (int)$auth1['numeric_id'], "Database numeric ID remains unchanged (" . $auth1['numeric_id'] . ")");
assertTest($resLogin2['player']->name === $testUser, "Player nickname remains unchanged ({$testUser})");
}
// -------------------------------------------------------------
// Test 5: Bot Player Command Dispatch via UIjson API
// -------------------------------------------------------------
if (shouldRun(5)) {
echo "\n5. Testing Bot Player via UIjson API...\n";
$uiJson = new UIjson();
$botName = 'BotAction_' . rand(100, 999);
$botAuth = $pm->authenticateOrCreatePlayer($unitWorldId, $botName, 'botPass123', true);
// Step 5a: Login & initial look
$result1 = $engine->processCommand($botName, 'look', '', '', $uiJson, (int)$botAuth['numeric_id'], true, true);
$player = $result1['player'];
assertTest($player instanceof Player, "Bot player created as Player instance");
assertTest($player->getUI() === $uiJson, "Player has UI property set to UIjson instance");
assertTest($player->numericId === (int)$botAuth['numeric_id'], "Player instance has numericId populated");
assertTest($player->isBot === true, "Player instance has isBot flagged as true");
assertTest($player->getRoom()->id === 'beach', "Bot player starts in 'beach' room");
// Verify room snapshot structure
$snapshot = $uiJson->buildRoomSnapshot($player->getRoom(), $player);
assertTest($snapshot['id'] === 'beach', "Room snapshot ID is 'beach'");
assertTest(!empty($snapshot['description']), "Room snapshot contains description");
assertTest(count($snapshot['items']) === 1 && $snapshot['items'][0]['id'] === 'apple', "Room snapshot contains 'apple' item");
assertTest(count($snapshot['exits']) === 1 && $snapshot['exits'][0]['direction'] === 'E', "Room snapshot contains 'E' exit");
// Step 5b: Bot picks up apple
$result2 = $engine->processCommand($botName, 'pick', '', 'apple', $uiJson);
assertTest(isset($result2['player']->contents['apple']), "Bot player now has 'apple' in inventory");
assertTest(!isset($result2['room']->contents['apple']), "'apple' removed from beach room contents");
$playerStatus = $uiJson->buildPlayerStatus($result2['player']);
assertTest($playerStatus['carrying_count'] === 1, "Player status carrying_count is 1");
assertTest($playerStatus['inventory'][0]['id'] === 'apple', "Player status inventory lists 'apple'");
assertTest($playerStatus['numeric_id'] === (int)$botAuth['numeric_id'], "Player status contains numeric_id");
assertTest($playerStatus['is_bot'] === true, "Player status contains is_bot: true");
// Step 5c: Bot travels East to Tiki Bar
$result3 = $engine->processCommand($botName, 'go', 'E', '', $uiJson);
assertTest($result3['player']->getRoom()->id === 'bar', "Bot travelled East and is now in 'bar'");
// Step 5d: Bot drops apple in Tiki Bar
$result4 = $engine->processCommand($botName, 'drop', '', 'apple', $uiJson);
assertTest(!isset($result4['player']->contents['apple']), "Bot dropped 'apple', no longer in inventory");
assertTest(isset($result4['room']->contents['apple']), "'apple' is now inside 'bar' room contents");
// Step 5e: Bot talks
$result5 = $engine->processCommand($botName, 'say', 'Greetings from AI bot!', '', $uiJson);
assertTest(in_array("- Greetings from AI bot!", $result5['messages'], true) || in_array("<b>{$botName}</b> says: Greetings from AI bot!", $result5['messages'], true), "Bot speech captured in messages");
// Step 5f: 'save' command saves player profile without exiting
$resultSave = $engine->processCommand($botName, 'save', '', '', $uiJson);
assertTest(in_array("Game saved!", $resultSave['messages'], true), "Save command returns 'Game saved!' confirmation");
assertTest(($resultSave['logged_out'] ?? false) === false, "Save command does NOT logout player");
// Step 5g: 'logout' command logs out player
$resultLogout = $engine->processCommand($botName, 'logout', '', '', $uiJson);
assertTest(($resultLogout['logged_out'] ?? false) === true, "Logout command sets logged_out = true");
assertTest($world->getPlayer($resultLogout['player']->id) === null, "Player cleanly removed on logout");
// Step 5h: 'savexit' command is removed completely
$resultSavexit = $engine->processCommand($botName, 'savexit', '', '', $uiJson);
assertTest(($resultSavexit['logged_out'] ?? false) === false, "Legacy 'savexit' does NOT trigger logout");
assertTest(in_array("Unknown command: savexit", $resultSavexit['messages'], true), "Legacy 'savexit' is treated as unknown command");
// Step 5i: Panel buttons verify 'save' & 'logout' replace 'savexit'
$defaultPanel = Dimx\Panel::createDefaultPanel();
assertTest($defaultPanel->getButton('save') !== null, "Default panel includes 'save' button");
assertTest($defaultPanel->getButton('logout') !== null, "Default panel includes 'logout' button");
assertTest($defaultPanel->getButton('logout')?->caption === 'Disconnect', "Default panel 'logout' button caption is 'Disconnect'");
assertTest($defaultPanel->getButton('savexit') === null, "Default panel does NOT include legacy 'savexit' button");
$pm->resetWorld($unitWorldId);
}
// -------------------------------------------------------------
// Test 6: Simulating multiplayer.php entrypoint for Bot (JSON)
// -------------------------------------------------------------
if (shouldRun(6)) {
echo "\n6. Testing multiplayer.php entrypoint with bot JSON query...\n";
// 6a: Bot without password should receive 401 login_required
$jsonOutputNoPass = runMultiplayer([
'format' => 'json',
'username' => 'DirectApiBot',
'cmd' => 'look',
]);
$decodedNoPass = json_decode($jsonOutputNoPass, true);
assertTest(($decodedNoPass['status'] ?? '') === 'login_required', "Bot without password gets 'login_required'");
assertTest(str_contains($decodedNoPass['error'] ?? '', 'Password is required'), "Bot error indicates password is required");
// 6b: Test Bot (BotAlpha) with username and password should authenticate and return game snapshot via UIjson
$jsonOutput = runMultiplayer([
'format' => 'json',
'username' => 'BotAlpha',
'password' => 'test123',
'cmd' => 'look',
]);
$decoded = json_decode($jsonOutput, true);
assertTest(is_array($decoded), "multiplayer.php returned valid JSON");
assertTest(($decoded['success'] ?? false) === true, "JSON response indicates success: true");
assertTest(isset($decoded['room']['id']), "JSON response includes room snapshot");
assertTest(isset($decoded['player']['name']) && $decoded['player']['name'] === 'BotAlpha', "JSON response includes player name 'BotAlpha'");
assertTest(isset($decoded['player']['numeric_id']) && is_numeric($decoded['player']['numeric_id']), "JSON response includes numeric_id: " . ($decoded['player']['numeric_id'] ?? 0));
assertTest(($decoded['player']['is_bot'] ?? false) === true, "JSON response player has is_bot = true");
// 6c: Bot with wrong password on existing account
$jsonOutputWrongPass = runMultiplayer([
'format' => 'json',
'username' => 'BotAlpha',
'password' => 'wrongSecret!',
'cmd' => 'look',
]);
$decodedWrongPass = json_decode($jsonOutputWrongPass, true);
assertTest(($decodedWrongPass['status'] ?? '') === 'login_required', "Bot with incorrect password gets 'login_required'");
assertTest(str_contains($decodedWrongPass['error'] ?? '', 'Incorrect password'), "Bot error message indicates incorrect password");
// 6d: Bot logs in a second time in a new session: verify in-memory ID changes while numeric ID remains constant
$firstSessionEngineId = $decoded['player']['id'] ?? '';
$firstNumericId = $decoded['player']['numeric_id'] ?? 0;
$jsonOutput2 = runMultiplayer([
'format' => 'json',
'username' => 'BotAlpha',
'password' => 'test123',
'cmd' => 'look',
]);
$decoded2 = json_decode($jsonOutput2, true);
$secondSessionEngineId = $decoded2['player']['id'] ?? '';
$secondNumericId = $decoded2['player']['numeric_id'] ?? 0;
assertTest(!empty($firstSessionEngineId) && !empty($secondSessionEngineId), "Both bot logins returned in-memory player IDs");
assertTest($firstSessionEngineId !== $secondSessionEngineId, "In-memory player ID changed between logins ({$firstSessionEngineId} != {$secondSessionEngineId})");
assertTest((int)$firstNumericId === (int)$secondNumericId, "Database numeric ID stayed constant ({$firstNumericId})");
assertTest($firstSessionEngineId !== (string)$firstNumericId, "In-memory ID is NOT the database numeric ID");
}
// -------------------------------------------------------------
// Test 7: Simulating multiplayer.php entrypoint for Human (HTML)
// -------------------------------------------------------------
if (shouldRun(7)) {
echo "\n7. Testing multiplayer.php entrypoint with human HTML player...\n";
$heroUser = 'HumanHero_' . bin2hex(random_bytes(3));
$htmlOutput = runMultiplayer([
'username' => $heroUser,
'password' => 'heroPass789',
'cmd' => 'look',
'reset' => '1',
], [], ['HTTP_ACCEPT' => 'text/html']);
assertTest(str_contains($htmlOutput, '<!DOCTYPE html>'), "multiplayer.php returned HTML doctype");
assertTest(str_contains($htmlOutput, $heroUser), "HTML output includes player name '{$heroUser}'");
assertTest(str_contains($htmlOutput, "👤 <b>{$heroUser}</b>"), "Header displays human-readable player name '{$heroUser}'");
assertTest(!str_contains($htmlOutput, '(Score:'), "Header does NOT display Score next to player name");
assertTest(!str_contains($htmlOutput, '💾'), "Header does NOT display storage diskette icon / method");
assertTest(!str_contains($htmlOutput, 'Carrying:'), "STATS box does NOT display Carrying 0/5");
assertTest(!preg_match('/👤\s*<b>p_\d+_[a-f0-9]+<\/b>/', $htmlOutput), "Header does NOT display internal engine player ID");
assertTest(str_contains($htmlOutput, 'The classic beach with white sand') || str_contains($htmlOutput, 'Sunny Beach') || str_contains($htmlOutput, 'beach'), "Action console displays initial room description");
assertTest(!preg_match('/\[p_\d+_[a-f0-9]+\]/', $htmlOutput), "HTML output does NOT expose internal player IDs in visible brackets");
assertTest(str_contains($htmlOutput, 'id="consoleBox"'), "HTML output includes consoleBox element");
assertTest(str_contains($htmlOutput, 'id="chatBox"'), "HTML output includes chatBox element");
assertTest(str_contains($htmlOutput, 'name="arg0"') && str_contains($htmlOutput, 'id="arg0Input"'), "UIhtml form includes arg0 input");
assertTest(str_contains($htmlOutput, 'name="arg1"') && str_contains($htmlOutput, 'id="arg1Input"'), "UIhtml form includes arg1 input");
assertTest(!str_contains($htmlOutput, 'id="paramInput"') && !str_contains($htmlOutput, 'id="targetInput"'), "UIhtml form does NOT include legacy paramInput or targetInput");
assertTest(!preg_match('/#navpad\s+td\s*\{[^}]*background-color/i', $htmlOutput), "#navpad td in <head> <style> does NOT contain background-color");
assertTest(preg_match('/<table[^>]+id="navpad"[^>]+style="[^"]*background-color:\s*[^;"]+/i', $htmlOutput) === 1, "#navpad <table> tag has inline style with background-color");
}
// -------------------------------------------------------------
// Test 8: Testing login prompt for Bot (JSON) and Human (HTML)
// -------------------------------------------------------------
if (shouldRun(8)) {
echo "\n8. Testing login prompts and form fields...\n";
// HTML login prompt without username
$htmlLoginPrompt = runMultiplayer([], [], ['HTTP_ACCEPT' => 'text/html']);
assertTest(str_contains($htmlLoginPrompt, 'Enter the World'), "multiplayer.php HTML prompt includes 'Enter the World' form");
assertTest(str_contains($htmlLoginPrompt, 'name="username"'), "multiplayer.php HTML prompt includes username input");
assertTest(str_contains($htmlLoginPrompt, 'name="password"'), "multiplayer.php HTML prompt includes password input");
assertTest(str_contains($htmlLoginPrompt, 'type="password"'), "multiplayer.php password input is masked (type=password)");
// Direct UIhtml renderLogin test with error
ob_start();
$htmlUi = new UIhtml();
$htmlUi->renderLogin("Invalid password. Please try again.", "PlayerOne");
$loginHtml = ob_get_clean();
assertTest(str_contains($loginHtml, 'Invalid password. Please try again.'), "UIhtml renders error message");
assertTest(str_contains($loginHtml, 'value="PlayerOne"'), "UIhtml preserves default username on error");
// Direct UIjson renderLogin test
ob_start();
$jsonUi = new UIjson();
$jsonUi->renderLogin("Test auth error");
$loginJson = ob_get_clean();
$decodedLogin = json_decode($loginJson, true);
assertTest(($decodedLogin['status'] ?? '') === 'login_required', "UIjson login status is 'login_required'");
assertTest(($decodedLogin['error'] ?? '') === 'Test auth error', "UIjson returns error message");
}
// -------------------------------------------------------------
// Test 9: Bot Logout / Disconnect & Room Occupant Verification
// -------------------------------------------------------------
if (shouldRun(9)) {
echo "\n9. Testing Bot Logout & Occupant Removal...\n";
$testBot1 = 'BotOne_' . rand(1000, 9999);
$testBot2 = 'BotTwo_' . rand(1000, 9999);
// Bot 1 connects
runMultiplayer([
'format' => 'json',
'username' => $testBot1,
'password' => 'bot1pass',
'cmd' => 'look',
]);
// Bot 2 connects and looks around - should see Bot1 in occupants
$bot2Json = runMultiplayer([
'format' => 'json',
'username' => $testBot2,
'password' => 'bot2pass',
'cmd' => 'look',
]);
$bot2Data = json_decode($bot2Json, true);
$occupantsBefore = array_column($bot2Data['room']['occupants'] ?? [], 'name');
assertTest(in_array($testBot1, $occupantsBefore, true), "Bot2 sees {$testBot1} in room occupants");
// Bot 1 logs out
$logoutJson = runMultiplayer([
'format' => 'json',
'username' => $testBot1,
'password' => 'bot1pass',
'cmd' => 'logout',
]);
$logoutData = json_decode($logoutJson, true);
assertTest(($logoutData['status'] ?? '') === 'logged_out', "Bot1 logout response status is 'logged_out'");
assertTest(($logoutData['logged_out'] ?? false) === true, "Bot1 logout response flag logged_out is true");
assertTest(array_key_exists('room', $logoutData) && $logoutData['room'] === null, "Bot1 logout response room snapshot is null");
// Bot 2 looks again - Bot1 should NO LONGER be in occupants!
$bot2JsonAfter = runMultiplayer([
'format' => 'json',
'username' => $testBot2,
'password' => 'bot2pass',
'cmd' => 'look',
]);
$bot2DataAfter = json_decode($bot2JsonAfter, true);
$occupantsAfter = array_column($bot2DataAfter['room']['occupants'] ?? [], 'name');
assertTest(!in_array($testBot1, $occupantsAfter, true), "Bot2 NO LONGER sees {$testBot1} after logout");
}
// -------------------------------------------------------------
// Test 10: world2.dxw Description Parsing (Apostrophe handling)
// -------------------------------------------------------------
if (shouldRun(10)) {
echo "\n10. Testing world2.dxw Description Parsing...\n";
$world2Path = __DIR__ . '/../docs/dxw-examples/world2.dxw';
$loader = new Dimx\DxwLoader('http://localhost');
$world2 = $loader->load($world2Path);
$surfer = $world2->getCharacter('surfer');
assertTest($surfer !== null, "World 2 contains 'surfer' character");
assertTest(
$surfer->description === "Walks up and down, I'd say he's got nothing to do.",
"Surfer description parsed entirely without stopping at apostrophe: '{$surfer->description}'"
);
$box = $world2->items['box'] ?? null;
assertTest($box !== null, "World 2 contains 'box' item");
assertTest(
$box->description === "It's just an ordinary cardboard box",
"Box description parsed entirely: '{$box->description}'"
);
$bungalow = $world2->getRoom('bungalow');
assertTest($bungalow !== null, "World 2 contains 'bungalow' room");
assertTest(
str_contains($bungalow->description, "There's a switch on the left wall."),
"Bungalow description contains full text with apostrophe: '{$bungalow->description}'"
);
$apple = $world2->items['apple'] ?? null;
assertTest($apple !== null, "World 2 contains 'apple' item");
assertTest(
str_contains($apple->description, "maybe it's good and tasty"),
"Apple description contains full text with apostrophe: '{$apple->description}'"
);
}
// -------------------------------------------------------------
// Test 11: onStart Event & Chat PANEL Enforcement
// -------------------------------------------------------------
if (shouldRun(11)) {
echo "\n11. Testing onStart Event & Chat PANEL Enforcement...\n";
// Purge any stale chat messages from previous runs
if ($pm->getPdo() !== null) {
try {
$pm->getPdo()->exec("DELETE FROM dimx_messages WHERE world_id = 'main'");
} catch (\Throwable $e) {}
}
// Verify prebuilt panels in World
assertTest($world2->getPanel('default') !== null, "World contains prebuilt 'default' panel");
assertTest($world2->getPanel('chat') !== null, "World contains prebuilt 'chat' panel");
$chatPanel = $world2->getPanel('chat');
$chatCmds = $chatPanel->getAvailableCommands();
assertTest(in_array('say', $chatCmds, true), "Chat panel allows 'say' command");
assertTest(in_array('save', $chatCmds, true), "Chat panel allows 'save' command");
assertTest(in_array('logout', $chatCmds, true), "Chat panel allows 'logout' command");
assertTest(in_array('look', $chatCmds, true), "Chat panel allows 'look' command");
assertTest(in_array('click', $chatCmds, true), "Chat panel allows 'click' command");
assertTest(in_array('use', $chatCmds, true), "Chat panel allows 'use' command");
assertTest(in_array('go', $chatCmds, true), "Move commands ('go') are always valid");
assertTest(!in_array('pick', $chatCmds, true), "Chat panel DOES NOT allow 'pick' command");
assertTest(!in_array('drop', $chatCmds, true), "Chat panel DOES NOT allow 'drop' command");
// Seed world2 using GameEngine to trigger onStart
$testWorldId = 'test_w2_' . rand(1000, 9999);
$engineW2 = new Dimx\GameEngine($pm, $testWorldId, $world2Path);
$seededWorld = $engineW2->loadOrSeedWorld();
assertTest($seededWorld->defaultPanel !== null, "Seeded world has active panel");
assertTest($seededWorld->defaultPanel->id === 'chat', "onStart event executed SetPanel: active panel is 'chat'");
// Test Bot login via UIjson on world2
$botW2 = 'ChatBot_' . rand(1000, 9999);
$botJsonOutput = runMultiplayer([
'format' => 'json',
'username' => $botW2,
'password' => 'botPass123',
'reset' => '1', // Reset main world to world2.dxw configuration
]);
$botData = json_decode($botJsonOutput, true);
assertTest(($botData['status'] ?? '') === 'ok', "Bot login response status is 'ok'");
assertTest(!array_key_exists('panel', $botData), "Bot output omits internal 'panel' structure (no panel ID exposed)");
assertTest(array_key_exists('commands', $botData), "Bot output exposes simplified top-level 'commands' list");
$botCmds = $botData['commands'] ?? [];
assertTest(
in_array('look', $botCmds, true),
"Bot commands include 'look': " . json_encode($botCmds)
);
assertTest(
in_array('click', $botCmds, true),
"Bot commands include 'click': " . json_encode($botCmds)
);
assertTest(
in_array('go', $botCmds, true),
"Bot commands include 'go': " . json_encode($botCmds)
);
assertTest(
in_array('use', $botCmds, true),
"Bot commands include 'use': " . json_encode($botCmds)
);
assertTest(
!in_array('examine', $botCmds, true),
"Bot commands DO NOT include 'examine'"
);
assertTest(
!in_array('talk', $botCmds, true),
"Bot commands DO NOT include 'talk'"
);
assertTest(
!in_array('quit', $botCmds, true),
"Bot commands DO NOT include 'quit'"
);
assertTest(
!in_array('disconnect', $botCmds, true),
"Bot commands DO NOT include 'disconnect'"
);
assertTest(
!in_array('exit', $botCmds, true),
"Chat bot commands DO NOT include vehicle 'exit'"
);
assertTest(
in_array('logout', $botCmds, true),
"Bot commands include 'logout'"
);
// Verify Bot inspecting surfer receives the complete description
$surferOcc = null;
foreach ($botData['room']['occupants'] ?? [] as $occ) {
if (($occ['id'] ?? '') === 'surfer') {
$surferOcc = $occ;
break;
}
}
assertTest($surferOcc !== null, "Bot sees surfer in room occupants");
assertTest(!array_key_exists('description', $surferOcc), "Bot room snapshot surfer description is hidden (must look at character to read it)");
assertTest(!array_key_exists('icon', $surferOcc), "Bot room snapshot surfer omits null icon");
assertTest(isset($surferOcc['image']), "Bot room snapshot surfer includes image");
assertTest(!array_key_exists('dimensions', $surferOcc['image']), "Bot room snapshot surfer image omits 'dimensions'");
assertTest(($surferOcc['image']['width'] ?? 0) === 120, "Bot room snapshot surfer image width is 120");
assertTest(($surferOcc['image']['height'] ?? 0) === 120, "Bot room snapshot surfer image height is 120");
assertTest(str_contains($surferOcc['image']['url'] ?? '', 'chrSurfista.gif'), "Bot room snapshot surfer image URL contains 'chrSurfista.gif'");
// Bot uses 'look' on surfer in chat panel - should succeed and trigger surfer.onLook
$lookJson = runMultiplayer([
'format' => 'json',
'username' => $botW2,
'password' => 'botPass123',
'cmd' => 'look',
'target' => 'surfer',
]);
$lookData = json_decode($lookJson, true);
$lookMsg = implode(' ', $lookData['console'] ?? []);
assertTest(
str_contains($lookMsg, "Walks up and down, I'd say he's got nothing to do."),
"Bot successfully looks at surfer: character description is in console"
);
assertTest(
!str_contains($lookMsg, "staring at me") && !str_contains($lookMsg, "Please look elsewhere!"),
"surfer.onLook spoken message is NOT in room description / console"
);
// Verify surfer.onLook Speak output is delivered in msgs
$chatTexts = array_column($lookData['msgs'] ?? [], 'text');
$chatAll = implode(' ', $chatTexts);
assertTest(
str_contains($chatAll, "staring at me") || str_contains($chatAll, "Please look elsewhere!"),
"surfer.onLook spoken message IS heard in msgs: '{$chatAll}'"
);
$surferChat = array_filter($lookData['msgs'] ?? [], fn($c) => ($c['sender'] ?? '') === 'a surfer');
assertTest(!empty($surferChat), "surfer.onLook speech has sender 'a surfer' in msgs");
$surferMsgItem = end($surferChat);
assertTest(($surferMsgItem['recipient'] ?? null) === $botW2, "surfer speaks to \$AGENT ({$botW2}) when second parameter is missing");
// Verify that another player does NOT receive this private message directed to $botW2
$otherChatJson = runMultiplayer([
'format' => 'json',
'username' => 'EavesdropperBot',
'password' => 'secret123',
'cmd' => 'look',
]);
$otherChatData = json_decode($otherChatJson, true);
$otherChatTexts = array_column($otherChatData['msgs'] ?? [], 'text');
$otherChatAll = implode(' ', $otherChatTexts);
assertTest(
!str_contains($otherChatAll, "staring at me") && !str_contains($otherChatAll, "Please look elsewhere!"),
"Other player does NOT hear the private speech directed to \$AGENT"
);
// Bot uses 'click' on surfer in chat panel - should also succeed
$clickJson = runMultiplayer([
'format' => 'json',
'username' => $botW2,
'password' => 'botPass123',
'cmd' => 'click',
'target' => 'surfer',
]);
$clickData = json_decode($clickJson, true);
$clickMsg = implode(' ', $clickData['console'] ?? []);
assertTest(
str_contains($clickMsg, "Walks up and down, I'd say he's got nothing to do."),
"Bot successfully clicks on surfer in chat panel: '{$clickMsg}'"
);
// Bot tries disallowed command 'pick' in chat panel
$disallowedPickJson = runMultiplayer([
'format' => 'json',
'username' => $botW2,
'password' => 'botPass123',
'cmd' => 'pick',
'target' => 'box',
]);
$disallowedPickData = json_decode($disallowedPickJson, true);
$disallowedPickMsg = implode(' ', $disallowedPickData['console'] ?? []);
assertTest(
str_contains($disallowedPickMsg, "Command 'pick' is not allowed in current panel (chat)"),
"Bot sending 'pick' is rejected in chat panel: '{$disallowedPickMsg}'"
);
// Test continuous session navigation and using switch to start game
$resGo1 = $engineW2->processCommand('SessionBot', 'go', 'U', '', $uiJson, null, true, true);
$botSessionId = $resGo1['player']->id;
assertTest($resGo1['room']?->id === 'rocca', "Move command 'go U' took player to 'rocca'");
$resGo2 = $engineW2->processCommand('SessionBot', 'go', 'E', '', $uiJson, null, true, false, $botSessionId);
assertTest($resGo2['room']?->id === 'bungalow', "Move command 'go E' took player to 'bungalow'");
// Use switch in bungalow: triggers switch.onUse and transitions world to default panel!
$resUse = $engineW2->processCommand('SessionBot', 'use', '', 'switch', $uiJson, null, true, false, $botSessionId);
$useSwitchMsg = implode(' ', $resUse['messages'] ?? []);
assertTest(
str_contains($useSwitchMsg, "The adventure has started!"),
"switch.onUse fired and broadcasted: '{$useSwitchMsg}'"
);
assertTest($resUse['world']->defaultPanel->id === 'default', "switch.onUse successfully switched panel to 'default'");
assertTest($resUse['world']->defaultPanel->isCommandAllowed('pick'), "Default panel now allows 'pick'");
// Human HTML verification: Navigation exits remain visible and active
$humanHtmlOutput = runMultiplayer([
'format' => 'html',
'username' => 'HumanChatHero',
'password' => 'humanPass123',
]);
assertTest(str_contains($humanHtmlOutput, 'id="panel_chat"'), "Human player gets HTML panel with id='panel_chat'");
assertTest(str_contains($humanHtmlOutput, 'name="txtBox"'), "Human player gets speech textbox");
assertTest(str_contains($humanHtmlOutput, "sendCmd('look')"), "Human player sees Look button");
assertTest(!str_contains($humanHtmlOutput, 'id="btn_click"'), "Human player DOES NOT see explicit Click button (click is implicit on objects)");
assertTest(str_contains($humanHtmlOutput, "sendCmd('use')"), "Human player sees Use button");
assertTest(str_contains($humanHtmlOutput, "sendCmd('say')"), "Human player gets Say button");
assertTest(str_contains($humanHtmlOutput, "sendCmd('save')"), "Human player gets Save button");
assertTest(str_contains($humanHtmlOutput, "sendCmd('logout')"), "Human player gets Disconnect (logout) button");
assertTest(str_contains($humanHtmlOutput, "Disconnect"), "Human player sees Disconnect button label");
assertTest(str_contains($humanHtmlOutput, "sendCmd('go','w16')"), "Human player STILL SEES exit button for [U] to the rock");
assertTest(!str_contains($humanHtmlOutput, "sendCmd('pick')"), "Human player DOES NOT see Pick button");
// Test STATS box rendering in UIhtml (Capital letter rule & no Carrying)
$statsWorld = new Dimx\World('stats_world', 'Stats World');
$statsPlayer = new Dimx\Player($statsWorld, 'StatsTester', 'p_stats_1');
$statsPlayer->setAttrList('Health=100,Skill=5,open=0,locked=1,Score=50');
$statsRoom = new Dimx\Room($statsWorld, 'Stats Room', 'stats_room');
$statsPlayer->container = $statsRoom;
ob_start();
$htmlUiInstance = new Dimx\UIhtml($statsPlayer);
$htmlUiInstance->render([
'world' => $statsWorld,
'player' => $statsPlayer,
'room' => $statsRoom,
'messages' => [],
'lockError' => false,
]);
$statsHtml = ob_get_clean();
assertTest(!str_contains($statsHtml, 'Carrying:'), "UIhtml STATS box omits Carrying");
assertTest(str_contains($statsHtml, '<b>Health:</b> 100'), "UIhtml STATS box displays capitalized attribute 'Health: 100'");
assertTest(str_contains($statsHtml, '<b>Skill:</b> 5'), "UIhtml STATS box displays capitalized attribute 'Skill: 5'");
assertTest(str_contains($statsHtml, '<b>Score:</b> 50'), "UIhtml STATS box displays capitalized attribute 'Score: 50'");
assertTest(!str_contains($statsHtml, '<b>open:</b>'), "UIhtml STATS box omits lowercase attribute 'open'");
assertTest(!str_contains($statsHtml, '<b>locked:</b>'), "UIhtml STATS box omits lowercase attribute 'locked'");
assertTest(!str_contains($statsHtml, 'id="btn_go"'), "UIhtml default panel DOES NOT render 'go' button inside #ctrls");
assertTest(!str_contains($statsHtml, "sendCmd('go');"), "UIhtml #ctrls DOES NOT render an explicit Go button");
}
// -------------------------------------------------------------
// Test 12: Testing UIbot vs UIjson and testBots Configuration
// -------------------------------------------------------------
if (shouldRun(12)) {
echo "\n12. Testing UIbot vs UIjson and testBots Configuration...\n";
$uiBot = new UIbot();
assertTest($uiBot instanceof Dimx\UIjson, "UIbot inherits from UIjson");
assertTest($uiBot->getType() === 'bot', "UIbot type is 'bot'");
// Create mock room with both NPC Character and Player occupant
$w = $seededWorld ?? $world;
$mockRoom = new Dimx\Room($w, 'Test Room', 'test_room');
$targetRoom = new Dimx\Room($w, 'Secret Target', 'secret_target');
$mockLink = new Dimx\Link($w, 'Test Door', 'test_door', $mockRoom, $targetRoom, true, 'E');
$npcChar = new Dimx\Character($w, 'NpcDude', 'npc_dude');
$npcChar->move($mockRoom);
$otherPlayer = new Dimx\Player($w, 'OtherPlayer', 'p_other');
$otherPlayer->move($mockRoom);
$observerPlayer = new Dimx\Player($w, 'Observer', 'p_observer');
$observerPlayer->move($mockRoom);
$uiBotSnapshot = $uiBot->buildRoomSnapshot($mockRoom, $observerPlayer);
$uiJsonSnapshot = $uiJson->buildRoomSnapshot($mockRoom, $observerPlayer);
// UIbot must NOT have 'is_player' in any occupant
$uiBotOccupants = $uiBotSnapshot['occupants'] ?? [];
assertTest(count($uiBotOccupants) === 2, "UIbot snapshot contains 2 occupants");
$hasIsPlayerInBot = false;
foreach ($uiBotOccupants as $occ) {
if (array_key_exists('is_player', $occ)) {
$hasIsPlayerInBot = true;
}
}
assertTest(!$hasIsPlayerInBot, "UIbot occupant snapshot omits 'is_player' (NPCs and players indistinguishable)");
$hasDescInBot = false;
foreach ($uiBotOccupants as $occ) {
if (array_key_exists('description', $occ)) {
$hasDescInBot = true;
}
}
assertTest(!$hasDescInBot, "UIbot occupant snapshot omits 'description' (bot must look at character)");
// UIbot must NOT have 'target_room_id' or 'target_room_name' in exits
$uiBotExits = $uiBotSnapshot['exits'] ?? [];