mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-12-02 11:54:04 +01:00
ok game is working-ish
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
const ROT = require('./rot.js');
|
||||
|
||||
/**
|
||||
* Dungeon generation utilities
|
||||
*/
|
||||
class DungeonGenerator {
|
||||
static generate(width, height) {
|
||||
// Create dungeon using ROT.js Map.Digger
|
||||
const digger = new ROT.Map.Digger(width, height, {
|
||||
roomWidth: [3, 9],
|
||||
roomHeight: [3, 7],
|
||||
corridorLength: [2, 6],
|
||||
dugPercentage: 0.2
|
||||
});
|
||||
|
||||
// Initialize the empty map with walls (1)
|
||||
const map = Array(height).fill().map(() => Array(width).fill(1));
|
||||
|
||||
// Fill in floors (0) using digger's callback
|
||||
digger.create((x, y, value) => {
|
||||
// value: 0 = floor, 1 = wall
|
||||
map[y][x] = value;
|
||||
});
|
||||
|
||||
// Get rooms that were created
|
||||
const rooms = digger.getRooms();
|
||||
|
||||
// Place entrance in the first room
|
||||
const entranceRoom = rooms[0];
|
||||
const entranceCenter = entranceRoom.getCenter();
|
||||
const entrance = [entranceCenter[0], entranceCenter[1]];
|
||||
|
||||
// Place exit in the last room
|
||||
const exitRoom = rooms[rooms.length - 1];
|
||||
const exitCenter = exitRoom.getCenter();
|
||||
const exit = [exitCenter[0], exitCenter[1]];
|
||||
|
||||
// Place treasure in a middle room (not first or last)
|
||||
let treasureRoom;
|
||||
if (rooms.length > 2) {
|
||||
treasureRoom = rooms[Math.floor(rooms.length / 2)];
|
||||
} else {
|
||||
// Fallback if we have fewer than 3 rooms
|
||||
treasureRoom = rooms[0];
|
||||
}
|
||||
const treasureCenter = treasureRoom.getCenter();
|
||||
// Place treasure slightly off center to make it more interesting
|
||||
const treasure = [
|
||||
treasureCenter[0] + Math.floor(Math.random() * 3) - 1,
|
||||
treasureCenter[1] + Math.floor(Math.random() * 3) - 1
|
||||
];
|
||||
|
||||
// Ensure the treasure is on a floor tile
|
||||
if (map[treasure[1]][treasure[0]] !== 0) {
|
||||
treasure[0] = treasureCenter[0];
|
||||
treasure[1] = treasureCenter[1];
|
||||
}
|
||||
|
||||
return {
|
||||
map: map,
|
||||
rooms: rooms,
|
||||
entrance: entrance,
|
||||
exit: exit,
|
||||
treasure: treasure
|
||||
};
|
||||
}
|
||||
|
||||
static getRandomRoomCenter(rooms, excludeFirst = false, excludeLast = false) {
|
||||
if (!rooms || rooms.length === 0) return null;
|
||||
|
||||
let availableRooms = [...rooms];
|
||||
if (excludeFirst && availableRooms.length > 1) {
|
||||
availableRooms = availableRooms.slice(1);
|
||||
}
|
||||
if (excludeLast && availableRooms.length > 1) {
|
||||
availableRooms = availableRooms.slice(0, -1);
|
||||
}
|
||||
|
||||
const randomRoom = availableRooms[Math.floor(Math.random() * availableRooms.length)];
|
||||
return randomRoom.getCenter();
|
||||
}
|
||||
|
||||
static isFloorTile(map, x, y) {
|
||||
return map[y] && map[y][x] === 0;
|
||||
}
|
||||
|
||||
static isWallTile(map, x, y) {
|
||||
return map[y] && map[y][x] === 1;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DungeonGenerator;
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
const ROT = require('./rot.js');
|
||||
const Player = require('./player.js');
|
||||
const Monster = require('./monster.js');
|
||||
const DungeonGenerator = require('./dungeon.js');
|
||||
|
||||
class Game {
|
||||
constructor(socketId, mapWidth, mapHeight) {
|
||||
this.socketId = socketId;
|
||||
this.width = mapWidth || 25; // Reduced default size to match client display
|
||||
this.height = mapHeight || 19; // Reduced default size to match client display
|
||||
this.gameState = 'waiting'; // waiting, active, won, lost
|
||||
this.startBlock = null;
|
||||
this.dungeon = null;
|
||||
this.player = new Player();
|
||||
this.monster = new Monster();
|
||||
this.fee = 0; // Amount player paid
|
||||
this.visibleTiles = {}; // Will store visible tiles
|
||||
this.fov = null; // FOV calculator
|
||||
this.generateDungeon();
|
||||
}
|
||||
|
||||
generateDungeon() {
|
||||
this.dungeon = DungeonGenerator.generate(this.width, this.height);
|
||||
|
||||
if (this.dungeon.entrance) {
|
||||
this.player.moveTo(this.dungeon.entrance[0], this.dungeon.entrance[1]);
|
||||
}
|
||||
|
||||
// Place monster far from entrance
|
||||
if (this.dungeon.rooms && this.dungeon.rooms.length > 2) {
|
||||
const monsterRoom = this.dungeon.rooms[Math.floor(this.dungeon.rooms.length * 0.7)];
|
||||
const center = monsterRoom.getCenter();
|
||||
this.monster.moveTo(center[0], center[1]);
|
||||
}
|
||||
|
||||
// Initialize FOV calculator
|
||||
this.fov = new ROT.FOV.PreciseShadowcasting(
|
||||
(x, y) => {
|
||||
// Return true if the tile is transparent (can see through it)
|
||||
return this.dungeon.map[y] && this.dungeon.map[y][x] === 0;
|
||||
}
|
||||
);
|
||||
|
||||
// Calculate initial FOV
|
||||
this.updateFOV();
|
||||
|
||||
// Set game state to active
|
||||
this.gameState = 'active';
|
||||
}
|
||||
|
||||
updateFOV() {
|
||||
// Reset visible tiles
|
||||
this.visibleTiles = {};
|
||||
|
||||
// Calculate new visible tiles
|
||||
this.fov.compute(this.player.x, this.player.y, 10, (x, y, r, visibility) => { // Added r and visibility params
|
||||
if (visibility > 0) { // Only add if tile is actually visible
|
||||
if (!this.visibleTiles[y]) {
|
||||
this.visibleTiles[y] = {};
|
||||
}
|
||||
// Store the actual tile type (0 for floor, 1 for wall) from the dungeon map
|
||||
if (this.dungeon && this.dungeon.map && this.dungeon.map[y] && this.dungeon.map[y][x] !== undefined) {
|
||||
this.visibleTiles[y][x] = this.dungeon.map[y][x];
|
||||
} else {
|
||||
// Should not happen if FOV is within map bounds, but as a fallback:
|
||||
// this.visibleTiles[y][x] = 1; // Default to wall if outside known map
|
||||
}
|
||||
}
|
||||
});
|
||||
// console.log("FOV updated. Player:", this.player.x, this.player.y, "Visible tiles count:", Object.keys(this.visibleTiles).reduce((acc, k) => acc + Object.keys(this.visibleTiles[k]).length, 0));
|
||||
}
|
||||
|
||||
movePlayer(dx, dy) {
|
||||
const newX = this.player.x + dx;
|
||||
const newY = this.player.y + dy;
|
||||
|
||||
// Debug logging for movement validation
|
||||
console.log(`[DEBUG] Move attempt: from (${this.player.x},${this.player.y}) to (${newX},${newY}) with dx=${dx},dy=${dy}`);
|
||||
console.log(`[DEBUG] Map bounds: width=${this.width}, height=${this.height}`);
|
||||
console.log(`[DEBUG] Dungeon exists: ${!!this.dungeon}`);
|
||||
if (this.dungeon && this.dungeon.map) {
|
||||
console.log(`[DEBUG] Map row ${newY} exists: ${!!this.dungeon.map[newY]}`);
|
||||
if (this.dungeon.map[newY]) {
|
||||
console.log(`[DEBUG] Map cell [${newY}][${newX}] value: ${this.dungeon.map[newY][newX]} (0=floor, 1=wall)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the move is valid (not into a wall and within map bounds)
|
||||
if (this.dungeon &&
|
||||
this.dungeon.map[newY] &&
|
||||
this.dungeon.map[newY][newX] !== undefined &&
|
||||
this.dungeon.map[newY][newX] === 0) { // 0 is floor
|
||||
|
||||
this.player.moveTo(newX, newY);
|
||||
console.log(`Player moved to ${newX},${newY} in game for socket ${this.socketId}`);
|
||||
|
||||
// Update FOV after moving
|
||||
this.updateFOV();
|
||||
|
||||
// Check for game events like finding treasure or exit
|
||||
if (this.dungeon.exit && this.player.isAt(this.dungeon.exit[0], this.dungeon.exit[1])) {
|
||||
// Handle win condition (e.g., escaped)
|
||||
this.gameState = 'won';
|
||||
return { status: 'moved', event: 'escaped', player: this.player.getState(), visibleTiles: this.visibleTiles };
|
||||
}
|
||||
if (this.dungeon.treasure && this.player.isAt(this.dungeon.treasure[0], this.dungeon.treasure[1]) && !this.player.hasTreasure) {
|
||||
this.player.hasTreasure = true;
|
||||
// Remove treasure from dungeon so it won't be sent in future updates
|
||||
this.dungeon.treasure = null;
|
||||
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(`Player move to ${newX},${newY} for socket ${this.socketId} is invalid (wall or out of bounds).`);
|
||||
|
||||
// Debug: Show map around player
|
||||
console.log(`[DEBUG] Map around player position:`);
|
||||
for (let y = this.player.y - 2; y <= this.player.y + 2; y++) {
|
||||
let row = '';
|
||||
for (let x = this.player.x - 2; x <= this.player.x + 2; x++) {
|
||||
if (x === this.player.x && y === this.player.y) {
|
||||
row += '@'; // Player position
|
||||
} else if (x === newX && y === newY) {
|
||||
row += 'X'; // Attempted move position
|
||||
} else if (this.dungeon && this.dungeon.map[y] && this.dungeon.map[y][x] !== undefined) {
|
||||
row += this.dungeon.map[y][x] === 0 ? '.' : '#';
|
||||
} else {
|
||||
row += '?'; // Out of bounds or undefined
|
||||
}
|
||||
}
|
||||
console.log(`[DEBUG] Y=${y}: ${row}`);
|
||||
}
|
||||
|
||||
return { status: 'invalid' };
|
||||
}
|
||||
|
||||
moveMonster() {
|
||||
this.monster.moveTowardPlayer(this.player, this.dungeon);
|
||||
}
|
||||
|
||||
// Update the getState() method to include all entities with relative positions
|
||||
getState() {
|
||||
const state = {
|
||||
gameState: this.gameState,
|
||||
player: this.player.getState(), // Use Player's getState method
|
||||
monster: this.monster ? this.monster.getState() : null, // Use Monster's getState method
|
||||
visibleTiles: { ...this.visibleTiles }, // Send a copy of visible tiles
|
||||
entrance: this.dungeon ? this.dungeon.entrance : null,
|
||||
exit: this.dungeon ? this.dungeon.exit : null,
|
||||
treasure: this.dungeon ? this.dungeon.treasure : null,
|
||||
};
|
||||
|
||||
// Debug logging to verify entity data
|
||||
console.log("🎮 getState() sending entities - Monster:", state.monster, "Entrance:", state.entrance, "Exit:", state.exit, "Treasure:", state.treasure);
|
||||
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if monster killed player
|
||||
function checkMonsterKill(player, monster) {
|
||||
// Use Monster's hasCaughtPlayer method
|
||||
const monsterInstance = new Monster(monster.x, monster.y);
|
||||
return monsterInstance.hasCaughtPlayer(player);
|
||||
}
|
||||
|
||||
module.exports = Game;
|
||||
module.exports.checkMonsterKill = checkMonsterKill;
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
const express = require('express');
|
||||
var app = require('express')();
|
||||
var http = require('http').Server(app);
|
||||
var io = require('socket.io')(http);
|
||||
var rpc = require('./rpccalls.js');
|
||||
var db = require('./dbcalls.js');
|
||||
var user = require('./user');
|
||||
|
||||
// Function to get a user by socket ID
|
||||
// Enhance the getUserBySocket function to try both IDs
|
||||
|
||||
function getUserBySocket(socketId) {
|
||||
console.log(`Looking up user with socketId: ${socketId}`);
|
||||
|
||||
// Try direct lookup first
|
||||
let foundUser = user.getUserBySocketId(socketId);
|
||||
|
||||
// If not found but we have a socket map, try the mapped ID
|
||||
if (!foundUser && clientSocketMap.has(socketId)) {
|
||||
const mappedId = clientSocketMap.get(socketId);
|
||||
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"}`);
|
||||
return foundUser;
|
||||
}
|
||||
|
||||
const Game = require('./game');
|
||||
const activeGames = new Map(); // Maps socketId to Game objects
|
||||
let lastBlockHeight = 0; // Track last block height
|
||||
const MIN_FEE = 10; // Minimum entrance fee in WOW
|
||||
const MAX_FEE = 100; // Maximum entrance fee in WOW
|
||||
const WAITING_PLAYERS = []; // Players waiting for the next block
|
||||
const DEBUG_MODE = true; // Set to false to disable debug mode
|
||||
let debugBlockHeight = 1;
|
||||
const clientSocketMap = new Map(); // To track client-to-server socket ID mappings
|
||||
|
||||
app.use(express.static('html'));
|
||||
app.get('/', function(req, res) {
|
||||
res.sendfile('index.html');
|
||||
});
|
||||
|
||||
// Replace your existing block check interval with this conditional version
|
||||
if (DEBUG_MODE) {
|
||||
console.log("🐛 DEBUG MODE ENABLED - Simulating blocks every 30 seconds");
|
||||
|
||||
// Initial debug block
|
||||
io.emit('blockheight', debugBlockHeight);
|
||||
|
||||
// Debug block height simulator
|
||||
setInterval(function() {
|
||||
debugBlockHeight++;
|
||||
console.log(`🐛 DEBUG: New simulated block: ${debugBlockHeight}`);
|
||||
io.emit('blockheight', debugBlockHeight);
|
||||
|
||||
// Start games for waiting players
|
||||
startGamesForWaiting(debugBlockHeight);
|
||||
|
||||
// Check active games for timeout
|
||||
checkGamesTimeout(debugBlockHeight);
|
||||
|
||||
}, 30000); // Every 30 seconds
|
||||
} else {
|
||||
// Your original block check code
|
||||
setInterval(function() {
|
||||
rpc.daemonCall("get_block_count", "", function(result) {
|
||||
const currentHeight = result.result.count;
|
||||
rpc.lastBlock.setHeight(currentHeight);
|
||||
|
||||
// If new block found
|
||||
if (currentHeight > lastBlockHeight) {
|
||||
console.log(`New block found: ${currentHeight}`);
|
||||
io.emit('blockheight', currentHeight);
|
||||
|
||||
// Start games for waiting players
|
||||
startGamesForWaiting(currentHeight);
|
||||
|
||||
// Check active games for timeout
|
||||
checkGamesTimeout(currentHeight);
|
||||
|
||||
lastBlockHeight = currentHeight;
|
||||
} else {
|
||||
io.emit('blockheight', currentHeight);
|
||||
}
|
||||
});
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Start games for waiting players
|
||||
function startGamesForWaiting(blockHeight) {
|
||||
console.log(`Starting games for ${WAITING_PLAYERS.length} waiting players at block height ${blockHeight}`);
|
||||
|
||||
while (WAITING_PLAYERS.length > 0) {
|
||||
const playerEntry = WAITING_PLAYERS.shift();
|
||||
const serverId = playerEntry.serverId;
|
||||
|
||||
console.log(`Processing player: server=${serverId}`);
|
||||
|
||||
const currentUser = getUserBySocket(serverId);
|
||||
|
||||
if (currentUser) {
|
||||
currentUser.blockRec = blockHeight;
|
||||
|
||||
try {
|
||||
const game = currentUser.startGame(80, 40);
|
||||
activeGames.set(serverId, game);
|
||||
|
||||
const gameState = game.getState();
|
||||
gameState.blockHeight = blockHeight;
|
||||
|
||||
console.log(`🎮 SENDING GAME_START to ${serverId}`);
|
||||
|
||||
// Send ONLY ONE message - the game state itself
|
||||
io.to(serverId).emit('game_start', gameState);
|
||||
|
||||
console.log(`Game started for player ${serverId}`);
|
||||
} catch (error) {
|
||||
console.error(`Error creating game:`, error);
|
||||
io.to(serverId).emit('message', 'Error starting game: ' + error.message);
|
||||
}
|
||||
} else {
|
||||
console.error(`User not found for socket ${serverId}`);
|
||||
io.to(serverId).emit('message', 'Error: User not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if any active games have timed out
|
||||
function checkGamesTimeout(currentHeight) {
|
||||
activeGames.forEach((game, socketId) => {
|
||||
const user = getUserBySocket(socketId);
|
||||
|
||||
// Player has 3 blocks to complete the dungeon
|
||||
// If they started on block 2, they must escape before block 5 is found
|
||||
if (user && user.blockRec && currentHeight > user.blockRec + 2) {
|
||||
console.log(`Game timeout for player ${socketId}: started on block ${user.blockRec}, current block ${currentHeight} (allowed until block ${user.blockRec + 2})`);
|
||||
|
||||
// Game has timed out - player didn't escape in time
|
||||
game.gameState = 'lost';
|
||||
io.to(socketId).emit('game_over', {
|
||||
status: 'lost',
|
||||
reason: 'timeout',
|
||||
message: 'You didn\'t escape before the block time limit!'
|
||||
});
|
||||
|
||||
activeGames.delete(socketId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Socket.io handlers
|
||||
io.on('connection', function(socket) {
|
||||
console.log('A user connected');
|
||||
console.log(socket.client.id);
|
||||
console.log(socket.handshake.address);
|
||||
|
||||
// Create and register user (automatically stored in registry)
|
||||
new user.User(socket.id, socket.handshake.address);
|
||||
// Also store socket.client.id as an attribute
|
||||
const newUser = 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})`);
|
||||
}
|
||||
|
||||
// Insert into visitors DB
|
||||
db.insertVisitor(socket.client.id, socket.handshake.address, 0);
|
||||
|
||||
// Send welcome message
|
||||
io.to(socket.client.id).emit('welcome', socket.client.id);
|
||||
|
||||
socket.on('chat message', function(msg) {
|
||||
console.log('Message received:', msg);
|
||||
|
||||
if (msg.toLowerCase() == 'hello') {
|
||||
io.to(`${socket.client.id}`).emit('message',
|
||||
'Welcome, to enter the dungeon type Enter, and you will be given a Wownero address, ' +
|
||||
'which you must send between 10-100 WOW to enter. The more you send, the more you can win.');
|
||||
}
|
||||
// Update the 'enter' command handler to send waiting_status
|
||||
if (msg.toLowerCase() == 'enter') {
|
||||
console.log(`Player ${socket.id} requested to enter the dungeon`);
|
||||
|
||||
// Use the updated user lookup function
|
||||
const currentUser = getUserBySocket(socket.id);
|
||||
|
||||
if (currentUser) {
|
||||
console.log(`Found user for socket ${socket.id}, adding to queue...`);
|
||||
|
||||
// Add to waiting players queue
|
||||
if (!WAITING_PLAYERS.some(p => p.serverId === socket.id)) {
|
||||
WAITING_PLAYERS.push({
|
||||
serverId: socket.id,
|
||||
clientId: socket.id,
|
||||
user: currentUser,
|
||||
joinedAt: Date.now()
|
||||
});
|
||||
|
||||
// Send waiting status data for display - THIS IS THE KEY PART
|
||||
io.to(socket.id).emit('waiting_status', {
|
||||
status: 'waiting',
|
||||
message: 'Waiting for the next block to be found...',
|
||||
position: WAITING_PLAYERS.length,
|
||||
currentBlock: debugBlockHeight || lastBlockHeight || 0,
|
||||
joinTime: Date.now()
|
||||
});
|
||||
|
||||
console.log(`Added player to queue. Current queue: ${WAITING_PLAYERS.length} players`);
|
||||
} else {
|
||||
io.to(socket.id).emit('message', 'You are already in the queue. Please wait.');
|
||||
}
|
||||
} else {
|
||||
io.to(socket.id).emit('message', 'Error: Could not add you to the game queue. Please try again.');
|
||||
}
|
||||
}
|
||||
// Add a handler for the 'cancel' command
|
||||
else if (msg.toLowerCase() == 'cancel') {
|
||||
// Remove player from waiting queue
|
||||
const index = WAITING_PLAYERS.findIndex(p => p.serverId === socket.id);
|
||||
|
||||
if (index !== -1) {
|
||||
WAITING_PLAYERS.splice(index, 1);
|
||||
io.to(socket.id).emit('message', 'You have left the queue.');
|
||||
|
||||
// Reset to welcome screen
|
||||
io.to(socket.id).emit('queue_cancelled');
|
||||
} else {
|
||||
io.to(socket.id).emit('message', 'You were not in the queue.');
|
||||
}
|
||||
}
|
||||
else {
|
||||
io.emit('message', msg);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle player movement
|
||||
socket.on('player_move', function(moveData) { // Changed from 'move' to 'player_move' and added moveData
|
||||
console.log(`Player move event received from ${socket.id}:`, moveData);
|
||||
const currentUser = getUserBySocket(socket.id);
|
||||
|
||||
if (currentUser && currentUser.game && currentUser.game.gameState === 'active') {
|
||||
if (typeof moveData.dx === 'number' && typeof moveData.dy === 'number') {
|
||||
const game = currentUser.game;
|
||||
const moveResult = game.movePlayer(moveData.dx, moveData.dy); // This should update player pos and FOV
|
||||
|
||||
if (moveResult && moveResult.status === 'moved') {
|
||||
// Move monster after player moves
|
||||
game.moveMonster();
|
||||
|
||||
// Check if monster caught player
|
||||
const GameModule = require('./game');
|
||||
const checkMonsterKill = GameModule.checkMonsterKill ||
|
||||
((player, monster) => monster.x === player.x && monster.y === player.y);
|
||||
|
||||
if (checkMonsterKill(game.player, game.monster)) {
|
||||
game.gameState = 'lost';
|
||||
io.to(socket.id).emit('game_over', {
|
||||
status: 'lost',
|
||||
reason: 'monster',
|
||||
message: 'The monster caught you!'
|
||||
});
|
||||
activeGames.delete(socket.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for treasure pickup
|
||||
if (moveResult.event === 'treasure_found') {
|
||||
io.to(socket.id).emit('message', 'You found the treasure!');
|
||||
}
|
||||
|
||||
// Check for escape
|
||||
if (moveResult.event === 'escaped') {
|
||||
game.gameState = 'won';
|
||||
io.to(socket.id).emit('game_over', {
|
||||
status: 'won',
|
||||
reason: 'escaped',
|
||||
message: 'Congratulations! You escaped the dungeon!'
|
||||
});
|
||||
activeGames.delete(socket.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedGameState = game.getState(); // Get the new state
|
||||
|
||||
// Log before sending to client for debugging
|
||||
console.log(`Sending game_update to ${socket.id} after player move. Player:`, updatedGameState.player, "Visible tiles keys:", Object.keys(updatedGameState.visibleTiles || {}));
|
||||
|
||||
io.to(socket.id).emit('game_update', updatedGameState);
|
||||
} else {
|
||||
console.log(`Player move from ${socket.id} was invalid or resulted in no change.`);
|
||||
// Optionally, send an update even for invalid moves if you want to provide feedback
|
||||
// const currentGameState = game.getState();
|
||||
// io.to(socket.id).emit('game_update', currentGameState);
|
||||
}
|
||||
} else {
|
||||
console.error(`Invalid moveData received from ${socket.id}:`, moveData);
|
||||
}
|
||||
} else {
|
||||
console.log(`Player move event from ${socket.id} ignored: No active game found for user.`);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle disconnection
|
||||
socket.on('disconnect', function() {
|
||||
console.log('User disconnected', socket.client.id);
|
||||
user.removeUser(socket.client.id);
|
||||
});
|
||||
|
||||
// Add this to your socket handlers in index.js
|
||||
socket.on('debug_ping', function(data) {
|
||||
console.log(`Debug ping received from ${socket.client.id}`);
|
||||
socket.emit('debug_pong', {
|
||||
message: "Hello from server!",
|
||||
clientTime: data.time,
|
||||
serverTime: Date.now(),
|
||||
socketId: socket.client.id
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('register_client', function(data) {
|
||||
console.log(`Client registered: ${socket.id} (server) <-> ${data.clientId} (client)`);
|
||||
|
||||
// Store both mappings for lookup
|
||||
clientSocketMap.set(data.clientId, socket.id);
|
||||
clientSocketMap.set(socket.id, data.clientId);
|
||||
|
||||
// Send confirmation back to client
|
||||
socket.emit('socket_registered', {
|
||||
clientId: data.clientId,
|
||||
serverId: socket.id,
|
||||
success: true
|
||||
});
|
||||
});
|
||||
|
||||
}); // End of io.on('connection') handler
|
||||
|
||||
// Add this debug function to check all registered users
|
||||
|
||||
function debugRegisteredUsers() {
|
||||
console.log("\n🔍 CHECKING ALL REGISTERED USERS:");
|
||||
const allUsers = user.getAllUsers ? user.getAllUsers() : null;
|
||||
|
||||
if (!allUsers) {
|
||||
console.log("No getAllUsers function available or no users registered");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${allUsers.length} registered users:`);
|
||||
allUsers.forEach((u, i) => {
|
||||
console.log(`User ${i+1}:`, {
|
||||
id: u.id,
|
||||
clientId: u.clientId || 'undefined',
|
||||
address: u.address
|
||||
});
|
||||
});
|
||||
console.log(); // Empty line for readability
|
||||
}
|
||||
|
||||
// Call this after a user registers and at intervals
|
||||
setInterval(debugRegisteredUsers, 10000);
|
||||
|
||||
http.listen(3000, function() {
|
||||
console.log('listening on *:3000');
|
||||
});
|
||||
|
||||
// Make sure this function is defined in your file
|
||||
function startGameForPlayer(socketId, blockHeight) {
|
||||
console.log(`Starting game for player ${socketId} at block height ${blockHeight}`);
|
||||
|
||||
const currentUser = getUserBySocket(socketId);
|
||||
if (!currentUser) {
|
||||
console.error(`User with socket ID ${socketId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create a new game
|
||||
const game = currentUser.startGame(25, 19);
|
||||
if (!game) {
|
||||
console.error("Game creation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Store the game in activeGames map
|
||||
activeGames.set(socketId, game);
|
||||
|
||||
// Get game state - ensure it has the required fields
|
||||
const gameState = {
|
||||
gameState: "active", // Add this so frontend knows it's active
|
||||
player: {
|
||||
x: game.player.x,
|
||||
y: game.player.y,
|
||||
hasKey: !!game.player.hasKey,
|
||||
hasTreasure: !!game.player.hasTreasure
|
||||
},
|
||||
monster: game.monster,
|
||||
visibleTiles: game.calculateFOV ? game.calculateFOV() : {},
|
||||
entrance: [game.dungeon.entrance.x, game.dungeon.entrance.y],
|
||||
exit: [game.dungeon.exit.x, game.dungeon.exit.y],
|
||||
treasure: [game.dungeon.treasure.x, game.dungeon.treasure.y]
|
||||
};
|
||||
|
||||
console.log("Sending game_start with state:", JSON.stringify(gameState, null, 2).substring(0, 200) + "...");
|
||||
|
||||
// Add a small delay before sending (sometimes helps with socket timing issues)
|
||||
setTimeout(() => {
|
||||
debugSocket(socketId, 'game_start', gameState);
|
||||
// Send initial game state to client
|
||||
io.to(socketId).emit('game_start', gameState);
|
||||
console.log(`Game started for player ${socketId}`);
|
||||
}, 100);
|
||||
} catch (err) {
|
||||
console.error("Error starting game:", err);
|
||||
io.to(socketId).emit('message', 'Error starting game: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function debugSocket(socketId, eventName, data) {
|
||||
console.log(`🔌 SOCKET DEBUG: Sending ${eventName} to ${socketId.substring(0, 8)}...`);
|
||||
console.log(`📦 PAYLOAD (first 300 chars): ${JSON.stringify(data).substring(0, 300)}...`);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
const ROT = require('./rot.js');
|
||||
|
||||
/**
|
||||
* Monster class - Manages monster state and AI
|
||||
*/
|
||||
class Monster {
|
||||
constructor(x = 0, y = 0) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
// Move monster to new position
|
||||
moveTo(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
// Check if monster is at given coordinates
|
||||
isAt(x, y) {
|
||||
return this.x === x && this.y === y;
|
||||
}
|
||||
|
||||
// Simple AI to move toward player
|
||||
moveTowardPlayer(player, dungeon) {
|
||||
if (!player || !dungeon || !dungeon.map) return;
|
||||
|
||||
const dx = Math.sign(player.x - this.x);
|
||||
const dy = Math.sign(player.y - this.y);
|
||||
|
||||
// Try horizontal move first
|
||||
if (dx !== 0) {
|
||||
const newX = this.x + dx;
|
||||
if (dungeon.map[this.y] && dungeon.map[this.y][newX] === 0) {
|
||||
this.x = newX;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Try vertical move
|
||||
if (dy !== 0) {
|
||||
const newY = this.y + dy;
|
||||
if (dungeon.map[newY] && dungeon.map[newY][this.x] === 0) {
|
||||
this.y = newY;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Try random direction if direct path is blocked
|
||||
const dirs = [[0,1],[1,0],[0,-1],[-1,0]];
|
||||
const shuffledDirs = ROT.RNG.shuffle(dirs.slice());
|
||||
|
||||
for (const [dx, dy] of shuffledDirs) {
|
||||
const nx = this.x + dx;
|
||||
const ny = this.y + dy;
|
||||
if (dungeon.map[ny] && dungeon.map[ny][nx] === 0) {
|
||||
this.x = nx;
|
||||
this.y = ny;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if monster has caught the player
|
||||
hasCaughtPlayer(player) {
|
||||
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;
|
||||
}
|
||||
|
||||
// Get monster state as object
|
||||
getState() {
|
||||
return {
|
||||
x: this.x,
|
||||
y: this.y
|
||||
};
|
||||
}
|
||||
|
||||
// Set monster state from object
|
||||
setState(state) {
|
||||
if (state.x !== undefined) this.x = state.x;
|
||||
if (state.y !== undefined) this.y = state.y;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Monster;
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Player class - Manages player state and actions
|
||||
*/
|
||||
class Player {
|
||||
constructor(x = 0, y = 0) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.hasKey = false;
|
||||
this.hasTreasure = false;
|
||||
}
|
||||
|
||||
// Move player to new position
|
||||
moveTo(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
// Check if player is at given coordinates
|
||||
isAt(x, y) {
|
||||
return this.x === x && this.y === y;
|
||||
}
|
||||
|
||||
// Reset player state
|
||||
reset() {
|
||||
this.hasKey = false;
|
||||
this.hasTreasure = false;
|
||||
}
|
||||
|
||||
// Get player state as object
|
||||
getState() {
|
||||
return {
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
hasKey: this.hasKey,
|
||||
hasTreasure: this.hasTreasure
|
||||
};
|
||||
}
|
||||
|
||||
// Set player state from object
|
||||
setState(state) {
|
||||
if (state.x !== undefined) this.x = state.x;
|
||||
if (state.y !== undefined) this.y = state.y;
|
||||
if (state.hasKey !== undefined) this.hasKey = state.hasKey;
|
||||
if (state.hasTreasure !== undefined) this.hasTreasure = state.hasTreasure;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Player;
|
||||
@@ -0,0 +1,79 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Wowngeon Fixes Test</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: monospace;
|
||||
background: #000;
|
||||
color: #0f0;
|
||||
padding: 20px;
|
||||
}
|
||||
.test-result {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
border: 1px solid #333;
|
||||
}
|
||||
.pass { border-color: #0f0; }
|
||||
.fail { border-color: #f00; }
|
||||
iframe {
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #666;
|
||||
margin: 20px 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>🎮 Wowngeon Fixes Verification</h1>
|
||||
|
||||
<div class="test-result">
|
||||
<h2>🔧 Fix #1: START Button Visibility</h2>
|
||||
<p><strong>Issue:</strong> START button was invisible (cut off in game display)</p>
|
||||
<p><strong>Fix:</strong> Moved to HTML status area with proper styling</p>
|
||||
<p><strong>Test:</strong> Check if START button is visible in the status area below</p>
|
||||
</div>
|
||||
|
||||
<div class="test-result">
|
||||
<h2>⏱️ Fix #2: Auto-Entry Death Timing</h2>
|
||||
<p><strong>Issue:</strong> Players died after 2+ blocks instead of 1 block in debug mode</p>
|
||||
<p><strong>Fix:</strong> Set currentUser.blockRec = currentBlock + 1 for consistent timing</p>
|
||||
<p><strong>Test:</strong> Use "enter" command and check death timing logs in console</p>
|
||||
</div>
|
||||
|
||||
<h2>🎯 Live Game Test</h2>
|
||||
<iframe src="http://localhost:3000"></iframe>
|
||||
|
||||
<div class="test-result">
|
||||
<h3>📋 Test Instructions:</h3>
|
||||
<ol>
|
||||
<li><strong>START Button Test:</strong> Look for the green "🎮 START GAME" button in the status area (should be visible)</li>
|
||||
<li><strong>Death Timing Test:</strong> Click START or type "enter" in chat, then check browser console for timing logs</li>
|
||||
<li><strong>Expected Logs:</strong> Should see "🕒 AUTO-ENTRY: Player starts on block X, will die after block X+2"</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Test the START button visibility
|
||||
window.addEventListener('load', function() {
|
||||
setTimeout(function() {
|
||||
const iframe = document.querySelector('iframe');
|
||||
if (iframe && iframe.contentDocument) {
|
||||
const startButton = iframe.contentDocument.getElementById('startButton');
|
||||
if (startButton) {
|
||||
console.log('✅ START button found in iframe');
|
||||
const styles = window.getComputedStyle(startButton);
|
||||
console.log('START button styles:', {
|
||||
display: styles.display,
|
||||
visibility: styles.visibility,
|
||||
background: styles.backgroundColor
|
||||
});
|
||||
} else {
|
||||
console.log('❌ START button not found in iframe');
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user