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
+62 -37
View File
@@ -88,39 +88,52 @@ The backend has been refactored into focused modules organized by domain for mai
- **Debug/Production Split**: Development and production logic properly separated
- **Maintainable**: 600-line monolith reduced to focused 69-line orchestrator
### Frontend Structure (`html/`)
### Frontend Structure (`html/js/`)
#### Modular JavaScript Architecture:
The frontend has been reorganized into a logical directory structure for better maintainability:
1. **DisplayManager.js** - Display & Canvas Management
- ROT.Display initialization and setup
- Display state management and clearing
- Tile-based rendering system
#### **Organized JavaScript Architecture:**
2. **ScreenManager.js** - Screen State Management
- Welcome screen with block simulation
- Win/lose screens and waiting screens
- Centered text drawing utilities
**Core Game Logic (`core/`)**
- **game.js** - Main Game Controller coordinating all modules with clean APIs
- **gameState.js** - Game State Management (player, map, monster, item data)
- **options.js** - Game configuration and settings
3. **RenderEngine.js** - Game Rendering Engine
- Game screen rendering and object drawing
- Field of view rendering and visibility checks
- Drawing game objects (player, monsters, items, terrain)
**Display & Rendering (`display/`)**
- **displayManager.js** - Display & Canvas Management (ROT.Display initialization)
- **screenManager.js** - Screen State Management (welcome, win/lose, waiting screens)
- **renderEngine.js** - Game Rendering Engine (FOV rendering, drawing game objects)
- **waitingScreenAnimator.js** - Animated waiting screens during block progression
4. **GameState.js** - Game State Management
- Player, map, monster, item data management
- Game state updates and validation
- Field of view computation and player movement logic
**User Interface (`ui/`)**
- **ui.js** - User interface management and chat functionality
- **teletype.js** - Typewriter-style text effects
5. **game.js** - Main Game Controller
- Coordinates all modules with clean APIs
- Provides backward-compatible interface
- Handles game initialization and flow
**Input Handling (`input/`)**
- **inputHandler.js** - Keyboard/mouse input with movement throttling
6. **Additional Modules**:
- **inputHandler.js** - Keyboard/mouse input with movement throttling
- **socketHandlers.js** - WebSocket communication with initialization protection
- **ui.js** - User interface management and chat functionality
**Network Communication (`network/`)**
- **socketHandlers.js** - WebSocket communication with initialization protection
**External Libraries (`lib/`)**
- **jquery-3.4.1.min.js** - jQuery library
- **rot.js** & **rot.min.js** - ROT.js library for roguelike mechanics
## Recent Updates & Production Readiness
### Console Logging Cleanup
- **Backend**: Implemented conditional logging using `process.env.NODE_ENV` checks
- **Frontend**: Removed verbose console.log statements while preserving error logging
- **Production Ready**: Clean console output in production mode controlled by environment variables
### Monster Collision Fix
- **Exact Tile Collision**: Fixed monster kill logic to only trigger when monster and player occupy the exact same tile
- **Removed Adjacent Kills**: Players are no longer killed when monsters are merely adjacent
### Code Organization
- **Frontend Restructure**: Organized JavaScript files into logical directories (`core/`, `display/`, `ui/`, `input/`, `network/`, `lib/`)
- **Better Maintainability**: Clear separation of concerns with modular file structure
- **Updated HTML**: Both `index.html` and `debug.html` updated to reference new file paths
## Socket Event Architecture
@@ -228,7 +241,7 @@ wowngeon/
│ │ ├── game.js # Game class with factory methods
│ │ ├── dungeon.js # Dungeon generation system
│ │ ├── player.js # Player state management
│ │ ├── monster.js # Monster AI
│ │ ├── monster.js # Monster AI with exact collision detection
│ │ ├── lightingAndFov.js # Field of view calculations
│ │ ├── rot.js # ROT.js library
│ │ └── rot.min.js # ROT.js minified
@@ -244,16 +257,28 @@ wowngeon/
│ └── debugManager.js # Debug/production mode handling
├── html/ # Frontend web interface
│ ├── index.html # Main game page
│ ├── js/ # Modular JavaScript
│ │ ├── displayManager.js # Display management
│ │ ├── screenManager.js # Screen states
│ │ ├── renderEngine.js # Game rendering
│ │ ├── gameState.js # Game state management
│ │ ├── game.js # Main game controller
│ │ ├── inputHandler.js # Input handling
│ │ ├── socketHandlers.js # WebSocket communication
│ │ ├── ui.js # User interface
│ │ └── options.js # Game configuration
│ ├── debug.html # Debug testing page
│ ├── js/ # Organized JavaScript modules
│ │ ├── core/ # Core game logic
│ │ │ ├── game.js # Main game controller
│ │ │ ├── gameState.js # Game state management
│ │ │ └── options.js # Game configuration
│ │ ├── display/ # Display and rendering
│ │ │ ├── displayManager.js # Display management
│ │ │ ├── screenManager.js # Screen states
│ │ │ ├── renderEngine.js # Game rendering
│ │ │ └── waitingScreenAnimator.js # Animated screens
│ │ ├── ui/ # User interface
│ │ │ ├── ui.js # UI management
│ │ │ └── teletype.js # Text effects
│ │ ├── input/ # Input handling
│ │ │ └── inputHandler.js # Keyboard/mouse input
│ │ ├── network/ # Network communication
│ │ │ └── socketHandlers.js # WebSocket communication
│ │ └── lib/ # External libraries
│ │ ├── jquery-3.4.1.min.js
│ │ ├── rot.js
│ │ └── rot.min.js
│ ├── styles/ # CSS styling
│ └── tiles.png # Game tile graphics
└── test/ # Test files
+8 -8
View File
@@ -51,16 +51,16 @@
</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>
<script src="js/lib/jquery-3.4.1.min.js"></script>
<script src="js/lib/rot.min.js"></script>
<script src="js/core/options.js"></script>
<script src="js/ui/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 src="js/core/game.js"></script>
<script src="js/ui/ui.js"></script>
<script src="js/network/socketHandlers.js"></script>
<script src="js/input/inputHandler.js"></script>
<script>
// Capture console messages
+13 -13
View File
@@ -14,23 +14,23 @@
</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>
<script src="js/lib/jquery-3.4.1.min.js"></script>
<script src="js/lib/rot.min.js"></script>
<script src="js/core/options.js"></script>
<script src="js/ui/teletype.js"></script>
<!-- Modular game components (order matters for dependencies) -->
<script src="js/displayManager.js"></script>
<script src="js/waitingScreenAnimator.js"></script>
<script src="js/screenManager.js"></script>
<script src="js/renderEngine.js"></script>
<script src="js/gameState.js"></script>
<script src="js/game.js"></script>
<script src="js/display/displayManager.js"></script>
<script src="js/display/waitingScreenAnimator.js"></script>
<script src="js/display/screenManager.js"></script>
<script src="js/display/renderEngine.js"></script>
<script src="js/core/gameState.js"></script>
<script src="js/core/game.js"></script>
<!-- Other modules -->
<script src="js/ui.js"></script>
<script src="js/socketHandlers.js"></script>
<script src="js/inputHandler.js"></script>
<script src="js/ui/ui.js"></script>
<script src="js/network/socketHandlers.js"></script>
<script src="js/input/inputHandler.js"></script>
</head>
<body>
<div class="container">
+1 -22
View File
@@ -3,7 +3,7 @@
if (typeof window !== 'undefined' && !window.socket) {
window.socket = {
emit: function(event, data) {
console.log("[Mock Socket] Would emit:", event, data);
// Mock socket emit - removed debug logging
}
};
}
@@ -16,8 +16,6 @@ var Game = {
_maxLogMessages: 5,
init: function() {
console.log("Game.init called - Modular version");
// Update screen dimensions from options
if (typeof options !== 'undefined') {
this._screenWidth = options.width || 25;
@@ -52,21 +50,16 @@ var Game = {
console.error("Game: Cannot start game, display not ready.");
return false;
}
console.log("Game: startGame called. PlayerData:", playerData, "MapData:", mapData, "InitialVisibleTiles:", initialVisibleTiles);
console.log("🔥 LIGHTING DATA received in startGame:", lightingData);
console.log("🔦 TORCH DATA received in startGame:", torchData);
DisplayManager.clearDisplay();
// Force clear all display caches and artifacts
if (typeof DisplayManager !== 'undefined' && DisplayManager.forceClearToBlack) {
console.log("✅ Force clearing display to prevent artifacts...");
DisplayManager.forceClearToBlack();
}
// Stop the block simulation to prevent welcome screen from interfering
if (typeof ScreenManager !== 'undefined' && ScreenManager.stopBlockSimulation) {
console.log("✅ Stopping block simulation...");
ScreenManager.stopBlockSimulation();
}
@@ -74,7 +67,6 @@ var Game = {
GameState.setGameActive(true);
// Clear any previous game state but preserve what we need for initialization
console.log("✅ Clearing previous game state (but preserving server data)...");
GameState._exploredTiles = {};
// Don't clear _visibleTiles yet - let initializeMap handle it properly
GameState._map = {};
@@ -97,11 +89,9 @@ var Game = {
// Initialize lighting and torch data
if (lightingData) {
GameState._lighting = lightingData;
console.log("🔥 GameState: Lighting data stored with", Object.keys(lightingData).length, "rows");
}
if (torchData) {
GameState._torches = torchData;
console.log("🔦 GameState: Torch data stored with", torchData.length, "torches");
}
// Initialize map and validate player position
@@ -122,7 +112,6 @@ var Game = {
GameState._scheduler.add(GameState._player, true);
console.log("Player coordinates before drawing game screen:", GameState._player.x, GameState._player.y);
if (!GameState._map[GameState._player.y] || GameState._map[GameState._player.y][GameState._player.x] === undefined) {
console.error(`Player position (${GameState._player.x}, ${GameState._player.y}) is STILL invalid before drawing. Map issue?`);
ScreenManager.drawCenteredText(10, "Error: Player invalid for draw!");
@@ -130,7 +119,6 @@ var Game = {
}
this._drawGameScreen();
console.log("Game started successfully and initial screen drawn.");
return true;
} catch (err) {
@@ -155,7 +143,6 @@ var Game = {
// Redraw the game screen if any relevant data changed
if (needsRedraw) {
console.log("Redrawing game screen due to game update.");
this._drawGameScreen();
}
},
@@ -168,14 +155,6 @@ var Game = {
if (!this._ensureDisplay()) return;
const gameState = GameState.getGameStateForRender();
// Debug: Verify lighting data is included in render state
console.log("🎨 _drawGameScreen() passing lighting data:", {
hasLighting: !!gameState.lighting,
lightingKeys: gameState.lighting ? Object.keys(gameState.lighting).length : 0,
hasTorches: !!gameState.torches,
torchCount: gameState.torches ? gameState.torches.length : 0
});
RenderEngine.drawGameScreen(gameState);
},
@@ -68,7 +68,6 @@ var GameState = {
// Try to initialize from mapData.tiles
if (mapData && mapData.tiles && typeof mapData.tiles === 'object' && Object.keys(mapData.tiles).length > 0) {
console.log("Initializing map from mapData.tiles:", mapData.tiles);
for (var yKey in mapData.tiles) {
const y = parseInt(yKey);
this._map[y] = {};
@@ -78,11 +77,9 @@ var GameState = {
}
}
mapInitialized = true;
console.log("Game map initialized from mapData.tiles:", this._map);
}
// Try array-based mapData
else if (mapData && Array.isArray(mapData) && mapData.length > 0) {
console.warn("Received array-based mapData, attempting to convert.");
for (let y = 0; y < mapData.length; y++) {
this._map[y] = {};
if (mapData[y] && Array.isArray(mapData[y])) {
@@ -92,11 +89,9 @@ var GameState = {
}
}
mapInitialized = true;
console.log("Game map initialized from array-based mapData:", this._map);
}
// Try initialVisibleTiles
else if (initialVisibleTiles && typeof initialVisibleTiles === 'object' && Object.keys(initialVisibleTiles).length > 0) {
console.log("Initializing _visibleTiles from server-sent initialVisibleTiles and inferring _map for FOV.");
this._visibleTiles = JSON.parse(JSON.stringify(initialVisibleTiles)); // Deep copy
for (const yKey in this._visibleTiles) {
@@ -108,8 +103,6 @@ var GameState = {
}
}
mapInitialized = true;
console.log("Game map partially initialized for FOV from initialVisibleTiles:", this._map);
console.log("_visibleTiles set directly from initialVisibleTiles:", this._visibleTiles);
}
// Create default map if nothing worked
@@ -131,7 +124,6 @@ var GameState = {
this._map[this._player.y][this._player.x] = 0; // Force floor
}
}
console.log("Default game map created. Player position:", this._player.x, this._player.y);
}
return mapInitialized;
@@ -150,7 +142,6 @@ var GameState = {
if (tile === 0 || tile === "'1" || tile === "'2") {
this._player.x = x_scan;
this._player.y = y_scan;
console.warn(`Player moved to fallback position: (${this._player.x}, ${this._player.y})`);
foundFallback = true;
break;
}
@@ -191,7 +182,6 @@ var GameState = {
// NOTE: Don't call updateExploredTiles() here on initial game load
// Explored tiles should only be updated when player moves, not on first FOV computation
console.log("Initial FOV computed/processed. Visible tiles count:", Object.keys(this._visibleTiles).reduce((acc, yKey) => acc + Object.keys(this._visibleTiles[yKey]).length, 0));
},
updateExploredTiles: function() {
@@ -207,8 +197,6 @@ var GameState = {
},
updateGameState: function(data) {
console.log("🎲 GameState.updateGameState received data:", data);
if (!this._gameActive) {
console.warn("GameState.updateGameState called, but game is not active. Ignoring update.");
return false;
@@ -255,33 +243,25 @@ var GameState = {
// Update lighting and torch data
if (data.lighting !== undefined) {
console.log("🔥 BEFORE UPDATE: this._lighting has", this._lighting ? Object.keys(this._lighting).length : 0, "rows");
console.log("🔥 NEW DATA: data.lighting has", Object.keys(data.lighting).length, "rows");
console.log("🔥 LIGHTING DATA SAMPLE:", JSON.stringify(data.lighting).substring(0, 200));
this._lighting = data.lighting;
console.log("🔥 AFTER UPDATE: this._lighting has", this._lighting ? Object.keys(this._lighting).length : 0, "rows");
needsRedraw = true;
}
if (data.torches !== undefined) {
this._torches = data.torches;
needsRedraw = true;
console.log("🔦 GameState: Updated torch data with", data.torches.length, "torches");
}
// Update visible tiles (most critical for movement feedback)
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);
}
@@ -313,19 +293,18 @@ var GameState = {
// Move the player
this._player.x = newX;
this._player.y = newY;
console.log("Player moved to:", this._player.x, this._player.y);
// Update visibility and redraw
this.updateExploredTiles();
return true;
} else {
console.log("Move blocked by wall or invalid map data at:", newX, newY);
return false;
}
},
// Debug functions
// Debug functions
debugPrintMap: function(screenWidth, screenHeight) {
// Map debugging - preserve console.log for debug function
console.log("Current game map:");
for (let y = 0; y < screenHeight; y++) {
let row = "";
@@ -341,6 +320,7 @@ var GameState = {
},
debugTileMapping: function() {
// Tile mapping debugging - preserve console.log for debug function
const testValues = [0, 1, undefined, null];
for (const val of testValues) {
const char = (val === 1) ? '#' : "\'";
@@ -357,7 +337,8 @@ var GameState = {
return;
}
console.log("⚠️ LOCAL FOV COMPUTATION (should only be used for testing without server)");
// Warning for local FOV computation (keep for debugging)
// console.log("⚠️ LOCAL FOV COMPUTATION (should only be used for testing without server)");
const oldVisibleTiles = JSON.parse(JSON.stringify(this._visibleTiles));
this._visibleTiles = {};
@@ -376,22 +357,10 @@ var GameState = {
if (!this._exploredTiles[y]) this._exploredTiles[y] = {};
this._exploredTiles[y][x] = this._map[y] && this._map[y][x] !== undefined ? this._map[y][x] : 0;
}.bind(this));
console.log("FOV computed for player at:", this._player.x, this._player.y);
console.log("Visible tiles:", Object.keys(this._visibleTiles).length);
},
// Get game state data for rendering
getGameStateForRender: function() {
// Debug: Log the actual lighting data being returned
console.log("🔍 getGameStateForRender() lighting check:", {
lightingExists: !!this._lighting,
lightingKeys: this._lighting ? Object.keys(this._lighting).length : 0,
lightingRef: this._lighting,
torchExists: !!this._torches,
torchCount: this._torches ? this._torches.length : 0
});
const renderState = {
map: this._map,
player: this._player,
@@ -408,7 +377,6 @@ var GameState = {
torches: this._torches
};
console.log("🔍 getGameStateForRender() RETURNING lighting with", renderState.lighting ? Object.keys(renderState.lighting).length : 0, "keys");
return renderState;
},
@@ -120,9 +120,9 @@ var RenderEngine = {
const isCurrentlyVisible = this.isVisible(wx, wy, visibleTiles);
// Added log to inspect lightingAlpha for visible, lit tiles
if (isCurrentlyVisible && lightingAlpha > 0.01) { // Using 0.01 to catch small, non-zero alphas
console.log(`RenderEngine TRACE: Tile (${wx},${wy}), Visible: ${isCurrentlyVisible}, lightingAlpha: ${lightingAlpha.toFixed(3)}, from: ${lighting[wy] ? lighting[wy][wx].toFixed(3) : 'N/A'}`);
}
// if (isCurrentlyVisible && lightingAlpha > 0.01) { // Using 0.01 to catch small, non-zero alphas
// console.log(`RenderEngine TRACE: Tile (${wx},${wy}), Visible: ${isCurrentlyVisible}, lightingAlpha: ${lightingAlpha.toFixed(3)}, from: ${lighting[wy] ? lighting[wy][wx].toFixed(3) : 'N/A'}`);
// }
if (isCurrentlyVisible) {
if (lightingAlpha > 0) {
@@ -115,13 +115,10 @@ var ScreenManager = {
// Hide animation button on welcome screen
this.hideAnimationButton();
// Debug button (shown only in development)
// Debug mode detection (for future use)
const isDebugMode = window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1' ||
window.location.protocol === 'file:';
if (isDebugMode) {
this.drawCenteredText(this._screenHeight - 3, "[DEBUG: Press D]");
}
},
@@ -135,7 +132,6 @@ var ScreenManager = {
// Start simulated block mining (30 second intervals)
startBlockSimulation: function() {
console.log("Starting block simulation...");
this._currentBlockHeight = Math.floor(Math.random() * 1000000) + 3200000; // Realistic Wownero block height
this._waitingForBlock = true;
@@ -179,7 +175,6 @@ var ScreenManager = {
// Stop block simulation
stopBlockSimulation: function() {
console.log("Stopping block simulation and clearing all intervals...");
if (this._blockTimer) {
clearInterval(this._blockTimer);
this._blockTimer = null;
@@ -238,8 +233,6 @@ var ScreenManager = {
const animationEnabled = (typeof WaitingScreenAnimator !== 'undefined') ?
WaitingScreenAnimator.isAnimationEnabled() : false;
console.log("🎬 Drawing waiting screen, animation enabled:", animationEnabled);
// Delegate to WaitingScreenAnimator with proper parameters
if (typeof WaitingScreenAnimator !== 'undefined') {
if (animationEnabled) {
@@ -286,9 +279,9 @@ var ScreenManager = {
const animationEnabled = (typeof WaitingScreenAnimator !== 'undefined') ?
WaitingScreenAnimator.isAnimationEnabled() : false;
animButton.textContent = animationEnabled ? '🎬 DISABLE ANIMATION' : '🎬 ENABLE ANIMATION';
console.log("✅ Animation button shown:", animButton.textContent);
} else {
console.warn("❌ Animation button element not found!");
// Animation button element not found - non-critical warning
// console.warn("❌ Animation button element not found!");
}
},
@@ -303,14 +296,13 @@ var ScreenManager = {
let animButton = document.getElementById('animationToggleButton');
if (!animButton) {
console.warn("🔧 Animation button not found, checking if it exists in DOM...");
// Try to find it by class or create it if missing
// Animation button not found - create or handle missing button
const statusDiv = document.querySelector('.status');
if (statusDiv) {
const existingButtons = statusDiv.querySelectorAll('button');
console.log("Found buttons in status div:", existingButtons.length);
// Check existing buttons for debugging
for (let btn of existingButtons) {
console.log("Button:", btn.id, btn.textContent);
// Button discovery for debugging
}
}
return false;
@@ -9,11 +9,9 @@ const InputHandler = {
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();
@@ -30,12 +28,9 @@ const InputHandler = {
// Don't send empty messages
if (!msg) return false;
console.log("📝 SENDING CHAT:", msg);
// If the message is "enter", always send it to server
// The server will handle queueing logic and timing
if (msg.toLowerCase() === 'enter') {
console.log("🔑 'ENTER' COMMAND DETECTED - sending to server");
socket.emit('chat message', msg);
// Show appropriate screen based on current state
@@ -44,12 +39,10 @@ const InputHandler = {
window.location.protocol === 'file:';
if (isDebugMode || ScreenManager.canEnterGame()) {
console.log("✅ Can enter immediately - showing waiting screen");
if (typeof ScreenManager !== 'undefined' && ScreenManager.drawWaitingScreen) {
ScreenManager.drawWaitingScreen();
}
} else {
console.log("⏳ Will be queued - showing queue message");
$('#messages').append($('<li style="color: #ff0;">').text("* You have been added to the queue! Game will start after next block."));
UI.scrollChat();
}
@@ -93,7 +86,6 @@ const InputHandler = {
}
if (moved) {
console.log(`🎹 KEYDOWN: dx=${dx}, dy=${dy}, key=${e.key}, time=${Date.now()}`);
e.preventDefault(); // Prevent page scrolling
// Implement movement throttling to prevent rapid-fire movement
@@ -101,18 +93,15 @@ const InputHandler = {
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;
}
@@ -121,47 +110,19 @@ const InputHandler = {
}
} else {
// Game display has focus but game is not active (welcome screen)
// Check for debug key 'D' to start immediately
if (e.key === 'D' || e.key === 'd') {
// Check if we're in debug mode (localhost)
const isDebugMode = window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1' ||
window.location.protocol === 'file:';
if (isDebugMode) {
console.log("🔧 DEBUG: 'D' key pressed - starting game immediately");
e.preventDefault();
// Emit enter command to start game immediately
socket.emit('chat message', 'enter');
// Show waiting screen while game starts
if (typeof ScreenManager !== 'undefined' && ScreenManager.drawWaitingScreen) {
ScreenManager.drawWaitingScreen();
}
// Add debug message to chat
$('#messages').append($('<li style="color: #0f0;">').text("🔧 DEBUG: Starting game immediately..."));
UI.scrollChat();
} else {
console.log("Debug key pressed but not in debug mode");
}
} else if (e.key === 'A' || e.key === 'a') {
// Only handle animation toggle
if (e.key === 'A' || e.key === 'a') {
// Toggle animation on waiting screen
console.log("🎬 'A' key pressed - toggling animation");
e.preventDefault();
if (typeof ScreenManager !== 'undefined') {
ScreenManager.toggleAnimation();
}
} else {
console.log("Game display has focus, but Game is not active.");
}
}
} else if (e.key === 'Enter' && document.activeElement !== $('#chatInput')[0]) {
// If Enter is pressed and chat is not focused
if (typeof Game !== 'undefined' && !Game._gameActive) {
// On welcome screen - start the game
console.log("🔑 Enter key pressed on welcome screen - starting game");
e.preventDefault();
const isDebugMode = window.location.hostname === 'localhost' ||
@@ -171,12 +132,10 @@ const InputHandler = {
socket.emit('chat message', 'enter');
if (isDebugMode || ScreenManager.canEnterGame()) {
console.log("✅ Can enter immediately - showing waiting screen");
if (typeof ScreenManager !== 'undefined' && ScreenManager.drawWaitingScreen) {
ScreenManager.drawWaitingScreen();
}
} else {
console.log("⏳ Will be queued - showing queue message");
$('#messages').append($('<li style="color: #ff0;">').text("* You have been added to the queue! Game will start after next block."));
UI.scrollChat();
}
@@ -196,12 +155,10 @@ const InputHandler = {
setupClickHandlers: function() {
// Add click handling for the HTML START button
$('#startButton').click(function(e) {
console.log("🖱️ START button clicked - auto-starting game");
// Use the new auto_start event for immediate entry
socket.emit('auto_start');
console.log("✅ Auto-start requested - showing waiting screen");
if (typeof ScreenManager !== 'undefined' && ScreenManager.drawWaitingScreen) {
ScreenManager.drawWaitingScreen();
}
@@ -213,7 +170,6 @@ const InputHandler = {
// Add click handling for the animation toggle button
$('#animationToggleButton').click(function(e) {
console.log("🎬 Animation toggle button clicked");
if (typeof ScreenManager !== 'undefined' && ScreenManager.toggleAnimation) {
ScreenManager.toggleAnimation();
@@ -235,7 +191,6 @@ const InputHandler = {
if (toggleButton) {
toggleButton.addEventListener('click', function() {
try {
console.log("Display mode switching is no longer needed - modes are equivalent");
toggleButton.textContent = 'Mode switching disabled';
toggleButton.disabled = true;
} catch (e) {
View File
@@ -6,7 +6,6 @@ const SocketHandlers = {
init: function() {
if (this._initialized) {
console.warn("SocketHandlers.init() called multiple times - ignoring duplicate call");
return;
}
@@ -15,7 +14,6 @@ const SocketHandlers = {
return;
}
console.log("SocketHandlers: Initializing for the first time...");
this.registerEventHandlers();
this._initialized = true;
},
@@ -40,7 +38,6 @@ const SocketHandlers = {
},
onConnect: function() {
console.log("Connected with socket ID:", socket.id);
// Tell server our client ID
socket.emit('register_client', {
@@ -63,7 +60,6 @@ const SocketHandlers = {
onStatusUpdate: function(data) {
// Handle player-specific status updates
console.log("📨 STATUS UPDATE received:", data);
// Display status message with appropriate styling
const statusClass = data.type === 'error' ? 'error' : 'status';
@@ -73,7 +69,6 @@ const SocketHandlers = {
onChatBroadcast: function(data) {
// Handle chat messages broadcast to all players
console.log("💬 CHAT BROADCAST received:", data);
const timestamp = new Date(data.timestamp || Date.now()).toLocaleTimeString();
const chatMsg = `[${timestamp}] ${data.username || 'Anonymous'}: ${data.message}`;
@@ -83,7 +78,6 @@ const SocketHandlers = {
},
onWaitingStatus: function(data) {
console.log("🕒 WAITING STATUS received:", data);
if (data.status === 'waiting') {
$('#messages').append($('<li style="color:#ff0;">').text(data.message));
@@ -97,15 +91,6 @@ const SocketHandlers = {
},
onGameStart: function(data) {
console.log("🎮 Game start received with data:", data);
console.log("🔍 DETAILED DATA CHECK:");
console.log(" - Player:", data?.player);
console.log(" - Map keys:", data?.map ? Object.keys(data.map).length : "NO MAP");
console.log(" - Monster:", data?.monster);
console.log(" - Items:", data?.items);
console.log(" - VisibleTiles keys:", data?.visibleTiles ? Object.keys(data.visibleTiles).length : "NO VISIBLE TILES");
console.log(" - Lighting keys:", data?.lighting ? Object.keys(data.lighting).length : "NO LIGHTING");
console.log(" - Torches:", data?.torches ? data.torches.length : "NO TORCHES (expected - lighting calculated server-side)");
$('#messages').append($('<li class="game-start">').text("Starting game..."));
@@ -122,16 +107,11 @@ const SocketHandlers = {
try {
// Pass all game data including lighting and torches
var success = Game.startGame(data.player, data.map, data.monster, data.items, data.visibleTiles, data.lighting, data.torches);
console.log("Game start result:", success ? "SUCCESS" : "FAILED");
if (!success) {
$('#messages').append($('<li class="error">').text("Game start failed. Check console for details."));
console.log("❌ GAME START FAILED - reverting to welcome screen");
if (typeof Game !== 'undefined' && Game._drawWelcomeScreen) Game._drawWelcomeScreen();
} else {
// Draw the initial game screen - the game draws itself after startGame()
console.log("Game started successfully, initial screen should be drawn");
// Shift focus to the game display area after successful game start
$('#game-display').focus();
UI.updateFocusIndicator();
@@ -144,39 +124,9 @@ const SocketHandlers = {
},
onGameUpdate: function(data) {
// Debug log to see what data we're receiving
console.log("🎮 GAME UPDATE received with keys:", Object.keys(data));
// Debug lighting data specifically
if (data.lighting && Object.keys(data.lighting).length > 0) {
console.log("🔥 GAME UPDATE: lighting data received with", Object.keys(data.lighting).length, "rows");
} else {
console.log("⚠️ GAME UPDATE: NO lighting data in update");
}
// Debug torch data specifically
if (data.torches && data.torches.length > 0) {
console.log("🔦 GAME UPDATE: torch data received with", data.torches.length, "torches");
} else {
console.log("ℹ️ GAME UPDATE: No torch data (expected - lighting calculated server-side)");
}
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 (window.GameDebug) window.GameDebug.updateDebugDisplay("SOCKET: Received game update with visibleTiles");
}
if (typeof Game !== 'undefined' && Game._gameActive) {
@@ -185,7 +135,6 @@ const SocketHandlers = {
},
onGameOver: function(data) {
console.log("🎮 GAME OVER received:", data);
// Update game state based on outcome
if (typeof Game !== 'undefined') {
@@ -224,9 +173,7 @@ const SocketHandlers = {
}
// Auto-return to title screen after 30 seconds
console.log("⏰ Setting 30-second timer to return to title screen...");
setTimeout(() => {
console.log("⏰ 30 seconds elapsed - returning to title screen");
$('#messages').append($('<li style="color:#888;">').text("Returning to title screen..."));
UI.scrollChat();
@@ -250,7 +197,6 @@ const SocketHandlers = {
},
onQueueCancelled: function() {
console.log("Queue cancelled, returning to welcome screen");
if (typeof Game !== 'undefined' && Game._drawWelcomeScreen) {
Game._drawWelcomeScreen();
@@ -260,7 +206,6 @@ const SocketHandlers = {
},
onBlockHeight: function(height) {
console.log(`📈 BLOCK HEIGHT: ${height}`);
UI.updateBlockHeight(height);
$('#statusValue').text('Connected');
$('#statusValue').css('color', '#0f0');
-3
View File
@@ -21,15 +21,12 @@ const UI = {
if (document.activeElement === gameDisplay[0]) {
gameDisplay.css('outline', '2px solid yellow');
chatInput.css('outline', 'none');
console.log("Focus: Game Display");
} else if (document.activeElement === chatInput[0]) {
chatInput.css('outline', '2px solid cyan');
gameDisplay.css('outline', 'none');
console.log("Focus: Chat Input");
} else {
gameDisplay.css('outline', 'none');
chatInput.css('outline', 'none');
console.log("Focus: None or Other");
}
},
+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;
}
+1 -14
View File
@@ -65,20 +65,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