Spaces:
Sleeping
Sleeping
Download app.js from publicstring/sellersnode: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/spaces/publicstring/sellersnode/resolve/main/app.js
- Command line
-
hf download hf://spaces/publicstring/sellersnode/app.js
-
curl -L -o app.js https://huggingface.co/spaces/publicstring/sellersnode/resolve/main/app.js
30.5 kB
| // server.js | |
| import express from 'express'; | |
| import cors from 'cors'; | |
| import { WebSocketServer, WebSocket } from 'ws'; | |
| import { v4 as uuidv4 } from 'uuid'; | |
| import { | |
| resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE, | |
| attributeCap, featureGateReason, getEvolutionPoints, COMPOSITION_ORDER | |
| } from './mechanics.js'; | |
| const app = express(); | |
| const PORT = process.env.PORT || 7860; | |
| app.use(cors({ | |
| origin: '*', | |
| })); | |
| const MIN_ROOMS = 5; | |
| const ROOM_SAFETY_CAP = 200; | |
| const ROOM_EMPTY_GRACE_MS = 15000; | |
| let roomCounter = 0; | |
| const rooms = {}; | |
| const roomEmptySince = new Map(); | |
| const roomChatLogs = new Map(); | |
| const CHAT_HISTORY_LIMIT = 50; | |
| const BOT_TEMPLATES = [ | |
| { | |
| compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 }, | |
| attributes: { WATER_RETENTION: 2, INSULATION: 0, MUSCLE_DENSITY: 8, BONE_DENSITY: 5, FAT_RESERVES: 2, METABOLIC_RATE: 2, NEURAL_COMPLEXITY: 2, THERMAL_REGULATION: 0, BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0 }, | |
| features: ['CRUSHING_MANDIBLES'], socialType: 'SOLITARY' | |
| }, | |
| { | |
| compositions: { ANIMALIA: 40, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 60, MYCELIUM: 0, MINERALIS: 0 }, | |
| attributes: { WATER_RETENTION: 0, INSULATION: 0, MUSCLE_DENSITY: 2, BONE_DENSITY: 0, FAT_RESERVES: 4, METABOLIC_RATE: 2, NEURAL_COMPLEXITY: 3, THERMAL_REGULATION: 0, BUOYANCY: 5, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 8 }, | |
| features: ['TOXIN_GLANDS', 'GELATINOUS_BODY'], socialType: 'SOLITARY' | |
| }, | |
| { | |
| compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 }, | |
| attributes: { WATER_RETENTION: 2, INSULATION: 0, MUSCLE_DENSITY: 4, BONE_DENSITY: 1, FAT_RESERVES: 2, METABOLIC_RATE: 8, NEURAL_COMPLEXITY: 4, THERMAL_REGULATION: 2, BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0 }, | |
| features: ['SLASHING_BLADES'], socialType: 'PACK' | |
| }, | |
| { | |
| compositions: { ANIMALIA: 50, CHITINARIA: 50, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 }, | |
| attributes: { WATER_RETENTION: 6, INSULATION: 0, MUSCLE_DENSITY: 4, BONE_DENSITY: 4, FAT_RESERVES: 2, METABOLIC_RATE: 3, NEURAL_COMPLEXITY: 4, THERMAL_REGULATION: 4, BUOYANCY: 0, CAMOUFLAGE: 5, REGENERATION: 0, TOXIN_RESISTANCE: 2 }, | |
| features: ['SCORPION_TAIL'], socialType: 'SOLITARY' | |
| } | |
| ]; | |
| // Expanded to 25 unique variants! | |
| const BOT_NAMES = [ | |
| 'Alpha', 'Beta', 'Gamma', 'Delta', 'Omega', | |
| 'Zeta', 'Sigma', 'Prime', 'Apex', 'Titan', | |
| 'Leviathan', 'Chimera', 'Vertex', 'Nebula', 'Pulsar', | |
| 'Quasar', 'Zenith', 'Onyx', 'Kestrel', 'Raptor', | |
| 'Vortex', 'Echo', 'Talon', 'Nova', 'Orion' | |
| ]; | |
| function populateBots(room) { | |
| // Always add between 8 and 12 bots (0-4 + 8) | |
| const numBots = Math.floor(Math.random() * 5) + 8; | |
| for (let i = 0; i < numBots; i++) { | |
| const botId = `bot-${uuidv4()}`; | |
| const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)]; | |
| const randomName = `${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`; | |
| room.players[botId] = { | |
| id: botId, name: randomName, roomId: room.id, | |
| state: JSON.parse(JSON.stringify(template)), ready: true, | |
| score: 0, joinedAt: Date.now(), hasCollectedGift: true, groupId: null | |
| }; | |
| } | |
| } | |
| function randomBiome() { | |
| return ['DESERT', 'RAINFOREST', 'UNDERWATER'][Math.floor(Math.random() * 3)]; | |
| } | |
| function makeRoom() { | |
| roomCounter++; | |
| const id = `room-${roomCounter}`; | |
| const room = { id, status: 'LOBBY', players: {}, startTime: 0, biome: randomBiome(), groups: {}, hasRealPlayers: false }; | |
| populateBots(room); | |
| return room; | |
| } | |
| const ARENA_SIZE = 800; | |
| const SAFE_ZONE_START = 400; | |
| const FOOD_COUNT = 15; | |
| const HUNGER_THRESHOLD = 100; | |
| const MATING_SPAWN_DELAY = 3000; | |
| const RESULTS_DISPLAY_MS = 12000; | |
| const MAX_ROUND_DURATION_MS = 5 * 60_000; | |
| const ZONE_DAMAGE_RATE = 15; | |
| const ZONE_PHASES = [ | |
| { waitMs: 15000, shrinkMs: 20000, targetRadius: 300 }, | |
| { waitMs: 10000, shrinkMs: 15000, targetRadius: 180 }, | |
| { waitMs: 10000, shrinkMs: 15000, targetRadius: 80 }, | |
| { waitMs: 10000, shrinkMs: 20000, targetRadius: 0 }, | |
| ]; | |
| for (let i = 0; i < MIN_ROOMS; i++) { | |
| const r = makeRoom(); | |
| rooms[r.id] = r; | |
| } | |
| function isRoomJoinable(room) { | |
| if (room.status === 'EXTINCTION') return false; | |
| if (!room.hasRealPlayers) return true; | |
| const elapsed = room.startTime ? Date.now() - room.startTime : 0; | |
| const pCount = Object.keys(room.players).length; | |
| return !(pCount >= 2 && elapsed > 60000); | |
| } | |
| const roomStates = new Map(); | |
| function resetRoomToLobby(room) { | |
| room.status = 'LOBBY'; | |
| room.startTime = 0; | |
| room.biome = randomBiome(); | |
| room.groups = {}; | |
| for (const pid of Object.keys(room.players)) { | |
| if (pid.startsWith('offspring-') || pid.startsWith('bot-')) { delete room.players[pid]; continue; } | |
| room.players[pid].ready = false; | |
| room.players[pid].state = JSON.parse(JSON.stringify(INITIAL_STATE)); | |
| } | |
| populateBots(room); | |
| roomStates.delete(room.id); | |
| roomChatLogs.delete(room.id); | |
| roomEmptySince.delete(room.id); | |
| } | |
| function initRoomState(roomId) { | |
| const room = rooms[roomId]; | |
| const colors = ['#67e8f9', '#fbbf24', '#34d399', '#f472b6', '#a78bfa', '#fb923c']; | |
| const initial = {}; | |
| let idx = 0; | |
| Object.values(room.players).forEach((p) => { | |
| const angle = Math.random() * Math.PI * 2; | |
| const dist = Math.random() * 300; | |
| initial[p.id] = { | |
| id: p.id, name: p.name, | |
| x: ARENA_SIZE / 2 + Math.cos(angle) * dist, y: ARENA_SIZE / 2 + Math.sin(angle) * dist, | |
| targetX: ARENA_SIZE / 2 + Math.cos(angle) * dist, targetY: ARENA_SIZE / 2 + Math.sin(angle) * dist, | |
| color: colors[idx % colors.length], dead: false, | |
| hunger: 0, matingCooldown: 0, combatCooldown: 0, offspringCount: 0, envDamage: 0, | |
| }; | |
| idx++; | |
| }); | |
| const food = Array.from({ length: FOOD_COUNT }).map(() => ({ | |
| x: 50 + Math.random() * (ARENA_SIZE - 100), y: 50 + Math.random() * (ARENA_SIZE - 100), | |
| consumed: false, capacity: 100, | |
| })); | |
| roomStates.set(roomId, { | |
| lastTick: Date.now(), tickCount: 0, entities: initial, foodNodes: food, | |
| safeZoneRadius: SAFE_ZONE_START, matingPairs: [], visualEffects: [], | |
| endingSince: null, winner: null, winnerAt: null, | |
| }); | |
| } | |
| function zoneDeathAttacker(biome) { | |
| switch (biome) { | |
| case 'DESERT': return 'The Encroaching Sands'; | |
| case 'RAINFOREST': return 'The Choking Canopy'; | |
| case 'UNDERWATER': return 'The Crushing Depths'; | |
| default: return 'The Shrinking Tide'; | |
| } | |
| } | |
| function sanitizeState(raw) { | |
| try { | |
| const s = { | |
| compositions: { ...INITIAL_STATE.compositions, ...(raw?.compositions || {}) }, | |
| attributes: { ...INITIAL_STATE.attributes, ...(raw?.attributes || {}) }, | |
| features: Array.isArray(raw?.features) ? raw.features.slice(0, 5) : [], | |
| socialType: ['SOLITARY', 'PACK', 'HIVE'].includes(raw?.socialType) ? raw.socialType : 'SOLITARY', | |
| }; | |
| const compSum = COMPOSITION_ORDER.reduce((sum, k) => sum + (Number(s.compositions[k]) || 0), 0); | |
| if (Math.abs(compSum - 100) > 2) return JSON.parse(JSON.stringify(INITIAL_STATE)); | |
| for (const k of Object.keys(s.attributes)) { | |
| const cap = attributeCap(k, s.compositions); | |
| const val = Number(s.attributes[k]) || 0; | |
| s.attributes[k] = Math.max(0, Math.min(val, cap)); | |
| } | |
| s.features = s.features.filter(f => !featureGateReason(f, s.compositions)); | |
| const ep = getEvolutionPoints(s); | |
| if (ep.used > ep.max) return null; | |
| return s; | |
| } catch { | |
| return null; | |
| } | |
| } | |
| app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length })); | |
| app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.')); | |
| const server = app.listen(PORT, '0.0.0.0', () => console.log(`Standalone Backend running on port ${PORT}`)); | |
| const wss = new WebSocketServer({ server }); | |
| const connections = new Map(); | |
| const players = new Map(); | |
| function broadcastAllRooms() { | |
| const str = JSON.stringify({ type: 'ALL_ROOMS', rooms }); | |
| for (const ws of Array.from(connections.values())) { | |
| if (ws.readyState === WebSocket.OPEN) ws.send(str); | |
| } | |
| } | |
| function broadcastRoom(roomId) { | |
| const room = rooms[roomId]; | |
| if (!room) return; | |
| broadcastToRoom(roomId, JSON.stringify({ type: 'ROOM_STATE', room })); | |
| } | |
| function broadcastToRoom(roomId, dataStr) { | |
| const room = rooms[roomId]; | |
| if (!room) return; | |
| for (const pid of Object.keys(room.players)) { | |
| const ws = connections.get(pid); | |
| if (ws && ws.readyState === WebSocket.OPEN) ws.send(dataStr); | |
| } | |
| } | |
| function maybeAddRoom() { | |
| const anyJoinable = Object.values(rooms).some(isRoomJoinable); | |
| if (!anyJoinable && Object.keys(rooms).length < ROOM_SAFETY_CAP) { | |
| const r = makeRoom(); | |
| rooms[r.id] = r; | |
| broadcastAllRooms(); | |
| } | |
| } | |
| function maybeScaleDownRooms() { | |
| const now = Date.now(); | |
| const ids = Object.keys(rooms); | |
| if (ids.length <= MIN_ROOMS) return; | |
| const removable = ids.filter(id => { | |
| const room = rooms[id]; | |
| if (room.status !== 'LOBBY' || Object.keys(room.players).length > 0) { | |
| roomEmptySince.delete(id); | |
| return false; | |
| } | |
| const since = roomEmptySince.get(id); | |
| if (since === undefined) { roomEmptySince.set(id, now); return false; } | |
| return now - since > ROOM_EMPTY_GRACE_MS; | |
| }); | |
| let toRemove = ids.length - MIN_ROOMS; | |
| let changed = false; | |
| for (const id of removable) { | |
| if (toRemove <= 0) break; | |
| delete rooms[id]; | |
| roomEmptySince.delete(id); | |
| toRemove--; | |
| changed = true; | |
| } | |
| if (changed) broadcastAllRooms(); | |
| } | |
| function checkRoomExtinction(roomId) { | |
| const room = rooms[roomId]; | |
| const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-')); | |
| if (realPlayers.length > 0 && Object.keys(room.players).length >= 2 && Object.values(room.players).every(p => p.ready)) { | |
| room.status = 'EXTINCTION'; | |
| room.startTime = Date.now(); | |
| initRoomState(roomId); | |
| broadcastRoom(roomId); | |
| broadcastAllRooms(); | |
| } | |
| } | |
| wss.on('connection', (ws) => { | |
| const playerId = uuidv4(); | |
| connections.set(playerId, ws); | |
| players.set(playerId, { | |
| id: playerId, name: `Player ${playerId.substring(0, 4)}`, | |
| roomId: null, state: null, ready: false, score: 0, | |
| joinedAt: Date.now(), hasCollectedGift: false, groupId: null, | |
| }); | |
| ws.send(JSON.stringify({ type: 'INIT', playerId, rooms })); | |
| ws.on('message', (message) => { | |
| try { | |
| const data = JSON.parse(message.toString()); | |
| const player = players.get(playerId); | |
| if (!player) return; | |
| switch (data.type) { | |
| case 'JOIN_ROOM': { | |
| if (player.roomId && rooms[player.roomId]) { | |
| delete rooms[player.roomId].players[playerId]; | |
| } | |
| const target = rooms[data.roomId]; | |
| if (!target) break; | |
| if (!isRoomJoinable(target)) { | |
| maybeAddRoom(); | |
| ws.send(JSON.stringify({ type: 'JOIN_ROOM_FAILED', roomId: data.roomId, reason: 'Room locked — try the newest room.' })); | |
| break; | |
| } | |
| player.roomId = data.roomId; | |
| player.name = data.name || player.name; | |
| target.players[playerId] = player; | |
| roomEmptySince.delete(data.roomId); | |
| broadcastRoom(data.roomId); | |
| broadcastAllRooms(); | |
| ws.send(JSON.stringify({ type: 'CHAT_HISTORY', messages: roomChatLogs.get(data.roomId) || [] })); | |
| break; | |
| } | |
| case 'LEAVE_ROOM': { | |
| const roomId = player.roomId; | |
| if (roomId && rooms[roomId]) { | |
| const gs = roomStates.get(roomId); | |
| if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) { | |
| gs.entities[playerId].dead = true; | |
| gs.entities[playerId].deathTime = Date.now(); | |
| gs.entities[playerId].deathReason = 'Disconnected'; | |
| } | |
| delete rooms[roomId].players[playerId]; | |
| if (player.groupId && rooms[roomId].groups[player.groupId]) { | |
| rooms[roomId].groups[player.groupId].memberIds = | |
| rooms[roomId].groups[player.groupId].memberIds.filter(id => id !== playerId); | |
| } | |
| broadcastRoom(roomId); | |
| } | |
| player.roomId = null; | |
| player.ready = false; | |
| broadcastAllRooms(); | |
| break; | |
| } | |
| case 'UPDATE_STATE': { | |
| const clean = sanitizeState(data.state); | |
| if (clean) { | |
| player.state = clean; | |
| if (player.roomId) { | |
| rooms[player.roomId].players[playerId] = player; | |
| broadcastRoom(player.roomId); | |
| } | |
| } | |
| break; | |
| } | |
| case 'SET_READY': { | |
| player.ready = data.ready; | |
| if (player.roomId) { | |
| rooms[player.roomId].players[playerId] = player; | |
| checkRoomExtinction(player.roomId); | |
| broadcastRoom(player.roomId); | |
| } | |
| break; | |
| } | |
| case 'CHAT': { | |
| if (player.roomId) { | |
| const entry = { from: player.name, text: data.text, timestamp: Date.now() }; | |
| const log = roomChatLogs.get(player.roomId) || []; | |
| log.push(entry); | |
| if (log.length > CHAT_HISTORY_LIMIT) log.splice(0, log.length - CHAT_HISTORY_LIMIT); | |
| roomChatLogs.set(player.roomId, log); | |
| broadcastToRoom(player.roomId, JSON.stringify({ type: 'CHAT_MSG', ...entry })); | |
| } | |
| break; | |
| } | |
| case 'SEND_GIFT': { | |
| const target = players.get(data.toPlayerId); | |
| if (!target) break; | |
| const isNoob = Date.now() - target.joinedAt < 15000 && !target.hasCollectedGift; | |
| if (isNoob) { | |
| target.hasCollectedGift = true; | |
| player.score += 10; | |
| const result = { type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: true, giverReward: 10, giverId: player.id }; | |
| ws.send(JSON.stringify(result)); | |
| const targetWs = connections.get(target.id); | |
| if (targetWs) targetWs.send(JSON.stringify(result)); | |
| } else { | |
| ws.send(JSON.stringify({ type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: false, giverReward: 0, giverId: player.id })); | |
| } | |
| break; | |
| } | |
| case 'CREATE_GROUP': | |
| case 'JOIN_GROUP': { | |
| if (!player.roomId) break; | |
| const room = rooms[player.roomId]; | |
| if (!room) break; | |
| if (data.type === 'CREATE_GROUP') { | |
| const gid = uuidv4(); | |
| room.groups[gid] = { id: gid, name: data.name, memberIds: [playerId] }; | |
| player.groupId = gid; | |
| } else { | |
| const g = room.groups[data.groupId]; | |
| if (g && !g.memberIds.includes(playerId)) { | |
| if (player.groupId && room.groups[player.groupId]) { | |
| room.groups[player.groupId].memberIds = | |
| room.groups[player.groupId].memberIds.filter(id => id !== playerId); | |
| } | |
| g.memberIds.push(playerId); | |
| player.groupId = data.groupId; | |
| } | |
| } | |
| broadcastRoom(player.roomId); | |
| break; | |
| } | |
| } | |
| } catch (e) { | |
| console.error('WS parse error', e); | |
| } | |
| }); | |
| ws.on('close', () => { | |
| const player = players.get(playerId); | |
| if (player && player.roomId) { | |
| const roomId = player.roomId; | |
| const room = rooms[roomId]; | |
| const gs = roomStates.get(roomId); | |
| if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) { | |
| gs.entities[playerId].dead = true; | |
| gs.entities[playerId].deathTime = Date.now(); | |
| gs.entities[playerId].deathReason = 'Disconnected'; | |
| } | |
| if (room) { | |
| delete room.players[playerId]; | |
| if (player.groupId && room.groups[player.groupId]) { | |
| room.groups[player.groupId].memberIds = room.groups[player.groupId].memberIds.filter(id => id !== playerId); | |
| } | |
| broadcastRoom(roomId); | |
| broadcastAllRooms(); | |
| } | |
| } | |
| connections.delete(playerId); | |
| players.delete(playerId); | |
| }); | |
| }); | |
| let globalTick = 0; | |
| setInterval(() => { | |
| globalTick++; | |
| let stateChanged = false; | |
| const now = Date.now(); | |
| if (globalTick % 40 === 0) maybeScaleDownRooms(); | |
| for (const roomId in rooms) { | |
| const room = rooms[roomId]; | |
| const pCount = Object.keys(room.players).length; | |
| const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-')); | |
| if (room.status === 'LOBBY' && pCount > 0) { | |
| room.status = 'CRAFTING'; | |
| room.hasRealPlayers = realPlayers.length > 0; | |
| room.startTime = now; | |
| stateChanged = true; | |
| } else if (room.status === 'CRAFTING') { | |
| if (realPlayers.length > 0 && !room.hasRealPlayers) { | |
| room.hasRealPlayers = true; | |
| room.startTime = now - 50000; | |
| stateChanged = true; | |
| } else if (realPlayers.length === 0) { | |
| room.startTime = now; | |
| room.hasRealPlayers = false; | |
| } | |
| const elapsed = now - room.startTime; | |
| if ((elapsed >= 120000 || (pCount >= 2 && Object.values(room.players).every(p => p.ready))) && realPlayers.length > 0) { | |
| room.status = 'EXTINCTION'; | |
| room.startTime = now; | |
| initRoomState(roomId); | |
| stateChanged = true; | |
| maybeAddRoom(); | |
| } | |
| } else if (room.status === 'EXTINCTION') { | |
| const gs = roomStates.get(roomId); | |
| if (gs?.winner) { | |
| if (gs.winnerAt === null) gs.winnerAt = now; | |
| if (realPlayers.length === 0 || now - gs.winnerAt > RESULTS_DISPLAY_MS) { | |
| resetRoomToLobby(room); | |
| stateChanged = true; | |
| } | |
| continue; | |
| } | |
| if (realPlayers.length === 0 && now - room.startTime > 5000) { | |
| resetRoomToLobby(room); | |
| stateChanged = true; | |
| continue; | |
| } | |
| if (!gs) continue; | |
| const dt = Math.min(0.1, (now - gs.lastTick) / 1000); | |
| gs.lastTick = now; | |
| gs.tickCount++; | |
| const roundElapsed = now - room.startTime; | |
| let currentRadius = SAFE_ZONE_START; | |
| let accumTime = 0; | |
| for (const p of ZONE_PHASES) { | |
| if (roundElapsed < accumTime + p.waitMs) break; | |
| accumTime += p.waitMs; | |
| if (roundElapsed < accumTime + p.shrinkMs) { | |
| const progress = (roundElapsed - accumTime) / p.shrinkMs; | |
| currentRadius = currentRadius - (currentRadius - p.targetRadius) * progress; | |
| break; | |
| } | |
| accumTime += p.shrinkMs; | |
| currentRadius = p.targetRadius; | |
| } | |
| gs.safeZoneRadius = currentRadius; | |
| gs.visualEffects = gs.visualEffects.filter(fx => now - fx.timestamp < 1000); | |
| const pendingLogs = []; | |
| let needsPlayerBroadcast = false; | |
| const isPaired = (id) => gs.matingPairs.some(mp => !mp.done && (mp.a === id || mp.b === id)); | |
| for (const k in gs.entities) { | |
| if (gs.entities[k].dead && now - (gs.entities[k].deathTime || 0) > 10000) { | |
| delete gs.entities[k]; | |
| } | |
| } | |
| const activeKeys = Object.keys(gs.entities).filter(k => !gs.entities[k].dead); | |
| for (const k of activeKeys) { | |
| const e = gs.entities[k]; | |
| for (const otherK of activeKeys) { | |
| if (k === otherK) continue; | |
| const other = gs.entities[otherK]; | |
| const dx = e.x - other.x, dy = e.y - other.y; | |
| const dist = Math.hypot(dx, dy); | |
| if (dist > 0 && dist < 15) { | |
| const push = ((15 - dist) / 15) * 10 * dt; | |
| e.x += (dx / dist) * push; e.y += (dy / dist) * push; | |
| } | |
| } | |
| } | |
| for (const k of activeKeys) { | |
| const e = gs.entities[k]; | |
| const stateA = room.players[k]?.state; | |
| if (!stateA) { | |
| if (!e.dead) { e.dead = true; e.deathTime = now; e.deathReason = 'No Blueprint'; } | |
| continue; | |
| } | |
| const derivedA = getDerivedStats(stateA, room.biome); | |
| if (isPaired(k)) { | |
| const angle = Math.atan2(ARENA_SIZE / 2 - e.y, ARENA_SIZE / 2 - e.x); | |
| e.x += Math.cos(angle) * derivedA.speed * 0.3 * dt; | |
| e.y += Math.sin(angle) * derivedA.speed * 0.3 * dt; | |
| continue; | |
| } | |
| const distToCenter = Math.hypot(e.x - ARENA_SIZE / 2, e.y - ARENA_SIZE / 2); | |
| const outsideZone = distToCenter > gs.safeZoneRadius; | |
| if (outsideZone) { | |
| e.targetX = ARENA_SIZE / 2; e.targetY = ARENA_SIZE / 2; | |
| const overshoot = distToCenter - gs.safeZoneRadius; | |
| const severity = 1 + Math.min(3, overshoot / 100); | |
| e.envDamage += ZONE_DAMAGE_RATE * severity * dt; | |
| } | |
| let envDmgRate = 0; | |
| if (room.biome === 'UNDERWATER' && !derivedA.aquatic && stateA.compositions.CNIDARIA < 30 && stateA.attributes.BUOYANCY < 3) { | |
| envDmgRate = 12; | |
| } else if (room.biome === 'DESERT') { | |
| envDmgRate = derivedA.desiccationRate * 4; | |
| } | |
| if (envDmgRate > 0) e.envDamage += envDmgRate * dt; | |
| if (room.biome === 'RAINFOREST' && stateA.compositions.PLANTAE >= 30) { | |
| e.hunger = Math.max(0, e.hunger - dt * 0.5); | |
| } | |
| if (e.envDamage >= derivedA.hp) { | |
| e.dead = true; e.deathTime = now; | |
| e.deathReason = distToCenter > gs.safeZoneRadius ? 'Caught in Zone' : (room.biome === 'UNDERWATER' ? 'Drowned' : 'Desiccated'); | |
| pendingLogs.push({ id: Math.random().toString(), attacker: zoneDeathAttacker(room.biome), defender: e.name, attackerWon: true, notes: [e.deathReason] }); | |
| continue; | |
| } | |
| const PANIC_RETURN_SPEED = 20; | |
| const baseSpeed = derivedA.speed * 0.8; | |
| const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0); | |
| const isBot = k.startsWith('bot-'); | |
| let aiTarget = null; | |
| if (isBot) { | |
| const zoneMargin = gs.safeZoneRadius - distToCenter; | |
| if (zoneMargin < 60) { | |
| const urgency = 1 - Math.max(0, zoneMargin / 60); | |
| aiTarget = { x: ARENA_SIZE / 2 + (e.x - ARENA_SIZE / 2) * (1 - urgency * 0.8), y: ARENA_SIZE / 2 + (e.y - ARENA_SIZE / 2) * (1 - urgency * 0.8) }; | |
| } | |
| if (!aiTarget && e.hunger > 20) { | |
| const food = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < derivedA.detection && Math.hypot(f.x - ARENA_SIZE/2, f.y - ARENA_SIZE/2) < gs.safeZoneRadius * 0.85); | |
| if (food) aiTarget = { x: food.x, y: food.y }; | |
| } | |
| if (!aiTarget) { | |
| for (const otherK of activeKeys) { | |
| if (otherK === k) continue; | |
| const other = gs.entities[otherK]; | |
| const dist = Math.hypot(e.x - other.x, e.y - other.y); | |
| if (dist < derivedA.detection * 0.7) { | |
| const stateB = room.players[otherK]?.state; | |
| if (stateB && getDerivedStats(stateB, room.biome).hp > derivedA.hp * 1.3) { | |
| const fleeAngle = Math.atan2(e.y - other.y, e.x - other.x); | |
| aiTarget = { x: e.x + Math.cos(fleeAngle) * 100, y: e.y + Math.sin(fleeAngle) * 100 }; | |
| break; | |
| } | |
| } | |
| } | |
| } | |
| if (aiTarget) { e.targetX = aiTarget.x; e.targetY = aiTarget.y; } | |
| } | |
| if (!outsideZone && !isBot) { | |
| if (e.hunger > 15) { | |
| const nearFood = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < derivedA.detection * 0.8 && Math.hypot(f.x - ARENA_SIZE/2, f.y - ARENA_SIZE/2) < gs.safeZoneRadius * 0.9); | |
| if (nearFood) { e.targetX = nearFood.x; e.targetY = nearFood.y; } | |
| } else if (Math.hypot(e.targetX - e.x, e.targetY - e.y) < 12) { | |
| const a = Math.random() * Math.PI * 2; | |
| const r = Math.random() * gs.safeZoneRadius * 0.8; | |
| e.targetX = ARENA_SIZE / 2 + Math.cos(a) * r; | |
| e.targetY = ARENA_SIZE / 2 + Math.sin(a) * r; | |
| } | |
| } | |
| const moveAngle = Math.atan2(e.targetY - e.y, e.targetX - e.x); | |
| e.x = Math.max(10, Math.min(ARENA_SIZE - 10, e.x + Math.cos(moveAngle) * moveSpeed * dt)); | |
| e.y = Math.max(10, Math.min(ARENA_SIZE - 10, e.y + Math.sin(moveAngle) * moveSpeed * dt)); | |
| if (e.hunger > 15) { | |
| const nearFood = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < 25); | |
| if (nearFood) { | |
| const eatAmount = Math.min(e.hunger, 40 * dt, nearFood.capacity); | |
| nearFood.capacity -= eatAmount; | |
| e.hunger -= eatAmount; | |
| if (nearFood.capacity <= 0) nearFood.consumed = true; | |
| } | |
| } | |
| e.hunger += (derivedA.energyDemand / 20) * dt; | |
| if (e.hunger > HUNGER_THRESHOLD) { | |
| e.dead = true; e.deathTime = now; e.deathReason = 'Starved'; | |
| pendingLogs.push({ id: Math.random().toString(), attacker: 'Environment', defender: e.name, attackerWon: true, notes: ['Starvation'] }); | |
| continue; | |
| } | |
| if (e.matingCooldown > 0) e.matingCooldown = Math.max(0, e.matingCooldown - dt); | |
| if (e.combatCooldown > 0) e.combatCooldown = Math.max(0, e.combatCooldown - dt); | |
| for (const otherK of activeKeys) { | |
| if (k === otherK) continue; | |
| const other = gs.entities[otherK]; | |
| if (other.dead) continue; | |
| const stateB = room.players[otherK]?.state; | |
| if (!stateB) continue; | |
| const dist = Math.hypot(e.x - other.x, e.y - other.y); | |
| const combatRange = Math.max(35, moveSpeed * dt * 2 + 20); | |
| if (dist >= combatRange) continue; | |
| const canSee = dist < derivedA.detection * 0.6; | |
| if (!canSee && dist > 40) continue; | |
| if (stateA.socialType !== 'SOLITARY' && stateA.socialType === stateB.socialType && e.matingCooldown <= 0 && other.matingCooldown <= 0) { | |
| e.matingCooldown = 15; other.matingCooldown = 15; | |
| const midX = (e.x + other.x) / 2, midY = (e.y + other.y) / 2; | |
| gs.matingPairs.push({ a: k, b: otherK, gasX: midX, gasY: midY, startTime: now, done: false }); | |
| break; | |
| } | |
| if (e.combatCooldown <= 0 && other.combatCooldown <= 0) { | |
| const result = resolveCombat(stateA, stateB, room.biome); | |
| const attackTag = result.breakdown.primaryTag || 'CRUSH'; | |
| const outcome = result.breakdown.isShatter ? 'Shatter' : 'Normal'; | |
| if (result.breakdown.evaded) { | |
| e.combatCooldown = 1.2; other.combatCooldown = 1.2; | |
| pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: false, notes: [...result.breakdown.notes, `${other.name} evaded`] }); | |
| } else { | |
| gs.visualEffects.push({ id: Math.random().toString(), x: (e.x + other.x) / 2, y: (e.y + other.y) / 2, timestamp: now, attackTag, outcome }); | |
| pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: result.won, notes: result.breakdown.notes }); | |
| if (result.won) { | |
| other.dead = true; other.deathTime = now; other.deathReason = attackTag; | |
| } else { | |
| e.dead = true; e.deathTime = now; e.deathReason = attackTag; break; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| gs.matingPairs = gs.matingPairs.filter(mp => now - mp.startTime < 4000).map(mp => { | |
| if (!mp.done && now - mp.startTime > MATING_SPAWN_DELAY) { | |
| const stateA = room.players[mp.a]?.state; | |
| const stateB = room.players[mp.b]?.state; | |
| if (stateA && stateB && gs.entities[mp.a] && !gs.entities[mp.a].dead) { | |
| const offId = `offspring-${mp.a}-${gs.tickCount}`; | |
| const offspringState = breedOffspring(stateA, stateB); | |
| const distToCenter = Math.hypot(mp.gasX - ARENA_SIZE/2, mp.gasY - ARENA_SIZE/2); | |
| let spawnX = mp.gasX, spawnY = mp.gasY; | |
| if (distToCenter > gs.safeZoneRadius - 10) { | |
| const angle = Math.atan2(mp.gasY - ARENA_SIZE/2, mp.gasX - ARENA_SIZE/2); | |
| spawnX = ARENA_SIZE/2 + Math.cos(angle) * (gs.safeZoneRadius - 20); | |
| spawnY = ARENA_SIZE/2 + Math.sin(angle) * (gs.safeZoneRadius - 20); | |
| } | |
| gs.entities[offId] = { | |
| id: offId, name: `${gs.entities[mp.a].name}'s spawn`, | |
| x: spawnX + (Math.random() - 0.5) * 40, y: spawnY + (Math.random() - 0.5) * 40, | |
| targetX: spawnX, targetY: spawnY, color: gs.entities[mp.a].color, | |
| dead: false, hunger: 0, matingCooldown: 5, combatCooldown: 1, offspringCount: 0, envDamage: 0 | |
| }; | |
| gs.entities[mp.a].offspringCount++; | |
| if (gs.entities[mp.b]) gs.entities[mp.b].offspringCount++; | |
| room.players[offId] = { | |
| id: offId, name: gs.entities[offId].name, roomId: roomId, | |
| state: offspringState, ready: true, score: 0, | |
| joinedAt: Date.now(), hasCollectedGift: true, groupId: null, | |
| }; | |
| needsPlayerBroadcast = true; | |
| } | |
| return { ...mp, done: true }; | |
| } | |
| return mp; | |
| }); | |
| broadcastToRoom(roomId, JSON.stringify({ | |
| type: 'EXTINCTION_TICK', | |
| state: { | |
| entities: gs.entities, foodNodes: gs.foodNodes, safeZoneRadius: gs.safeZoneRadius, | |
| matingPairs: gs.matingPairs, visualEffects: gs.visualEffects | |
| }, | |
| logs: pendingLogs | |
| })); | |
| if (needsPlayerBroadcast) broadcastRoom(roomId); | |
| const all = Object.values(gs.entities); | |
| const alive = all.filter(e => !e.dead); | |
| if ((all.length > 1 && alive.length <= 1) || (all.length === 1 && alive.length === 0)) { | |
| if (!gs.endingSince) gs.endingSince = now; | |
| } else if (roundElapsed > MAX_ROUND_DURATION_MS) { | |
| if (!gs.endingSince) gs.endingSince = now; | |
| } else { | |
| gs.endingSince = null; | |
| } | |
| if (gs.endingSince && (now - gs.endingSince > 4000) && !gs.winner) { | |
| if (roundElapsed > MAX_ROUND_DURATION_MS) { | |
| const ranked = [...alive].sort((a, b) => b.offspringCount - a.offspringCount); | |
| gs.winner = ranked.length > 0 ? `${ranked[0].name} (sudden death)` : 'No survivors'; | |
| } else { | |
| gs.winner = alive.length === 1 ? alive[0].name : 'No survivors'; | |
| } | |
| gs.winnerAt = now; | |
| broadcastToRoom(roomId, JSON.stringify({ type: 'EXTINCTION_END', winner: gs.winner })); | |
| } | |
| } | |
| } | |
| if (stateChanged) broadcastAllRooms(); | |
| }, 50); |