-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser-mock-server.html
More file actions
743 lines (617 loc) · 22 KB
/
Copy pathbrowser-mock-server.html
File metadata and controls
743 lines (617 loc) · 22 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UniQuake Browser Server</title>
<style>
body {
font-family: 'Courier New', monospace;
background-color: #1e1e1e;
color: #e0e0e0;
margin: 0;
padding: 20px;
}
.container {
display: flex;
flex-direction: column;
height: calc(100vh - 40px);
max-width: 1200px;
margin: 0 auto;
}
.header {
margin-bottom: 20px;
}
.header h1 {
margin: 0;
color: #4fc3f7;
}
.main-content {
display: flex;
flex: 1;
gap: 20px;
}
.panel {
background-color: #2d2d2d;
border-radius: 5px;
padding: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
.server-panel {
flex: 1;
display: flex;
flex-direction: column;
}
.right-panels {
display: flex;
flex-direction: column;
flex: 2;
gap: 20px;
}
.game-panel {
flex: 2;
display: flex;
flex-direction: column;
}
.token-panel {
flex: 1;
}
.clients-panel {
flex: 1;
display: flex;
flex-direction: column;
}
.status-display {
background-color: #252525;
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
font-size: 14px;
}
.log {
flex: 1;
background-color: #252525;
border-radius: 3px;
padding: 10px;
overflow-y: auto;
font-size: 14px;
}
.client-list {
flex: 1;
background-color: #252525;
border-radius: 3px;
padding: 10px;
overflow-y: auto;
font-size: 14px;
margin-bottom: 10px;
}
.client-item {
background-color: #3d3d3d;
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
.client-item .client-name {
font-weight: bold;
color: #4fc3f7;
}
.client-item .client-info {
font-size: 12px;
color: #aaa;
}
.game-state {
flex: 1;
overflow-y: auto;
background-color: #252525;
border-radius: 3px;
padding: 10px;
font-size: 14px;
}
.token-info {
background-color: #252525;
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
input, button {
background-color: #3d3d3d;
border: none;
border-radius: 3px;
padding: 8px 12px;
color: #e0e0e0;
font-family: 'Courier New', monospace;
}
input {
flex: 1;
margin-bottom: 10px;
}
button {
background-color: #2196f3;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #1976d2;
}
button:disabled {
background-color: #555;
cursor: not-allowed;
}
.button-row {
display: flex;
gap: 10px;
margin-top: 10px;
}
.status-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
font-size: 14px;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 5px;
}
.status-registered {
background-color: #4caf50;
}
.status-unregistered {
background-color: #f44336;
}
/* ANSI color simulation */
.ansi-green {
color: #4caf50;
}
.ansi-red {
color: #f44336;
}
.ansi-yellow {
color: #ffeb3b;
}
.ansi-blue {
color: #2196f3;
}
.ansi-cyan {
color: #00bcd4;
}
.ansi-magenta {
color: #e91e63;
}
.ansi-white {
color: #ffffff;
}
.ansi-gray {
color: #9e9e9e;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-size: 14px;
}
.actions-panel {
background-color: #252525;
border-radius: 3px;
padding: 10px;
margin-top: 10px;
}
.action-buttons {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.action-buttons button {
flex: 1;
min-width: 120px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>UniQuake Browser Server</h1>
</div>
<div class="main-content">
<div class="server-panel panel">
<div class="status-row">
<div>
<span class="status-indicator" id="server-status"></span>
<span id="status-text">Not Registered</span>
</div>
</div>
<h2>Server Configuration</h2>
<div class="form-group">
<label for="server-name">Server Name</label>
<input type="text" id="server-name" readonly placeholder="Auto-generated on server start">
</div>
<div class="form-group">
<label for="server-map">Map</label>
<input type="text" id="server-map" value="browser_map">
</div>
<div class="form-group">
<label for="server-max-players">Max Players</label>
<input type="number" id="server-max-players" value="16" min="1" max="32">
</div>
<div class="form-group">
<label for="server-token-enabled">Token Enabled</label>
<input type="checkbox" id="server-token-enabled" checked>
</div>
<div class="button-row">
<button id="start-button">Start Server</button>
<button id="stop-button" disabled>Stop Server</button>
</div>
<h2>Server Status</h2>
<div class="status-display" id="server-status-display">
Server not started
</div>
<div class="actions-panel">
<h3>Server Actions</h3>
<div class="action-buttons">
<button id="broadcast-button" disabled>Broadcast Message</button>
<button id="game-state-button" disabled>Send Game State</button>
<button id="end-game-button" disabled>End Game</button>
</div>
</div>
</div>
<div class="right-panels">
<div class="game-panel panel">
<div class="game-state" id="game-state">No game state available</div>
</div>
</div>
</div>
</div>
<!-- Load scripts -->
<script src="lib/client/uniquake-token-service.js"></script>
<script src="lib/client/browser-mock-game.js"></script>
<script src="lib/client/browser-mock-server.js"></script>
<script src="lib/client/game-integration.js"></script>
<script>
// Load WebRTC adapter directly, bypassing the auto-connect behavior
window.UNIQUAKE_CONFIG = {
useWebRTC: true,
masterServer: 'ws://localhost:27950',
noAutoConnect: true // Flag to prevent auto-connection
};
// Load the adapter script
var script = document.createElement('script');
script.src = '/webrtc-adapter.js';
script.onload = function() {
console.log('WebRTC adapter loaded, initializing server');
initializeServer();
};
document.head.appendChild(script);
// Main server, game, and integration instances
let server, game, integration;
let selectedClientId = null;
/**
* Generate a random server name
*/
function generateServerName() {
const adjectives = ['Epic', 'Cosmic', 'Legendary', 'Mystic', 'Quantum', 'Rapid', 'Savage', 'Galactic', 'Neon', 'Shadow'];
const nouns = ['Server', 'Arena', 'Battlefield', 'Realm', 'Nexus', 'Dimension', 'Domain', 'Fortress', 'Outpost', 'Hub'];
const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
const noun = nouns[Math.floor(Math.random() * nouns.length)];
const num = Math.floor(Math.random() * 1000);
return `${adj}${noun}${num}`;
}
// Initialize server
async function initializeServer() {
// Get initial configuration from UI
const config = getServerConfig();
// Generate random server name - this will be used for registration during init()
const serverName = generateServerName();
document.getElementById('server-name').value = serverName;
config.serverName = serverName;
console.log('Generated server name for initial registration:', serverName);
// Create mock game
game = new BrowserMockGame({
isServer: true,
updateInterval: 10000, // 10 seconds between game state updates
onStateChange: updateGameState
});
// Create mock server
server = new BrowserMockServer({
masterServer: window.UNIQUAKE_CONFIG.masterServer || 'ws://localhost:27950',
serverName: config.serverName,
map: config.map,
maxPlayers: config.maxPlayers,
tokenEnabled: config.tokenEnabled,
debug: true,
onStatusUpdate: updateServerStatus,
onClientConnect: handleClientConnect,
onClientDisconnect: handleClientDisconnect,
onChatMessage: handleChatMessage
});
// Create game integration
integration = new GameIntegration({
server: server,
debug: true,
onGameStateUpdate: updateGameState,
onTokenEvent: handleTokenEvent,
onPlayerJoin: handlePlayerJoin,
onPlayerLeave: handlePlayerLeave,
onGameEnd: handleGameEnd
});
// Initialize all components
await game.init();
await server.init();
await integration.init(game);
// Store reference to game in server for synchronization
server.gameInstance = game;
// Check if the server was registered during init()
if (server.serverState.registered) {
console.log('Server was successfully registered during init(), proceeding to start');
} else {
console.warn('Server was not registered during init(), registration will be attempted in startServer()');
}
// Auto-start the server
await startServer();
console.log('Server system initialized and auto-started');
// Note: We no longer need a separate normalizeGameState function
// as we now use the token service's hashGameState method directly.
// The token service internally handles state normalization and hashing.
// Set up UI event handlers
setupUIHandlers();
// Update initial UI - disable event emission to avoid recursion
updateServerStatus(server.getStatus(false));
// Set up regular UI updates to ensure game state stays in sync
setInterval(() => {
if (game && server) {
// Update game state panel
updateGameState(game.getGameState());
console.log(`UI Sync - Game frame: ${game.gameState.frame}, Server frame: ${server.serverState.gameState.frame}`);
}
}, 10000); // Update every 10 seconds
}
// Get server configuration from UI
function getServerConfig() {
// Get current server name from input field, or leave undefined to be set later
const serverNameElem = document.getElementById('server-name');
const serverName = serverNameElem.value || undefined;
return {
serverName: serverName, // Will be auto-generated if undefined
map: document.getElementById('server-map').value,
maxPlayers: parseInt(document.getElementById('server-max-players').value) || 16,
tokenEnabled: document.getElementById('server-token-enabled').checked
};
}
// Set up UI event handlers
function setupUIHandlers() {
// Server control buttons
document.getElementById('start-button').addEventListener('click', startServer);
document.getElementById('stop-button').addEventListener('click', stopServer);
// Server action buttons
document.getElementById('broadcast-button').addEventListener('click', broadcastMessage);
document.getElementById('game-state-button').addEventListener('click', sendGameState);
document.getElementById('end-game-button').addEventListener('click', endGame);
// Removed client and token action buttons
}
// Start the server
async function startServer() {
// Update configuration from UI
const config = getServerConfig();
// Use the existing server name instead of generating a new one
// This ensures consistency between Server Status and Token System panels
const serverName = server.serverInfo.name;
document.getElementById('server-name').value = serverName;
config.serverName = serverName;
// Update server config
server.serverInfo.name = config.serverName;
server.serverInfo.map = config.map;
server.serverInfo.maxPlayers = config.maxPlayers;
// Check if the server is already registered
let success = server.serverState.registered;
if (success) {
console.log('Server already registered during init(), skipping explicit registration');
} else {
// Server wasn't registered during init(), we need to register it now
console.log('Server not registered yet, registering now...');
success = await server.registerServer();
}
if (success) {
// Start the game
game.start();
// Update UI
document.getElementById('start-button').disabled = true;
document.getElementById('stop-button').disabled = false;
document.getElementById('broadcast-button').disabled = false;
document.getElementById('game-state-button').disabled = false;
document.getElementById('end-game-button').disabled = false;
// Disable configuration inputs
document.getElementById('server-name').disabled = true;
document.getElementById('server-map').disabled = true;
document.getElementById('server-max-players').disabled = true;
document.getElementById('server-token-enabled').disabled = true;
} else {
alert('Failed to register server with master server');
}
}
// Stop the server
async function stopServer() {
// Unregister from master server
await server.unregisterServer();
// Stop the game
game.stop();
// Update UI
document.getElementById('start-button').disabled = false;
document.getElementById('stop-button').disabled = true;
document.getElementById('broadcast-button').disabled = true;
document.getElementById('game-state-button').disabled = true;
document.getElementById('end-game-button').disabled = true;
// Enable configuration inputs
document.getElementById('server-name').disabled = false;
document.getElementById('server-map').disabled = false;
document.getElementById('server-max-players').disabled = false;
document.getElementById('server-token-enabled').disabled = false;
}
// Broadcast a message to all clients
function broadcastMessage() {
const message = prompt('Enter message to broadcast:');
if (message) {
server.broadcastMessage(message);
}
}
// Send game state to all clients
function sendGameState() {
if (server.serverState.tokenService) {
server.createGameStateToken(true);
} else {
alert('Token service not available');
}
}
// End the game
function endGame() {
// Get connected clients
const clients = server.getClients();
if (clients.length === 0) {
alert('No clients connected');
return;
}
// If we have a selected client, use that as the winner
let winnerId = selectedClientId;
// If no client is selected, ask which client should win
if (!winnerId && clients.length > 0) {
const clientOptions = clients.map((client, index) =>
`${index + 1}. ${client.username || client.id}`
).join('\n');
const selection = prompt(`Select winner (enter number):\n${clientOptions}`);
const index = parseInt(selection) - 1;
if (!isNaN(index) && index >= 0 && index < clients.length) {
winnerId = clients[index].id;
} else {
alert('Invalid selection');
return;
}
}
// End the game with the selected winner
if (winnerId) {
game.endGame(winnerId);
integration.endGame(winnerId);
}
}
// Removed client and token action functions
// Update server status display
function updateServerStatus(status) {
const statusIndicator = document.getElementById('server-status');
const statusText = document.getElementById('status-text');
const statusDisplay = document.getElementById('server-status-display');
if (status.registered) {
statusIndicator.className = 'status-indicator status-registered';
statusText.textContent = 'Registered';
} else {
statusIndicator.className = 'status-indicator status-unregistered';
statusText.textContent = 'Not Registered';
}
// Update status display
statusDisplay.innerHTML = `
<strong>Name:</strong> ${status.name}<br>
<strong>Map:</strong> ${status.map}<br>
<strong>Players:</strong> ${status.players}/${status.maxPlayers}<br>
<strong>Peer ID:</strong> <span style="font-family: monospace; word-break: break-all;">${status.peerId || 'N/A'}</span><br>
<strong>Registered:</strong> ${status.registered ? 'Yes' : 'No'}<br>
`;
// Token info and client list panels have been removed
}
// Handle client connection
function handleClientConnect(client) {
console.log('Client connected:', client);
}
// Handle client disconnection
function handleClientDisconnect(client) {
console.log('Client disconnected:', client);
}
// Handle chat message
function handleChatMessage(event) {
console.log('Chat message:', event);
}
// Client list display removed
// Update game state display
function updateGameState(gameState) {
if (!gameState) return;
// Update game state display
const gameStateElem = document.getElementById('game-state');
// Get server information
const serverName = server ? server.serverInfo.name : 'Unknown';
const serverId = server ? (server.serverState.peerId || 'Not registered') : 'N/A';
const collectedTokens = server ? server.serverState.collectedTokens.length : 0;
// Calculate state hash for the game state panel
let stateHash = 'N/A';
if (server && server.serverState.tokenService && server.serverState.tokenService.hashGameState) {
try {
// Enable debug mode temporarily to see serialization and hash details
const debugEnabled = server.serverState.tokenService.debugMode;
server.serverState.tokenService.debugMode = true;
// Use the token service's normalization and hash calculation
// This ensures we use exactly the same process on server and client
stateHash = server.serverState.tokenService.hashGameState(gameState);
console.log(`Server - Hash calculated for frame ${gameState.frame}:`, stateHash);
// Restore previous debug setting
server.serverState.tokenService.debugMode = debugEnabled;
} catch (error) {
console.error('Failed to calculate game state hash:', error.message);
}
}
gameStateElem.innerHTML = `
<strong>Server Name:</strong> ${serverName}<br>
<strong>Server ID:</strong> <span style="font-family: monospace; word-break: break-all;">${serverId}</span><br>
<strong>Balance:</strong> ${collectedTokens} tokens collected<br>
<strong>Frame:</strong> ${gameState.frame}<br>
<strong>Timestamp:</strong> ${new Date(gameState.timestamp).toLocaleTimeString()}<br>
<strong>Players:</strong> ${Object.keys(gameState.players).length}<br>
<strong>State Hash:</strong> <span style="font-family: monospace; word-break: break-all;">${stateHash}</span><br>
`;
// Display player information
if (Object.keys(gameState.players).length > 0) {
gameStateElem.innerHTML += '<br><strong>Player Information:</strong><br>';
Object.keys(gameState.players).forEach(playerId => {
const player = gameState.players[playerId];
const score = gameState.score?.[playerId] || 0;
gameStateElem.innerHTML += `
- ${player.name}: Health: ${Math.round(player.health)} | Score: ${score}<br>
`;
});
}
// Display game end information if game has ended
if (gameState.ended) {
gameStateElem.innerHTML += `
<br><strong>Game Ended</strong><br>
<strong>Winner:</strong> ${gameState.winner ? gameState.players[gameState.winner]?.name || gameState.winner : 'None'}<br>
`;
if (gameState.finalScores) {
gameStateElem.innerHTML += '<strong>Final Scores:</strong><br>';
Object.keys(gameState.finalScores).forEach(playerId => {
const playerName = gameState.players[playerId]?.name || playerId;
const score = gameState.finalScores[playerId];
gameStateElem.innerHTML += `
- ${playerName}: ${score}<br>
`;
});
}
}
}
// Token information display removed
// Handle token events
function handleTokenEvent(event) {
console.log('Token event:', event);
}
// Handle player join event
function handlePlayerJoin(player) {
console.log('Player joined:', player);
}
// Handle player leave event
function handlePlayerLeave(player) {
console.log('Player left:', player);
}
// Handle game end event
function handleGameEnd(result) {
console.log('Game ended:', result);
}
</script>
</body>
</html>