diff --git a/main.js b/main.js index dcb6e4a..f6f855b 100644 --- a/main.js +++ b/main.js @@ -51,7 +51,7 @@ async function updatePlayerElo(player) { const connection = await pool.getConnection(); try { const updateQuery = ` - UPDATE jedaii_comp + UPDATE players SET elo = ? WHERE guid = ? `; @@ -62,7 +62,6 @@ async function updatePlayerElo(player) { } // Event handling - class GameEventEmitter extends events.EventEmitter {} const gameEventEmitter = new GameEventEmitter(); @@ -113,7 +112,7 @@ gameEventEmitter.on('RoundEnd', async (redScore, blueScore, playerScores) => { // Function to request a new token async function requestNewToken() { - const API_URL = 'https://panel.pineriver.net/api/client/servers/68f7edce/websocket'; // Corrected API endpoint + const API_URL = 'https://panel.pineriver.net/api/client/servers/35e1d7ab/websocket'; // Corrected API endpoint const API_KEY = 'Bearer ptlc_uohTuXbtbTmVaSAhwtD16R2oDynhQgTWBZKN2m5lWdh'; // Your actual API key try { const response = await axios.get(API_URL, { @@ -135,7 +134,7 @@ async function requestNewToken() { // Main function to start WebSocket connection and handle console output async function startWebSocketConnection() { try { - const API_URL = 'https://panel.pineriver.net/api/client/servers/68f7edce/websocket'; + const API_URL = 'https://panel.pineriver.net/api/client/servers/35e1d7ab/websocket'; const API_KEY = 'Bearer ptlc_uohTuXbtbTmVaSAhwtD16R2oDynhQgTWBZKN2m5lWdh'; // Request the token and WebSocket URL @@ -202,6 +201,13 @@ async function startWebSocketConnection() { function handleConsoleOutput(line) { const playerScores = {}; + if (eventClientConnect(line, line, playerQueue)) return; + if (eventDisconnect(line, line, currentPlayers, playerQueue)) return; + if (eventKill(line, line, currentPlayers)) return; + if (eventSay(line, line, currentPlayers)) return; + if (eventBroadcast(line, line, currentPlayers)) return; + if (eventShutdown(line, currentPlayers, playerQueue)) return; + if (line.startsWith('>>> red:') && line.includes(' blue:')) { const redScore = parseInt(line.split('red:')[1].split(' ')[0]); const blueScore = parseInt(line.split('blue:')[1]); @@ -226,6 +232,188 @@ function handleConsoleOutput(line) { } } +// Event Handlers +async function eventClientConnect(event, eventContent, playerQueue) { + if (event.includes("ClientConnect")) { + console.log("Client connecting..."); + + const pid = parseInt(eventContent.split("ID: ")[1].split(" ")[0], 10); + const guid = eventContent.includes("\\ja_guid\\") ? eventContent.split("\\ja_guid\\")[1].split("\\")[0] : null; + + if (!guid) { + console.log("GUID not found in event content, skipping player initialization."); + return false; + } + + if (currentPlayers.some(player => player.guid === guid)) { + return false; + } + + // Check if the player already exists in the database + const playerExists = await checkIfPlayerExists(guid); + + if (!playerExists) { + // Create a new player in the database + const newPlayer = { + guid: guid, + id: pid, + ip: null, // You might want to extract the IP from the eventContent if available + name: null, // Player name can be updated later + elo: 1000, // Default starting Elo rating + aliases: [] // Start with an empty list of aliases + }; + await insertNewPlayer(newPlayer); + console.log(`New player added to the database: [GUID: ${guid}]`); + } + + console.log(`Adding player to queue: [PID: ${pid}] [GUID: ${guid}]`); + playerQueue.push({ guid: guid, id: pid, ip: null, name: null }); + + return true; + } + return false; +} + +// Check if a player with the given GUID already exists in the database +async function checkIfPlayerExists(guid) { + const connection = await pool.getConnection(); + try { + const query = `SELECT COUNT(*) AS count FROM players WHERE guid = ?`; + const [rows] = await connection.execute(query, [guid]); + return rows[0].count > 0; + } finally { + if (connection) connection.release(); + } +} + +// Insert a new player into the database +async function insertNewPlayer(player) { + const connection = await pool.getConnection(); + try { + const aliasesStr = JSON.stringify(player.aliases); + const insertQuery = ` + INSERT INTO players (guid, name, ip, elo, aliases) + VALUES (?, ?, ?, ?, ?) + `; + await connection.execute(insertQuery, [player.guid, player.name, player.ip, player.elo, aliasesStr]); + console.log(`Player with GUID: ${player.guid} inserted into the database.`); + } finally { + if (connection) connection.release(); + } +} + +function searchByNameOrGuid(identifier, currentPlayers) { + const cleanIdentifier = removeColorCodes(identifier); + for (let i = 0; i < currentPlayers.length; i++) { + const player = currentPlayers[i]; + if (player.guid === cleanIdentifier || removeColorCodes(player.name).toLowerCase().includes(cleanIdentifier.toLowerCase())) { + return i; + } + } + return -1; +} + +async function eventSay(event, eventContent, currentPlayers) { + if (!event.includes('say')) { + return false; + } + + let name = eventContent.split(": ", 1)[0]; + const chat = eventContent.split(": ", 2)[1]; + const pIndex = searchByNameOrGuid(name, currentPlayers); + + if (pIndex === -1) return false; + + const player = currentPlayers[pIndex]; + const parts = chat.split(" "); + + // Check if the player typed "!rank" + if (parts[0] === "!rank") { + const playerElo = player.elo; // Get the player's Elo rating + const message = `say ${player.name}, your current Elo rating is: ${playerElo}`; + console.log(message); // Debugging: log the message + network.sendCmd(message); // Send the message back to the game server + return true; + } + + // Additional chat commands handling + // ... + + return true; +} + +async function eventBroadcast(event, eventContent, currentPlayers) { + if (event.includes("broadcast")) { + if (eventContent.includes("print ")) { + const templine = eventContent.split("print ")[1].trim(); + console.log(`Debug: Broadcast event detected: ${templine}`); + + // Additional broadcast event handling + // ... + } + } + return false; +} + +function eventShutdown(event, currentPlayers, playerQueue) { + if (event.toLowerCase().includes("shutdown")) { + console.log(">>>>>ROUND END<<<<<<<<<"); + + playerQueue.length = 0; // Clear the player queue + currentPlayers.length = 0; // Clear the current players list + return true; + } else { + return false; + } +} + +async function eventDisconnect(event, eventContent, currentPlayers, playerQueue) { + if (!event.includes("ClientD")) { + return false; + } + + const pid = parseInt(eventContent.split(" ")[0], 10); + console.log("Disconnected id:", pid); + + const pindex = searchById(pid, currentPlayers); + if (pindex === -1) { + console.log("Uninitialized client disconnected ID:", pid); + return false; + } + + const player = currentPlayers[pindex]; + + if (player.name) { + network.sendCmd(`say ${player.name} ^1has left the server to pick ^6flowers.`); + } + + console.log("REMOVING AND SAVING PLAYER...\n"); + currentPlayers.splice(pindex, 1); // Remove the player from the currentPlayers array + const queueIndex = searchById(pid, playerQueue); + if (queueIndex !== -1) { + playerQueue.splice(queueIndex, 1); // Remove the player from the playerQueue array + } + return true; +} + +async function eventKill(event, eventContent, currentPlayers) { + if (event.includes("Kill")) { + const pid = parseInt(eventContent.split(" ")[1], 10); + console.log("Death ID:", pid); + + const deadPlayerIndex = searchById(pid, currentPlayers); + if (deadPlayerIndex === -1) { + console.log("Client not initialized, please reconnect.", pid); + return false; + } + + // Additional kill event handling + // ... + } + + return false; +} + function checkLine(line) { if (line.startsWith("Pl")) return true; if (line.startsWith("Shut")) return true;