refactor frontend and fix debug mode

This commit is contained in:
jwinterm
2025-05-29 13:40:44 -04:00
parent de3eed792b
commit f02e16272e
28 changed files with 422 additions and 376 deletions
+18 -5
View File
@@ -1,5 +1,8 @@
const { Client } = require('pg');
// Environment-based console logging control
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
const client = new Client({
user: 'postgres',
host: 'localhost',
@@ -21,7 +24,11 @@ function initializeDatabase() {
`;
client.query(createTableQuery)
.then(() => console.log("Database initialized"))
.then(() => {
if (CONSOLE_LOGGING) {
console.log("Database initialized");
}
})
.catch(err => console.error("Database initialization error:", err));
}
@@ -43,7 +50,9 @@ function insertVisitor(socketid, ip, cookie) {
// If table doesn't exist yet, try to initialize again
if (res.rows[0].to_regclass === null) {
console.log("Table 'visitors' doesn't exist yet, creating it now...");
if (CONSOLE_LOGGING) {
console.log("Table 'visitors' doesn't exist yet, creating it now...");
}
initializeDatabase();
return;
}
@@ -51,11 +60,15 @@ function insertVisitor(socketid, ip, cookie) {
// Insert the visitor
client.query(insertVisitorText, values, (err, res) => {
if (err) {
console.log(err.stack);
console.error("Database insert error:", err.stack);
} else if (res.rows && res.rows[0]) {
console.log("Visitor inserted:", res.rows[0]);
if (CONSOLE_LOGGING) {
console.log("Visitor inserted:", res.rows[0]);
}
} else {
console.log("Visitor inserted");
if (CONSOLE_LOGGING) {
console.log("Visitor inserted");
}
}
});
});
+12 -3
View File
@@ -1,5 +1,8 @@
const Game = require('../game/game'); // Ensure Game is required
// Environment-based console logging control
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
// User class definition
class User {
constructor(id, address) {
@@ -22,7 +25,9 @@ class User {
// Add user to the registry upon creation
userRegistry.set(id, this);
console.log(`User created and registered: ${id}`);
if (CONSOLE_LOGGING) {
console.log(`User created and registered: ${id}`);
}
}
/**
@@ -32,7 +37,9 @@ class User {
joinGame(gameInstance) {
this.currentGame = gameInstance;
this.stats.gamesPlayed++;
console.log(`[User.joinGame] User ${this.id} joined game ${gameInstance.id}. Total games played: ${this.stats.gamesPlayed}`);
if (CONSOLE_LOGGING) {
console.log(`[User.joinGame] User ${this.id} joined game ${gameInstance.id}. Total games played: ${this.stats.gamesPlayed}`);
}
}
/**
@@ -64,7 +71,9 @@ class User {
this.stats.monstersDefeated += gameStats.monstersDefeated;
}
console.log(`[User.endGame] User ${this.id} game ended: ${result}. Score: ${score}. Stats: ${JSON.stringify(this.stats)}`);
if (CONSOLE_LOGGING) {
console.log(`[User.endGame] User ${this.id} game ended: ${result}. Score: ${score}. Stats: ${JSON.stringify(this.stats)}`);
}
}
}
+82 -22
View File
@@ -5,15 +5,50 @@
*/
const rpc = require('../rpc/rpccalls.js');
const packageConfig = require('../package.json');
class DebugManager {
constructor(broadcastManager) {
this.broadcastManager = broadcastManager;
this.DEBUG_MODE = true; // Set to false to disable debug mode
// Environment-based configuration
const nodeEnv = process.env.NODE_ENV || 'production';
this.IS_PRODUCTION = nodeEnv === 'production';
this.IS_DEBUG = nodeEnv === 'debug';
this.IS_DEVELOPMENT = nodeEnv === 'development';
// Debug mode is enabled in development or debug environments
this.DEBUG_MODE = this.IS_DEBUG || this.IS_DEVELOPMENT;
// Configuration from package.json
const config = this.IS_PRODUCTION ? packageConfig.config.production : packageConfig.config.debug;
this.CONSOLE_LOGGING = config.console_logging || this.DEBUG_MODE;
this.DEBUG_HOTKEYS = config.debug_hotkeys || this.DEBUG_MODE;
this.SIMULATED_BLOCKS = config.simulated_blocks || this.DEBUG_MODE;
this.debugBlockHeight = 1;
this.debugInterval = null;
this.statusInterval = null;
this.lastProductionBlockHeight = 0;
// Log configuration on startup
this.logConfig();
}
// ====== CONFIGURATION LOGGING ======
/**
* Log current configuration settings
*/
logConfig() {
if (this.CONSOLE_LOGGING) {
console.log("🔧 DEBUG MANAGER CONFIGURATION:");
console.log(` NODE_ENV: ${process.env.NODE_ENV || 'production'}`);
console.log(` DEBUG_MODE: ${this.DEBUG_MODE}`);
console.log(` CONSOLE_LOGGING: ${this.CONSOLE_LOGGING}`);
console.log(` DEBUG_HOTKEYS: ${this.DEBUG_HOTKEYS}`);
console.log(` SIMULATED_BLOCKS: ${this.SIMULATED_BLOCKS}`);
}
}
// ====== INITIALIZATION ======
@@ -22,7 +57,7 @@ class DebugManager {
* Initialize debug mode or production mode
*/
initialize() {
if (this.DEBUG_MODE) {
if (this.DEBUG_MODE && this.SIMULATED_BLOCKS) {
this.initializeDebugMode();
} else {
this.initializeProductionMode();
@@ -33,7 +68,9 @@ class DebugManager {
* Initialize debug mode with simulated blocks
*/
initializeDebugMode() {
console.log("🐛 DEBUG MODE ENABLED - Simulating blocks every 30 seconds");
if (this.CONSOLE_LOGGING) {
console.log("🐛 DEBUG MODE ENABLED - Simulating blocks every 30 seconds");
}
// Initial debug block broadcast
this.broadcastManager.broadcastBlockHeight(this.debugBlockHeight);
@@ -41,7 +78,9 @@ class DebugManager {
// Debug block height simulator - advances every 30 seconds
this.debugInterval = setInterval(() => {
this.debugBlockHeight++;
console.log(`🐛 DEBUG: New simulated block: ${this.debugBlockHeight}`);
if (this.CONSOLE_LOGGING) {
console.log(`🐛 DEBUG: New simulated block: ${this.debugBlockHeight}`);
}
this.broadcastManager.broadcastBlockHeight(this.debugBlockHeight);
// Notify listeners about new block
@@ -60,13 +99,17 @@ class DebugManager {
* Initialize production mode with real blockchain calls
*/
initializeProductionMode() {
console.log("🚀 PRODUCTION MODE ENABLED - Using real blockchain RPC calls");
if (this.CONSOLE_LOGGING) {
console.log("🚀 PRODUCTION MODE ENABLED - Using real blockchain RPC calls");
}
// Real blockchain monitoring
this.debugInterval = setInterval(() => {
rpc.daemonCall("get_block_count", "", (result) => {
if (!result || !result.result || !result.result.count) {
console.log("❌ Failed to get block count from daemon");
if (this.CONSOLE_LOGGING) {
console.log("❌ Failed to get block count from daemon");
}
return;
}
@@ -75,7 +118,9 @@ class DebugManager {
// If new block found
if (currentHeight > this.lastProductionBlockHeight) {
console.log(`⛏️ New block found: ${currentHeight}`);
if (this.CONSOLE_LOGGING) {
console.log(`⛏️ New block found: ${currentHeight}`);
}
this.broadcastManager.broadcastBlockHeight(currentHeight);
// Notify listeners about new block
@@ -107,8 +152,11 @@ class DebugManager {
setDebugBlockHeight(height) {
if (this.DEBUG_MODE) {
this.debugBlockHeight = height;
this.broadcastManager.broadcastBlockHeight(this.debugBlockHeight);
} else {
if (this.CONSOLE_LOGGING) {
console.log(`🐛 DEBUG: Block height set to: ${height}`);
}
this.broadcastManager.broadcastBlockHeight(height);
} else if (this.CONSOLE_LOGGING) {
console.warn("Cannot set debug block height in production mode");
}
}
@@ -119,10 +167,12 @@ class DebugManager {
advanceDebugBlock() {
if (this.DEBUG_MODE) {
this.debugBlockHeight++;
console.log(`🐛 DEBUG: Manually advanced block to: ${this.debugBlockHeight}`);
if (this.CONSOLE_LOGGING) {
console.log(`🐛 DEBUG: Manually advanced block to: ${this.debugBlockHeight}`);
}
this.broadcastManager.broadcastBlockHeight(this.debugBlockHeight);
this.onNewBlock(this.debugBlockHeight);
} else {
} else if (this.CONSOLE_LOGGING) {
console.warn("Cannot advance debug block in production mode");
}
}
@@ -136,7 +186,9 @@ class DebugManager {
*/
onNewBlock(blockHeight) {
// This method can be overridden or have callbacks registered
console.log(`📦 New block detected: ${blockHeight}`);
if (this.CONSOLE_LOGGING) {
console.log(`📦 New block detected: ${blockHeight}`);
}
// Call registered callbacks
if (this.newBlockCallbacks) {
@@ -144,7 +196,9 @@ class DebugManager {
try {
callback(blockHeight);
} catch (error) {
console.error("Error in new block callback:", error);
if (this.CONSOLE_LOGGING) {
console.error("Error in new block callback:", error);
}
}
});
}
@@ -184,13 +238,15 @@ class DebugManager {
* @param {object} data - Event data
*/
debugSocket(socketId, eventName, data) {
const shortSocketId = socketId.substring(0, 8);
console.log(`🔌 SOCKET DEBUG: Sending ${eventName} to ${shortSocketId}...`);
// Limit payload logging to prevent console spam
const dataStr = JSON.stringify(data);
const shortDataStr = dataStr.length > 300 ? dataStr.substring(0, 300) + "..." : dataStr;
console.log(`📦 PAYLOAD: ${shortDataStr}`);
if (this.CONSOLE_LOGGING) {
const shortSocketId = socketId.substring(0, 8);
console.log(`🔌 SOCKET DEBUG: Sending ${eventName} to ${shortSocketId}...`);
// Limit payload logging to prevent console spam
const dataStr = JSON.stringify(data);
const shortDataStr = dataStr.length > 300 ? dataStr.substring(0, 300) + "..." : dataStr;
console.log(`📦 PAYLOAD: ${shortDataStr}`);
}
}
// ====== CLEANUP ======
@@ -209,7 +265,9 @@ class DebugManager {
this.statusInterval = null;
}
console.log("🧹 Debug manager cleaned up");
if (this.CONSOLE_LOGGING) {
console.log("🧹 Debug manager cleaned up");
}
}
/**
@@ -217,7 +275,9 @@ class DebugManager {
* @param {boolean} enabled - Whether to enable debug mode
*/
setDebugMode(enabled) {
console.log(`🔄 Switching debug mode to: ${enabled ? 'ENABLED' : 'DISABLED'}`);
if (this.CONSOLE_LOGGING) {
console.log(`🔄 Switching debug mode to: ${enabled ? 'ENABLED' : 'DISABLED'}`);
}
this.cleanup();
this.DEBUG_MODE = enabled;
this.initialize();
+18 -5
View File
@@ -1,5 +1,8 @@
const ROT = require('./rot.js');
// Environment-based console logging control
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
// ========================================
// DUNGEON CONFIGURATION SECTION
// ========================================
@@ -51,7 +54,9 @@ class DungeonGenerator {
};
const config = { ...defaultOptions, ...options };
console.log(`[DungeonGenerator] Generating dungeon with effective torchDensity: ${config.torchDensity}`); // Log effective torchDensity
if (CONSOLE_LOGGING) {
console.log(`[DungeonGenerator] Generating dungeon with effective torchDensity: ${config.torchDensity}`);
}
// Create dungeon using ROT.js Map.Digger
const digger = new ROT.Map.Digger(width, height, {
@@ -132,7 +137,9 @@ class DungeonGenerator {
let placedTorchesCount = 0; // Counter for torches placed in this function
// Log the torchDensity being used for this map generation pass
console.log(`[DungeonGenerator.enhanceMapWithVariations] Starting enhancement with torchDensity: ${config.torchDensity}`);
if (CONSOLE_LOGGING) {
console.log(`[DungeonGenerator.enhanceMapWithVariations] Starting enhancement with torchDensity: ${config.torchDensity}`);
}
const height = basicMap.length; // Use basicMap's dimensions
const width = basicMap[0].length; // Use basicMap's dimensions
@@ -159,7 +166,9 @@ class DungeonGenerator {
}
}
}
console.log(`[DungeonGenerator.enhanceMapWithVariations] Placed ${placedTorchesCount} torches during map enhancement.`);
if (CONSOLE_LOGGING) {
console.log(`[DungeonGenerator.enhanceMapWithVariations] Placed ${placedTorchesCount} torches during map enhancement.`);
}
return enhancedMap;
}
@@ -196,7 +205,9 @@ class DungeonGenerator {
const height = enhancedMap.length;
const width = enhancedMap[0].length;
console.log(`[DungeonGenerator.getTorchPositions] Searching for torch tile '${config.torchTile}' in a ${width}x${height} map.`);
if (CONSOLE_LOGGING) {
console.log(`[DungeonGenerator.getTorchPositions] Searching for torch tile '${config.torchTile}' in a ${width}x${height} map.`);
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
@@ -205,7 +216,9 @@ class DungeonGenerator {
}
}
}
console.log(`[DungeonGenerator.getTorchPositions] Found ${torches.length} torches. Positions: ${JSON.stringify(torches)}`);
if (CONSOLE_LOGGING) {
console.log(`[DungeonGenerator.getTorchPositions] Found ${torches.length} torches. Positions: ${JSON.stringify(torches)}`);
}
return torches;
}
+32 -13
View File
@@ -5,6 +5,9 @@ const Monster = require('./monster.js');
const DungeonGenerator = require('./dungeon.js');
const LightingAndFov = require('./lightingAndFov.js');
// Environment-based console logging control
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
class Game {
/**
* Create a new game instance
@@ -42,9 +45,11 @@ class Game {
...gameOptions
};
console.log(`[Game Constructor] Creating game for user ${user.id} (socket: ${socketId})`);
console.log(`[Game Constructor] Dimensions: ${width}x${height}`);
console.log(`[Game Constructor] Game config:`, JSON.stringify(this.gameConfig, null, 2));
if (CONSOLE_LOGGING) {
console.log(`[Game Constructor] Creating game for user ${user.id} (socket: ${socketId})`);
console.log(`[Game Constructor] Dimensions: ${width}x${height}`);
console.log(`[Game Constructor] Game config:`, JSON.stringify(this.gameConfig, null, 2));
}
this.initializeGame();
}
@@ -70,7 +75,9 @@ class Game {
}
initializeGame() {
console.log(`[Game.initializeGame] Initializing game with config:`, JSON.stringify(this.gameConfig, null, 2));
if (CONSOLE_LOGGING) {
console.log(`[Game.initializeGame] Initializing game with config:`, JSON.stringify(this.gameConfig, null, 2));
}
if (typeof this.gameConfig.width === 'undefined' || typeof this.gameConfig.height === 'undefined') {
console.error("[Game.initializeGame] CRITICAL: Width or Height is undefined in gameConfig!", this.gameConfig);
throw new Error(`Invalid game dimensions: width=${this.gameConfig.width}, height=${this.gameConfig.height}`);
@@ -120,7 +127,9 @@ class Game {
const newX = this.player.x + dx;
const newY = this.player.y + dy;
console.log(`Move: (${this.player.x},${this.player.y}) -> (${newX},${newY})`);
if (CONSOLE_LOGGING) {
console.log(`Move: (${this.player.x},${this.player.y}) -> (${newX},${newY})`);
}
// Check if the move is valid (not into a wall and within map bounds)
const primaryFloor = this.gameConfig.primaryFloor || "'1";
@@ -132,7 +141,9 @@ class Game {
(this.dungeon.map[newY][newX] === primaryFloor || this.dungeon.map[newY][newX] === secondaryFloor)) {
this.player.moveTo(newX, newY);
console.log(`Player moved to ${newX},${newY} in game for socket ${this.socketId}`);
if (CONSOLE_LOGGING) {
console.log(`Player moved to ${newX},${newY} in game for socket ${this.socketId}`);
}
// Update FOV after moving
this.updateFOV();
@@ -144,17 +155,23 @@ class Game {
}
if (this.dungeon.treasure && this.player.isAt(this.dungeon.treasure[0], this.dungeon.treasure[1]) && !this.player.hasTreasure) {
this.player.hasTreasure = true;
console.log(`🏆 TREASURE PICKUP: Player ${this.socketId} collected treasure at (${this.dungeon.treasure[0]}, ${this.dungeon.treasure[1]})`);
if (CONSOLE_LOGGING) {
console.log(`🏆 TREASURE PICKUP: Player ${this.socketId} collected treasure at (${this.dungeon.treasure[0]}, ${this.dungeon.treasure[1]})`);
}
this.dungeon.treasure = null;
console.log(`🗑️ TREASURE REMOVED: dungeon.treasure is now null for player ${this.socketId}`);
console.log(`Player ${this.socketId} collected treasure! hasTreasure: ${this.player.hasTreasure}`);
if (CONSOLE_LOGGING) {
console.log(`🗑️ TREASURE REMOVED: dungeon.treasure is now null for player ${this.socketId}`);
console.log(`Player ${this.socketId} collected treasure! hasTreasure: ${this.player.hasTreasure}`);
}
return { status: 'moved', event: 'treasure_found', player: this.player.getState(), visibleTiles: this.visibleTiles };
}
return { status: 'moved', player: this.player.getState(), visibleTiles: this.visibleTiles };
}
console.log(`Move BLOCKED: ${newX},${newY} - cell value: ${this.dungeon && this.dungeon.map[newY] ? this.dungeon.map[newY][newX] : 'undefined'}`);
if (CONSOLE_LOGGING) {
console.log(`Move BLOCKED: ${newX},${newY} - cell value: ${this.dungeon && this.dungeon.map[newY] ? this.dungeon.map[newY][newX] : 'undefined'}`);
}
return { status: 'invalid' };
}
@@ -174,9 +191,11 @@ class Game {
treasure: this.dungeon ? this.dungeon.treasure : null,
};
console.log("🎮 getState() sending entities - Monster:", state.monster, "Entrance:", state.entrance, "Exit:", state.exit, "Treasure:", state.treasure);
if (state.treasure === null) {
console.log("✅ TREASURE NULL: Confirmed treasure is null in getState() - treasure was picked up!");
if (CONSOLE_LOGGING) {
console.log("🎮 getState() sending entities - Monster:", state.monster, "Entrance:", state.entrance, "Exit:", state.exit, "Treasure:", state.treasure);
if (state.treasure === null) {
console.log("✅ TREASURE NULL: Confirmed treasure is null in getState() - treasure was picked up!");
}
}
return state;
+1 -14
View File
@@ -70,20 +70,7 @@ class Monster {
if (!player) return false;
// Check for direct overlap - monster on same tile as player
if (this.x === player.x && this.y === player.y) {
return true;
}
// Check for adjacent tiles (optional - if you want 1-tile proximity kills)
const dx = Math.abs(this.x - player.x);
const dy = Math.abs(this.y - player.y);
// If monster is adjacent (one tile away in any direction)
if ((dx <= 1 && dy === 0) || (dx === 0 && dy <= 1)) {
return true;
}
return false;
return this.x === player.x && this.y === player.y;
}
// Get monster state as object
+12 -8
View File
@@ -27,7 +27,9 @@ app.get('/', function(req, res) {
// Debug endpoint to receive client-side debug info
app.post('/debug', (req, res) => {
console.log('📝 CLIENT DEBUG INFO:', req.body);
if (debugManager.CONSOLE_LOGGING) {
console.log('📝 CLIENT DEBUG INFO:', req.body);
}
res.json({ received: true, timestamp: Date.now() });
});
@@ -49,13 +51,15 @@ io.on('connection', function(socket) {
// Debug function for registered users
function debugRegisteredUsers() {
console.log("📊 REGISTERED USERS DEBUG:");
const allUsers = require('./db/user').getAllUsers();
console.log(`Total registered users: ${allUsers.length}`);
allUsers.forEach(user => {
console.log(` - User ID: ${user.id}, Socket: ${user.socketId}, Client: ${user.clientId}`);
});
console.log(`Active games: ${activeGames.size}`);
if (debugManager.CONSOLE_LOGGING) {
console.log("📊 REGISTERED USERS DEBUG:");
const allUsers = require('./db/user').getAllUsers();
console.log(`Total registered users: ${allUsers.length}`);
allUsers.forEach(user => {
console.log(` - User ID: ${user.id}, Socket: ${user.socketId}, Client: ${user.clientId}`);
});
console.log(`Active games: ${activeGames.size}`);
}
}
// Regular debug logging
+122 -50
View File
@@ -22,16 +22,20 @@ class SocketHandlers {
* Initialize socket event handlers for a new connection
*/
handleConnection(socket) {
console.log('A user connected');
console.log(socket.client.id);
console.log(socket.handshake.address);
if (this.debugManager.CONSOLE_LOGGING) {
console.log('A user connected');
console.log(socket.client.id);
console.log(socket.handshake.address);
}
// Create and register user
new user.User(socket.id, socket.handshake.address);
const newUser = this.getUserBySocket(socket.id);
if (newUser) {
newUser.clientId = socket.client.id;
console.log(`User created with both socket.id (${socket.id}) and socket.client.id (${socket.client.id})`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`User created with both socket.id (${socket.id}) and socket.client.id (${socket.client.id})`);
}
}
// Send welcome and current status
@@ -39,7 +43,9 @@ class SocketHandlers {
// Send current block height
const currentBlock = this.debugManager.getCurrentBlockHeight();
console.log(`📈 Sending current block height ${currentBlock} to new connection ${socket.id}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`📈 Sending current block height ${currentBlock} to new connection ${socket.id}`);
}
this.io.to(socket.id).emit('blockheight', currentBlock);
// Send connection status
@@ -58,7 +64,9 @@ class SocketHandlers {
* Handle chat messages and game commands
*/
handleChatMessage(socket, msg) {
console.log('Message received:', msg);
if (this.debugManager.CONSOLE_LOGGING) {
console.log('Message received:', msg);
}
const command = msg.toLowerCase();
@@ -88,7 +96,9 @@ class SocketHandlers {
* Handle game entry request
*/
handleGameEntry(socket) {
console.log(`Player ${socket.id} requested to enter the dungeon - STARTING IMMEDIATELY`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player ${socket.id} requested to enter the dungeon - STARTING IMMEDIATELY`);
}
const currentUser = this.getUserBySocket(socket.id);
if (!currentUser) {
@@ -96,22 +106,30 @@ class SocketHandlers {
return;
}
console.log(`Found user for socket ${socket.id}, starting game immediately...`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Found user for socket ${socket.id}, starting game immediately...`);
}
try {
// For auto-entry in debug mode, player enters on current block
const currentBlock = this.debugManager.getCurrentBlockHeight();
currentUser.blockRec = currentBlock;
console.log(`🕒 AUTO-ENTRY: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🕒 AUTO-ENTRY: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
}
const game = this.createGameForUser(currentUser, 'standard');
const gameState = game.getState();
gameState.blockHeight = currentBlock;
console.log(`🎮 SENDING IMMEDIATE GAME_START to ${socket.id}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🎮 SENDING IMMEDIATE GAME_START to ${socket.id}`);
}
this.io.to(socket.id).emit('game_start', gameState);
console.log(`Game started immediately for player ${socket.id}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Game started immediately for player ${socket.id}`);
}
} catch (error) {
console.error(`Error creating game:`, error);
this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Error starting game: ' + error.message);
@@ -122,7 +140,9 @@ class SocketHandlers {
* Handle game queue request (typing "enter")
*/
handleGameQueue(socket) {
console.log(`Player ${socket.id} requested to enter the dungeon - ADDING TO QUEUE`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player ${socket.id} requested to enter the dungeon - ADDING TO QUEUE`);
}
const currentUser = this.getUserBySocket(socket.id);
if (!currentUser) {
@@ -156,14 +176,18 @@ class SocketHandlers {
this.broadcastManager.sendStatusUpdate(socket.id, 'queue',
`Added to queue! You will enter when block ${nextBlock} is found. Current block: ${currentBlock}`);
console.log(`🕒 QUEUE ENTRY: Player ${socket.id} queued for block ${nextBlock}. Queue length: ${this.WAITING_PLAYERS.length}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🕒 QUEUE ENTRY: Player ${socket.id} queued for block ${nextBlock}. Queue length: ${this.WAITING_PLAYERS.length}`);
}
}
/**
* Handle auto start request (start button)
*/
handleAutoStart(socket) {
console.log(`Player ${socket.id} requested auto-start via start button - STARTING IMMEDIATELY`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player ${socket.id} requested auto-start via start button - STARTING IMMEDIATELY`);
}
const currentUser = this.getUserBySocket(socket.id);
if (!currentUser) {
@@ -181,25 +205,35 @@ class SocketHandlers {
const waitingIndex = this.WAITING_PLAYERS.findIndex(p => p.serverId === socket.id);
if (waitingIndex !== -1) {
this.WAITING_PLAYERS.splice(waitingIndex, 1);
console.log(`🚀 AUTO-START: Removed ${socket.id} from waiting queue for immediate start`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🚀 AUTO-START: Removed ${socket.id} from waiting queue for immediate start`);
}
}
console.log(`Found user for socket ${socket.id}, starting game immediately...`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Found user for socket ${socket.id}, starting game immediately...`);
}
try {
// For auto-entry, player enters on current block
const currentBlock = this.debugManager.getCurrentBlockHeight();
currentUser.blockRec = currentBlock;
console.log(`🕒 AUTO-START: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🕒 AUTO-START: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
}
const game = this.createGameForUser(currentUser, 'standard');
const gameState = game.getState();
gameState.blockHeight = currentBlock;
console.log(`🎮 SENDING IMMEDIATE GAME_START to ${socket.id} (AUTO-START)`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🎮 SENDING IMMEDIATE GAME_START to ${socket.id} (AUTO-START)`);
}
this.io.to(socket.id).emit('game_start', gameState);
console.log(`Game started immediately for player ${socket.id} via auto-start`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Game started immediately for player ${socket.id} via auto-start`);
}
} catch (error) {
console.error(`Error creating game:`, error);
this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Error starting game: ' + error.message);
@@ -225,7 +259,9 @@ class SocketHandlers {
* Handle chat broadcast to all clients
*/
handleChatBroadcast(socket, msg) {
console.log(`💬 Broadcasting chat message from ${socket.id}: "${msg}"`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`💬 Broadcasting chat message from ${socket.id}: "${msg}"`);
}
const currentUser = this.getUserBySocket(socket.id);
const username = currentUser?.username || `User_${socket.id.substr(-4)}`;
@@ -242,12 +278,16 @@ class SocketHandlers {
* Handle player movement
*/
handlePlayerMove(socket, moveData) {
console.log(`Player move event received from ${socket.id}:`, moveData);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player move event received from ${socket.id}:`, moveData);
}
const currentUser = this.getUserBySocket(socket.id);
const game = this.activeGames.get(socket.id);
if (!currentUser || !game || game.gameState !== 'active') {
console.log(`Player move event from ${socket.id} ignored: No active game found for user.`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player move event from ${socket.id} ignored: No active game found for user.`);
}
return;
}
@@ -256,7 +296,9 @@ class SocketHandlers {
const lastMoveTime = this.playerMoveTimestamps.get(socket.id) || 0;
if (now - lastMoveTime < this.MOVE_COOLDOWN) {
console.log(`Move from ${socket.id} throttled - too soon after last move (${now - lastMoveTime}ms)`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Move from ${socket.id} throttled - too soon after last move (${now - lastMoveTime}ms)`);
}
return;
}
@@ -269,7 +311,9 @@ class SocketHandlers {
const moveResult = game.movePlayer(moveData.dx, moveData.dy);
if (!moveResult || moveResult.status !== 'moved') {
console.log(`Player move from ${socket.id} was invalid or resulted in no change.`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Player move from ${socket.id} was invalid or resulted in no change.`);
}
return;
}
@@ -326,7 +370,9 @@ class SocketHandlers {
* Handle client disconnection
*/
handleDisconnect(socket) {
console.log('User disconnected', socket.client.id);
if (this.debugManager.CONSOLE_LOGGING) {
console.log('User disconnected', socket.client.id);
}
// Clean up movement timestamps
this.playerMoveTimestamps.delete(socket.id);
@@ -347,7 +393,9 @@ class SocketHandlers {
* Handle debug ping
*/
handleDebugPing(socket, data) {
console.log(`Debug ping received from ${socket.client.id}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Debug ping received from ${socket.client.id}`);
}
socket.emit('debug_pong', {
message: "Hello from server!",
clientTime: data.time,
@@ -360,7 +408,9 @@ class SocketHandlers {
* Handle client registration
*/
handleRegisterClient(socket, data) {
console.log(`Client registered: ${socket.id} (server) <-> ${data.clientId} (client)`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Client registered: ${socket.id} (server) <-> ${data.clientId} (client)`);
}
this.clientSocketMap.set(data.clientId, socket.id);
this.clientSocketMap.set(socket.id, data.clientId);
@@ -378,17 +428,23 @@ class SocketHandlers {
* Get user by socket ID with fallback mapping
*/
getUserBySocket(socketId) {
console.log(`Looking up user with socketId: ${socketId}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Looking up user with socketId: ${socketId}`);
}
let foundUser = user.getUserBySocketId(socketId);
if (!foundUser && this.clientSocketMap.has(socketId)) {
const mappedId = this.clientSocketMap.get(socketId);
console.log(`Socket ID ${socketId} not found directly, trying mapped ID: ${mappedId}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Socket ID ${socketId} not found directly, trying mapped ID: ${mappedId}`);
}
foundUser = user.getUserBySocketId(mappedId);
}
console.log(`User lookup result for ${socketId}: ${foundUser ? "FOUND" : "NOT FOUND"}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`User lookup result for ${socketId}: ${foundUser ? "FOUND" : "NOT FOUND"}`);
}
return foundUser;
}
@@ -407,7 +463,9 @@ class SocketHandlers {
user.joinGame(game);
this.activeGames.set(user.id, game);
console.log(`[createGameForUser] Created ${gameType} game ${game.id} for user ${user.id}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`[createGameForUser] Created ${gameType} game ${game.id} for user ${user.id}`);
}
return game;
}
@@ -422,20 +480,22 @@ class SocketHandlers {
* Log game update debug information
*/
logGameUpdate(socketId, gameState) {
console.log(`🔍 GAME UPDATE DEBUG for ${socketId}:`);
console.log(` - Player position: (${gameState.player?.x}, ${gameState.player?.y})`);
console.log(` - Visible tiles keys: ${Object.keys(gameState.visibleTiles || {}).length} rows`);
console.log(` - Lighting data included: ${!!gameState.lighting}`);
if (gameState.lighting) {
const lightingTileCount = Object.keys(gameState.lighting).reduce((acc, yKey) =>
acc + Object.keys(gameState.lighting[yKey] || {}).length, 0);
console.log(` - Lighting tiles count: ${lightingTileCount}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🔍 GAME UPDATE DEBUG for ${socketId}:`);
console.log(` - Player position: (${gameState.player?.x}, ${gameState.player?.y})`);
console.log(` - Visible tiles keys: ${Object.keys(gameState.visibleTiles || {}).length} rows`);
console.log(` - Lighting data included: ${!!gameState.lighting}`);
if (gameState.lighting) {
const lightingTileCount = Object.keys(gameState.lighting).reduce((acc, yKey) =>
acc + Object.keys(gameState.lighting[yKey] || {}).length, 0);
console.log(` - Lighting tiles count: ${lightingTileCount}`);
}
console.log(` - Torch data included: ${!!gameState.torches}`);
if (gameState.torches) {
console.log(` - Torch count: ${gameState.torches.length}`);
}
console.log(`Sending game_update to ${socketId} after player move.`);
}
console.log(` - Torch data included: ${!!gameState.torches}`);
if (gameState.torches) {
console.log(` - Torch count: ${gameState.torches.length}`);
}
console.log(`Sending game_update to ${socketId} after player move.`);
}
// Queue management methods (for future block-based game entry)
@@ -444,19 +504,25 @@ class SocketHandlers {
* Start games for waiting players when a new block is found
*/
startGamesForWaiting(blockHeight) {
console.log(`Starting games for ${this.WAITING_PLAYERS.length} waiting players at block height ${blockHeight}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Starting games for ${this.WAITING_PLAYERS.length} waiting players at block height ${blockHeight}`);
}
while (this.WAITING_PLAYERS.length > 0) {
const playerEntry = this.WAITING_PLAYERS.shift();
const serverId = playerEntry.serverId;
console.log(`Processing player: server=${serverId}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Processing player: server=${serverId}`);
}
const currentUser = this.getUserBySocket(serverId);
if (currentUser) {
currentUser.blockRec = blockHeight;
console.log(`🕒 QUEUE ENTRY: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🕒 QUEUE ENTRY: Player enters on block ${currentUser.blockRec}, will die when block ${currentUser.blockRec + 1} starts`);
}
try {
const game = this.createGameForUser(currentUser, 'standard');
@@ -464,9 +530,13 @@ class SocketHandlers {
const gameState = game.getState();
gameState.blockHeight = blockHeight;
console.log(`🎮 SENDING GAME_START to ${serverId}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`🎮 SENDING GAME_START to ${serverId}`);
}
this.io.to(serverId).emit('game_start', gameState);
console.log(`Game started for player ${serverId}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`Game started for player ${serverId}`);
}
} catch (error) {
console.error(`Error creating game:`, error);
this.io.to(serverId).emit('message', 'Error starting game: ' + error.message);
@@ -486,7 +556,9 @@ class SocketHandlers {
const user = this.getUserBySocket(socketId);
if (user && user.blockRec && currentHeight > user.blockRec) {
console.log(`💀 GAME TIMEOUT for player ${socketId}: entered on block ${user.blockRec}, died on block ${currentHeight}`);
if (this.debugManager.CONSOLE_LOGGING) {
console.log(`💀 GAME TIMEOUT for player ${socketId}: entered on block ${user.blockRec}, died on block ${currentHeight}`);
}
game.gameState = 'lost';
this.io.to(socketId).emit('game_over', {
+17 -1
View File
@@ -4,9 +4,25 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"start": "NODE_ENV=production node index.js",
"dev": "NODE_ENV=development node index.js",
"debug": "NODE_ENV=debug node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"config": {
"debug": {
"enabled": false,
"console_logging": false,
"debug_hotkeys": false,
"simulated_blocks": false
},
"production": {
"enabled": true,
"console_logging": false,
"debug_hotkeys": false,
"simulated_blocks": false
}
},
"author": "jw",
"license": "ISC",
"dependencies": {
+6 -1
View File
@@ -1,6 +1,9 @@
var axios = require('axios');
var request = require('request');
// Environment-based console logging control
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
/*List of RPC calls
Daemon -
Get blockheight: "get_block_count"
@@ -33,7 +36,9 @@ function daemonCall(method, params, callback, io) {
json: body
}, function (error, res, body) {
if (error) {
console.log("Daemon connection error:", error.message);
if (CONSOLE_LOGGING) {
console.log("Daemon connection error:", error.message);
}
callback(null);
return;
}