refactor backend and fix movement skipping

This commit is contained in:
jwinterm
2025-05-25 10:43:47 -04:00
parent 928af8b071
commit 0818b60541
21 changed files with 778 additions and 167 deletions
+182
View File
@@ -0,0 +1,182 @@
<!DOCTYPE html>
<html>
<head>
<title>Wowngeon Debug</title>
<style>
body {
font-family: monospace;
background: #000;
color: #0f0;
padding: 20px;
}
.module {
margin: 10px 0;
padding: 10px;
border: 1px solid #333;
}
.status-ok { color: #0f0; }
.status-error { color: #f00; }
.status-warning { color: #ff0; }
</style>
</head>
<body>
<h1>Wowngeon Module Debug</h1>
<div id="socket-status" class="module">
<h3>Socket.io Status</h3>
<div id="socket-info">Loading...</div>
</div>
<div id="modules-status" class="module">
<h3>Module Status</h3>
<div id="modules-info">Loading...</div>
</div>
<div id="game-status" class="module">
<h3>Game Display Status</h3>
<div id="game-info">Loading...</div>
</div>
<div id="console-log" class="module">
<h3>Console Messages</h3>
<div id="console-output"></div>
</div>
<!-- Socket.io -->
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<!-- Initialize socket -->
<script>
window.socket = io();
</script>
<!-- Core libraries -->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/rot.min.js"></script>
<script src="js/options.js"></script>
<script src="js/teletype.js"></script>
<!-- Game modules -->
<script src="js/game.js"></script>
<script src="js/ui.js"></script>
<script src="js/socketHandlers.js"></script>
<script src="js/inputHandler.js"></script>
<script>
// Capture console messages
const consoleOutput = document.getElementById('console-output');
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
function addToConsole(type, message) {
const div = document.createElement('div');
div.className = type === 'error' ? 'status-error' :
type === 'warn' ? 'status-warning' : 'status-ok';
div.textContent = `[${type.toUpperCase()}] ${message}`;
consoleOutput.appendChild(div);
consoleOutput.scrollTop = consoleOutput.scrollHeight;
}
console.log = function(...args) {
originalLog.apply(console, args);
addToConsole('log', args.join(' '));
};
console.error = function(...args) {
originalError.apply(console, args);
addToConsole('error', args.join(' '));
};
console.warn = function(...args) {
originalWarn.apply(console, args);
addToConsole('warn', args.join(' '));
};
$(document).ready(function() {
console.log("Debug page ready - checking module status...");
// Check socket status
$('#socket-info').html(`
<div class="${window.socket ? 'status-ok' : 'status-error'}">
Socket Available: ${!!window.socket}
</div>
<div class="${window.socket && window.socket.connected ? 'status-ok' : 'status-warning'}">
Socket Connected: ${window.socket ? window.socket.connected : 'N/A'}
</div>
`);
// Check modules
const modules = ['Game', 'UI', 'SocketHandlers', 'InputHandler'];
let moduleStatus = '';
modules.forEach(module => {
const available = typeof window[module] !== 'undefined';
const hasInit = available && typeof window[module].init === 'function';
moduleStatus += `
<div class="${available ? 'status-ok' : 'status-error'}">
${module}: ${available ? 'Available' : 'Missing'}
${hasInit ? ' (has init)' : ''}
</div>
`;
});
$('#modules-info').html(moduleStatus);
// Check ROT.js
$('#game-info').html(`
<div class="${typeof ROT !== 'undefined' ? 'status-ok' : 'status-error'}">
ROT.js Available: ${typeof ROT !== 'undefined'}
</div>
<div class="${typeof window.options !== 'undefined' ? 'status-ok' : 'status-error'}">
Options Available: ${typeof window.options !== 'undefined'}
</div>
<div class="${document.getElementById('game-display') ? 'status-ok' : 'status-error'}">
Game Display Container: ${!!document.getElementById('game-display')}
</div>
`);
// Try to initialize modules
if (typeof Game !== 'undefined') {
console.log("Attempting to initialize Game...");
try {
Game.init();
console.log("Game.init() completed successfully");
} catch (e) {
console.error("Game.init() failed:", e);
}
}
if (typeof InputHandler !== 'undefined') {
console.log("Attempting to initialize InputHandler...");
try {
InputHandler.init();
console.log("InputHandler.init() completed successfully");
} catch (e) {
console.error("InputHandler.init() failed:", e);
}
}
// Socket event listeners
if (window.socket) {
window.socket.on('connect', function() {
console.log('Socket connected successfully');
$('#socket-info').append('<div class="status-ok">Socket connected event received</div>');
});
window.socket.on('disconnect', function() {
console.log('Socket disconnected');
$('#socket-info').append('<div class="status-warning">Socket disconnected</div>');
});
window.socket.on('welcome', function(data) {
console.log('Welcome message received:', data);
});
}
});
</script>
<!-- Add a minimal game display area for testing -->
<div id="game-display" style="width: 800px; height: 400px; border: 1px solid #333; margin: 20px 0;">
<!-- Game display will be created here -->
</div>
</body>
</html>
+31 -1
View File
@@ -43,6 +43,12 @@
<!-- Game display -->
<div id="game-display" class="rotdis"></div>
<!-- Debug display area -->
<div id="debug-display" style="background: rgba(0,0,0,0.8); color: #0f0; font-family: monospace; font-size: 12px; padding: 10px; margin: 5px; border: 1px solid #333; max-height: 200px; overflow-y: auto;">
<div><strong>Debug Information:</strong></div>
<div id="debug-content">Ready...</div>
</div>
<!-- Chat messages area -->
<div class="chat-container">
<div id="messageBox">
@@ -81,12 +87,36 @@
<!-- Initialize game when ready -->
<script>
$(document).ready(function() {
console.log("Initializing Game...");
console.log("Document ready - initializing modules...");
console.log("Socket available:", !!window.socket);
console.log("Game object available:", typeof Game !== 'undefined');
console.log("SocketHandlers available:", typeof SocketHandlers !== 'undefined');
console.log("UI available:", typeof UI !== 'undefined');
console.log("InputHandler available:", typeof InputHandler !== 'undefined');
// Initialize Game
if (typeof Game !== 'undefined') {
console.log("Initializing Game...");
Game.init();
} else {
console.error("Game object not found!");
}
// Initialize SocketHandlers (CRITICAL for receiving game_start events!)
if (typeof SocketHandlers !== 'undefined') {
console.log("Initializing SocketHandlers...");
SocketHandlers.init();
} else {
console.error("SocketHandlers object not found!");
}
// Initialize InputHandler
if (typeof InputHandler !== 'undefined') {
console.log("Initializing InputHandler...");
InputHandler.init();
} else {
console.error("InputHandler object not found!");
}
});
</script>
</body>
+87
View File
@@ -377,6 +377,19 @@ var Game = {
if (data.visibleTiles && typeof data.visibleTiles === 'object' && Object.keys(data.visibleTiles).length > 0) {
console.log("Visible tiles updated. Number of rows:", Object.keys(data.visibleTiles).length);
this._visibleTiles = data.visibleTiles;
// Debug log for specific problematic coordinates
if (this._visibleTiles[18] && (this._visibleTiles[18][36] !== undefined || this._visibleTiles[18][35] !== undefined)) {
const clientDebug = `🔍 CLIENT y=18: x=35: ${this._visibleTiles[18][35]}, x=36: ${this._visibleTiles[18][36]}`;
console.log(clientDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(clientDebug);
}
if (this._visibleTiles[16] && (this._visibleTiles[16][36] !== undefined || this._visibleTiles[16][35] !== undefined)) {
const clientDebug = `🔍 CLIENT y=16: x=35: ${this._visibleTiles[16][35]}, x=36: ${this._visibleTiles[16][36]}`;
console.log(clientDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(clientDebug);
}
this._updateExploredTiles(); // This is important for fog of war
needsRedraw = true;
} else if (data.visibleTiles) {
@@ -441,10 +454,24 @@ var Game = {
tileType = this._visibleTiles[wy][wx];
baseFg = this.defaultFg; // Use this.defaultFg
baseChar = (tileType === 1) ? '#' : "'"; // Fixed: Always use ' for floor
// Debug for specific coordinates
if ((wx === 36 && (wy === 18 || wy === 16)) || (wx === 35 && (wy === 18 || wy === 16))) {
const renderDebug = `🔍 RENDER: (${wx},${wy}) tileType:${tileType} char:'${baseChar}' _visibleTiles[${wy}][${wx}]:${this._visibleTiles[wy][wx]}`;
console.log(renderDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(renderDebug);
}
} else if (this._exploredTiles[wy] && this._exploredTiles[wy][wx] !== undefined) {
tileType = this._exploredTiles[wy][wx];
baseFg = this.defaultFg; // Use this.defaultFg
baseChar = (tileType === 1) ? '#' : "'"; // Fixed: Always use ' for floor
// Debug for specific coordinates in explored tiles
if ((wx === 36 && (wy === 18 || wy === 16)) || (wx === 35 && (wy === 18 || wy === 16))) {
const exploreDebug = `🔍 EXPLORED: (${wx},${wy}) tileType:${tileType} char:'${baseChar}' _exploredTiles[${wy}][${wx}]:${this._exploredTiles[wy][wx]}`;
console.log(exploreDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(exploreDebug);
}
}
charStack.push(baseChar);
fgStack.push(baseFg);
@@ -693,7 +720,67 @@ var Game = {
}
console.log(row);
}
},
// Debugging function to test character mapping
debugTileMapping: function() {
const testValues = [0, 1, undefined, null];
for (const val of testValues) {
const char = (val === 1) ? '#' : "'";
const debugMsg = `Test mapping: value=${val} -> char='${char}'`;
console.log(debugMsg);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(debugMsg);
}
},
};
// Debug utility functions
const GameDebug = {
log: function(message) {
console.log(message);
this.updateDebugDisplay(message);
this.sendToServer(message);
},
updateDebugDisplay: function(message) {
const debugContent = document.getElementById('debug-content');
if (debugContent) {
const timestamp = new Date().toLocaleTimeString();
debugContent.innerHTML += `<div>[${timestamp}] ${message}</div>`;
// Keep only last 10 debug messages
const lines = debugContent.children;
if (lines.length > 10) {
debugContent.removeChild(lines[0]);
}
// Auto-scroll to bottom
const debugDisplay = document.getElementById('debug-display');
debugDisplay.scrollTop = debugDisplay.scrollHeight;
}
},
sendToServer: function(message) {
try {
fetch('/debug', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message })
}).catch(err => {
// Silently fail if server unavailable
});
} catch (err) {
// Silently fail
}
}
};
// Make it available globally
window.GameDebug = GameDebug;
// Ensure Game is available globally
if (typeof window !== 'undefined') {
window.Game = Game;
}
// Additional global or helper functions can be added here
+44 -7
View File
@@ -2,11 +2,23 @@
* Input handlers for the Wowngeon game
*/
const InputHandler = {
_lastMoveTime: 0,
_moveCooldown: 100, // Minimum 100ms between moves
_pendingMove: null,
_initialized: false, // Flag to prevent multiple initializations
init: function() {
if (this._initialized) {
console.warn("InputHandler.init() called multiple times - ignoring duplicate call");
return;
}
console.log("InputHandler: Initializing for the first time...");
this.setupChatForm();
this.setupFocusHandlers();
this.setupKeyboardControls();
this.setupModeToggle();
this._initialized = true;
},
setupChatForm: function() {
@@ -49,6 +61,7 @@ const InputHandler = {
},
setupKeyboardControls: function() {
const self = this; // Store reference to InputHandler for use in event handler
$(document).on('keydown', function(e) {
if (document.activeElement === $('#game-display')[0]) {
if (Game && Game._gameActive) {
@@ -64,10 +77,31 @@ const InputHandler = {
}
if (moved) {
console.log(`Attempting to move: dx=${dx}, dy=${dy}. Key: ${e.key}`);
console.log(`🎹 KEYDOWN: dx=${dx}, dy=${dy}, key=${e.key}, time=${Date.now()}`);
e.preventDefault(); // Prevent page scrolling
socket.emit('player_move', { dx: dx, dy: dy });
console.log(`Emitted player_move: dx=${dx}, dy=${dy}`);
// Implement movement throttling to prevent rapid-fire movement
const now = Date.now();
if (now - self._lastMoveTime >= self._moveCooldown) {
// Send move immediately if enough time has passed
socket.emit('player_move', { dx: dx, dy: dy });
console.log(`✅ EMITTED player_move: dx=${dx}, dy=${dy}`);
self._lastMoveTime = now;
self._pendingMove = null;
} else {
// Queue the move to be sent after cooldown
self._pendingMove = { dx: dx, dy: dy };
const timeToWait = self._moveCooldown - (now - self._lastMoveTime);
console.log(`⏳ QUEUED move: dx=${dx}, dy=${dy}, waiting ${timeToWait}ms`);
setTimeout(() => {
if (self._pendingMove) {
socket.emit('player_move', self._pendingMove);
console.log(`✅ EMITTED queued player_move: dx=${self._pendingMove.dx}, dy=${self._pendingMove.dy}`);
self._lastMoveTime = Date.now();
self._pendingMove = null;
}
}, timeToWait);
}
}
} else {
console.log("Game display has focus, but Game is not active.");
@@ -96,7 +130,10 @@ const InputHandler = {
}
};
// Initialize input handlers when DOM is ready
$(function() {
InputHandler.init();
});
// Ensure InputHandler is available globally
if (typeof window !== 'undefined') {
window.InputHandler = InputHandler;
}
// Note: InputHandler.init() is called from index.html after DOM ready
// to ensure proper initialization order with other modules
+41 -4
View File
@@ -2,13 +2,22 @@
* Socket event handlers for the Wowngeon game
*/
const SocketHandlers = {
_initialized: false, // Flag to prevent multiple initializations
init: function() {
if (this._initialized) {
console.warn("SocketHandlers.init() called multiple times - ignoring duplicate call");
return;
}
if (!window.socket) {
console.error("Socket not available!");
return;
}
console.log("SocketHandlers: Initializing for the first time...");
this.registerEventHandlers();
this._initialized = true;
},
registerEventHandlers: function() {
@@ -36,6 +45,12 @@ const SocketHandlers = {
clientId: socket.id,
userAgent: navigator.userAgent
});
// Auto-start game for faster testing
setTimeout(() => {
console.log("🚀 AUTO-STARTING GAME for faster testing");
socket.emit('chat message', 'enter');
}, 500); // Small delay to ensure connection is fully established
},
onWelcome: function(msg) {
@@ -100,6 +115,25 @@ const SocketHandlers = {
},
onGameUpdate: function(data) {
// Debug log to see what data we're receiving
if (data.visibleTiles) {
const debugMsg = "🔍 SOCKET: Received game update with visibleTiles";
console.log(debugMsg);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(debugMsg);
// Check for specific coordinates that are problematic
if (data.visibleTiles[18] && (data.visibleTiles[18][36] !== undefined || data.visibleTiles[18][35] !== undefined)) {
const coordDebug = `🔍 SOCKET y=18: x=35: ${data.visibleTiles[18][35]}, x=36: ${data.visibleTiles[18][36]}`;
console.log(coordDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(coordDebug);
}
if (data.visibleTiles[16] && (data.visibleTiles[16][36] !== undefined || data.visibleTiles[16][35] !== undefined)) {
const coordDebug = `🔍 SOCKET y=16: x=35: ${data.visibleTiles[16][35]}, x=36: ${data.visibleTiles[16][36]}`;
console.log(coordDebug);
if (window.GameDebug) window.GameDebug.updateDebugDisplay(coordDebug);
}
}
if (typeof Game !== 'undefined' && Game._gameActive) {
Game.updateGameState(data);
}
@@ -166,7 +200,10 @@ const SocketHandlers = {
}
};
// Initialize when DOM is ready
$(function() {
SocketHandlers.init();
});
// Ensure SocketHandlers is available globally
if (typeof window !== 'undefined') {
window.SocketHandlers = SocketHandlers;
}
// Note: SocketHandlers.init() is called from index.html after DOM ready
// to ensure proper initialization order with other modules
+5
View File
@@ -104,6 +104,11 @@ const UI = {
}
};
// Ensure UI is available globally
if (typeof window !== 'undefined') {
window.UI = UI;
}
// Initialize UI components when DOM is ready
$(function() {
UI.initTeletype();