// ============================================ // EUPHORICDOOM - GAME ENGINE v0.8.3 // ============================================ // ===== ITEM & WORLD DATA ===== const ITEMS_DB = { 'synth-coke': { name: 'Synth-Coke', icon: 'fa-pills', color: 'text-purple-400', category: 'drug', basePrice: 80, volatile: true, description: 'Highly addictive synthetic stimulant. Banned in all districts.' }, 'hack-chip': { name: 'Hacker Chip', icon: 'fa-microchip', color: 'text-cyan-400', category: 'tech', basePrice: 350, volatile: false, description: 'Military-grade hacking implant. Enables digital infiltration.' }, 'warehouse-key': { name: 'Warehouse Key', icon: 'fa-key', color: 'text-pink-400', category: 'key', basePrice: 0, volatile: false, description: 'Key to the Warehouse District smuggling hub.', tradeable: false }, 'stim-pack': { name: 'Stim Pack', icon: 'fa-syringe', color: 'text-green-400', category: 'medical', basePrice: 120, volatile: false, description: 'Combat stimulant. Restores 30 HP instantly.' }, 'echo-revolver': { name: 'Echo Revolver', icon: 'fa-crosshairs', color: 'text-purple-400', category: 'weapon', basePrice: 1800, volatile: false, description: 'Sonic handgun with confuse effect and carnival bell critical sounds.' }, 'ringmaster-crown': { name: "Ringmaster's Crown", icon: 'fa-crown', color: 'text-yellow-400', category: 'relic', basePrice: 1200, volatile: false, description: 'Passive bonus to reputation interactions.' }, 'circuit-heart': { name: 'Heart of the Circuit Priest', icon: 'fa-heart', color: 'text-cyan-400', category: 'relic', basePrice: 2500, volatile: false, description: 'Poison immunity at the cost of extreme DOT vulnerability.' }, 'broker-terminal': { name: "Broker's Terminal", icon: 'fa-laptop-code', color: 'text-green-400', category: 'tech', basePrice: 900, volatile: false, description: 'Portable insider stock trading device.' }, 'glass-veins-serum': { name: 'Glass Veins Serum', icon: 'fa-vial', color: 'text-blue-400', category: 'mutation-serum', basePrice: 600, volatile: true, description: 'Massive movement speed bonus, extreme bleeding weakness.' }, 'neural-dampener': { name: 'Neural Dampener', icon: 'fa-brain', color: 'text-indigo-400', category: 'tech', basePrice: 450, volatile: false, description: 'Blocks dreamworld intrusion for 24 hours.' }, 'shadow-cloak': { name: 'Shadow Cloak', icon: 'fa-user-secret', color: 'text-gray-400', category: 'armor', basePrice: 700, volatile: false, description: '+15% evasion in all encounters.' }, 'plasma-knife': { name: 'Plasma Knife', icon: 'fa-cut', color: 'text-red-400', category: 'weapon', basePrice: 280, volatile: false, description: 'Silent melee weapon. +8 critical hit chance.' }, 'adrenal-shot': { name: 'Adrenal Shot', icon: 'fa-syringe', color: 'text-orange-400', category: 'medical', basePrice: 200, volatile: false, description: 'Boosts all stats by 3 for one encounter.' }, 'data-frag': { name: 'Data Fragment', icon: 'fa-file-code', color: 'text-cyan-400', category: 'tech', basePrice: 50, volatile: false, description: 'Encrypted data worth credits to the right buyer.' }, 'chem-vial': { name: 'Raw Chemical Vial', icon: 'fa-flask', color: 'text-green-400', category: 'component', basePrice: 30, volatile: false, description: 'Base component for crafting drugs and stims.' }, 'circuit-board': { name: 'Salvaged Circuit Board', icon: 'fa-microchip', color: 'text-yellow-600', category: 'component', basePrice: 40, volatile: false, description: 'Base component for crafting tech items.' }, 'relic-shard': { name: 'Relic Shard', icon: 'fa-gem', color: 'text-purple-400', category: 'component', basePrice: 150, volatile: false, description: 'Mysterious fragment pulsing with unknown energy.' } }; const DISTRICTS_DB = { 'ash-market': { name: 'Ash Market District', color: '#ff2a6d', icon: 'fa-store-alt', description: 'The beating heart of black market commerce. Auctions, deals, and betrayal.', threatLevel: 'Moderate', available: true, priceModifier: 1.0, marketBias: 'balanced' }, 'warehouse': { name: 'Warehouse District', color: '#ff2a6d', icon: 'fa-warehouse', description: 'Industrial smuggling hub. Cheap goods, dangerous allies.', threatLevel: 'High', available: true, priceModifier: 0.85, marketBias: 'cheap' }, 'carnival': { name: 'Carnival Grounds', color: '#05d9e8', icon: 'fa-theater-masks', description: 'Where nightmare and spectacle collide. Strange relics and darker secrets.', threatLevel: 'Variable', available: true, priceModifier: 1.2, marketBias: 'expensive' }, 'bankers-row': { name: "Banker's Row", color: '#d300c5', icon: 'fa-university', description: 'The legitimate facade of corruption. Stock exchange and loan sharks.', threatLevel: 'Low', available: true, priceModifier: 1.1, marketBias: 'expensive' }, 'digital-sewers': { name: 'Digital Sewers', color: '#05d9e8', icon: 'fa-network-wired', description: 'Hacker underground. Tech items and data trades.', threatLevel: 'High', available: false, unlockCost: 2000, priceModifier: 0.9, marketBias: 'cheap' }, 'bleaks-domain': { name: "Bleak's Domain", color: '#ffd700', icon: 'fa-skull-crossbones', description: 'The loan shark empire. Enter only if you owe or dare.', threatLevel: 'Extreme', available: false, unlockCost: 5000, priceModifier: 0.75, marketBias: 'cheap' } }; const FACTIONS_DB = { 'red-sash': { name: 'Red Sash Cartel', color: 'bg-red-700', abbr: 'RS', description: 'Dominant drug empire. Control synth-coke trade and street-level enforcement.', bonus: '+15% drug prices when friendly' }, 'dust-collective': { name: 'Dust Collective', color: 'bg-blue-700', abbr: 'DC', description: 'Militant tech runners. Control hardware and data smuggling.', bonus: '+15% tech prices when friendly' }, 'digital-saints': { name: 'Digital Saints', color: 'bg-green-700', abbr: 'DS', description: 'Hacker collective. Control digital infrastructure and information.', bonus: '-10% hacking tool costs when friendly' }, 'independent-mercs': { name: 'Independent Mercs', color: 'bg-orange-700', abbr: 'IM', description: 'Freelance muscle and fixers. No loyalty but no vendettas either.', bonus: '+10% quest rewards when friendly' } }; const MUTATIONS_DB = { 'night-vision': { name: 'Night Vision', icon: 'fa-eye', color: 'text-pink-400', description: 'Enhanced low-light perception. +3 Perception.', statBonus: { perception: 3 }, risk: 'none' }, 'adaptive-reflexes': { name: 'Adaptive Reflexes', icon: 'fa-running', color: 'text-cyan-400', description: 'Reaction time accelerates in combat. +4 Agility.', statBonus: { agility: 4 }, risk: 'none' }, 'glass-veins': { name: 'Glass Veins', icon: 'fa-tint', color: 'text-blue-400', description: 'Massive movement speed bonus, extreme bleeding weakness.', statBonus: { agility: 8 }, statPenalty: { endurance: -5 }, risk: 'high' }, 'circuit-touched': { name: 'Circuit Touched', icon: 'fa-bolt', color: 'text-yellow-400', description: 'Electronic interference aura. +3 Intelligence, tech items cheaper.', statBonus: { intelligence: 3 }, risk: 'medium' }, 'iron-gut': { name: 'Iron Gut', icon: 'fa-shield-alt', color: 'text-green-400', description: 'Poison resistance and +4 Endurance.', statBonus: { endurance: 4 }, risk: 'low' }, 'phantom-limb': { name: 'Phantom Limb', icon: 'fa-hand-sparkles', color: 'text-purple-400', description: 'Ghostly appendage. Can interact with digital objects. +2 Intelligence.', statBonus: { intelligence: 2 }, risk: 'medium' }, 'berserker-adrenal': { name: 'Berserker Adrenal', icon: 'fa-fire', color: 'text-red-400', description: '+6 Strength in combat, -3 Intelligence.', statBonus: { strength: 6 }, statPenalty: { intelligence: -3 }, risk: 'high' } }; const QUESTS_DB = { 'painted-veil': { name: 'The Painted Veil', description: 'Smuggle rare compounds for the Red Sash Cartel or sabotage them for rivals.', type: 'trade', faction: 'red-sash', steps: 5, rewards: { credits: 250, xp: 150, faction: { 'red-sash': 10 } }, alternativeRewards: { credits: 180, xp: 120, faction: { 'dust-collective': 15 } } }, 'bankroll-bone': { name: 'Bankroll & Bone Marrow', description: 'Borrow from Mr. Bleak and either repay — or face endless hunters.', type: 'survival', faction: null, steps: 7, rewards: { credits: 500, xp: 300 } }, 'laughter-fog': { name: 'Laughter in the Fog', description: 'Investigate missing traders tied to the mythic "Clownfather".', type: 'investigation', faction: null, steps: 3, rewards: { credits: 0, xp: 400, item: 'ringmaster-crown' } }, 'electric-prophet': { name: 'The Electric Prophet', description: 'Enter Dreamworld missions to uncover deep mutation secrets.', type: 'mutation', faction: 'digital-saints', steps: 4, rewards: { xp: 350, mutation: 'circuit-touched' } }, 'crash-77': { name: "Market Crash '77", description: 'Manipulate or ride a collapsing megacorp to earn life-changing profits.', type: 'market', faction: null, steps: 6, rewards: { credits: 3000, xp: 500 } } }; const RECIPES_DB = { 'synth-coke': { name: 'Synth-Coke', ingredients: { 'chem-vial': 3, 'relic-shard': 1 }, output: 5, category: 'drug', xp: 25 }, 'stim-pack': { name: 'Stim Pack', ingredients: { 'chem-vial': 2 }, output: 1, category: 'medical', xp: 15 }, 'adrenal-shot': { name: 'Adrenal Shot', ingredients: { 'chem-vial': 2, 'circuit-board': 1 }, output: 1, category: 'medical', xp: 20 }, 'hack-chip': { name: 'Hacker Chip', ingredients: { 'circuit-board': 3, 'data-frag': 2 }, output: 1, category: 'tech', xp: 40 }, 'neural-dampener': { name: 'Neural Dampener', ingredients: { 'circuit-board': 2, 'data-frag': 3, 'relic-shard': 1 }, output: 1, category: 'tech', xp: 50 } }; const STOCKS_DB = { 'NDC': { name: 'NeonData Corp', price: 145.2, volatility: 0.6 }, 'RSX': { name: 'RedSash Express', price: 78.8, volatility: 0.9 }, 'DEP': { name: 'Digital Ether Protocols', price: 312.5, volatility: 0.4 }, 'BKL': { name: "Bleak Financial Group", price: 89.1, volatility: 0.7 }, 'CRN': { name: 'Carnival Industries', price: 203.7, volatility: 0.8 } }; const EVENTS_POOL = [ { text: 'Dust Collective raids in Warehouse District', effect: { 'weapon': 1.15, 'tech': 0.95 }, type: 'danger' }, { text: 'Red Sash Cartel flooding market with synth-coke', effect: { 'drug': 0.78 }, type: 'warning' }, { text: 'Digital Saints hacked Banker\'s Row', effect: { 'tech': 1.2, 'financial-risk': 1.08 }, type: 'info' }, { text: 'Mr. Bleak offering 12% interest loans for 48 hours', effect: { 'loan-available': true }, type: 'opportunity' }, { text: 'Carnival Industries stock surges on relic discovery', effect: { 'CRN-stock': 1.25 }, type: 'opportunity' }, { text: 'Warehouse fire destroys supply chain', effect: { 'drug': 1.2, 'component': 1.3 }, type: 'danger' }, { text: 'New mutation outbreak reported in Digital Sewers', effect: { 'mutation-serum': 0.7 }, type: 'warning' }, { text: 'Clownfather sighting reported near Carnival Grounds', effect: { 'relic': 1.15 }, type: 'info' }, { text: 'Peace treaty between Red Sash and Dust Collective', effect: { 'drug': 1.1, 'weapon': 0.9 }, type: 'opportunity' }, { text: 'Underground fighting ring busted in Ash Market', effect: { 'weapon': 1.1, 'medical': 0.85 }, type: 'danger' } ]; const NPCS_DB = { 'madame-karna': { name: 'Madame Karna', role: 'Auctioneer', district: 'ash-market', quote: 'Every relic has a price. Every soul has a discount.' }, 'mr-bleak': { name: 'Mr. Bleak', role: 'Loan Shark King', district: 'bankers-row', quote: 'Interest compounds. So does suffering.' }, 'echo-93': { name: 'Echo-93', role: 'Dreamwalker AI', district: 'digital-sewers', quote: 'I exist between frequencies. Can you hear me?' }, 'the-clownfather': { name: 'The Clownfather', role: 'Mythic Auctioneer', district: 'carnival', quote: 'Laughter is the only honest currency.' } }; // ===== GAME STATE ===== const DEFAULT_STATE = { player: { name: 'VEIL', class: 'Smuggler', level: 3, xp: 450, xpToNext: 1000, credits: 4720, hp: 80, maxHp: 100, statPoints: 0, stats: { charisma: 12, agility: 18, intelligence: 10, strength: 8, endurance: 14, luck: 15 } }, inventory: [ { id: 'synth-coke', qty: 5 }, { id: 'hack-chip', qty: 1 }, { id: 'warehouse-key', qty: 1 }, { id: 'stim-pack', qty: 2 } ], mutations: ['night-vision', 'adaptive-reflexes'], quests: { active: [ { id: 'painted-veil', progress: 2 }, { id: 'bankroll-bone', progress: 3 }, { id: 'laughter-fog', progress: 1 } ], completed: [], available: ['electric-prophet', 'crash-77'] }, factions: { 'red-sash': { reputation: 0, status: 'Neutral' }, 'dust-collective': { reputation: 25, status: 'Friendly' }, 'digital-saints': { reputation: -10, status: 'Wary' }, 'independent-mercs': { reputation: 5, status: 'Neutral' } }, market: {}, stocks: {}, currentDistrict: 'ash-market', unlockedDistricts: ['ash-market', 'warehouse', 'carnival', 'bankers-row'], safehouses: { 'ash-market': { owned: true, level: 1, bonus: 'Passive income: +50cr/day' } }, loans: [{ lender: 'Mr. Bleak', amount: 1500, interest: 0.12, daysLeft: 4, dailyInterest: 180 }], day: 3, time: 8, events: [], auction: { currentItems: ['ringmaster-crown', 'circuit-heart', 'echo-revolver'], dialogue: [] }, combatLog: [], log: [] }; let GS = {}; function loadGame() { const saved = localStorage.getItem('euphoricdoom_save'); if (saved) { try { GS = JSON.parse(saved); // Merge new properties from DEFAULT_STATE that might not exist in save for (const key in DEFAULT_STATE) { if (!(key in GS)) GS[key] = DEFAULT_STATE[key]; } // Merge nested player properties for (const key in DEFAULT_STATE.player) { if (!(key in GS.player)) GS.player[key] = DEFAULT_STATE.player[key]; } } catch (e) { GS = JSON.parse(JSON.stringify(DEFAULT_STATE)); } } else { GS = JSON.parse(JSON.stringify(DEFAULT_STATE)); } // Initialize market prices initMarketPrices(); initStockPrices(); } function saveGame() { localStorage.setItem('euphoricdoom_save', JSON.stringify(GS)); } function resetGame() { if (confirm('Are you sure you want to reset all progress? This cannot be undone!')) { localStorage.removeItem('euphoricdoom_save'); GS = JSON.parse(JSON.stringify(DEFAULT_STATE)); initMarketPrices(); initStockPrices(); saveGame(); refreshAllUI(); showToast('Game reset! Fresh start.', 'warning'); } } // ===== MARKET PRICE INITIALIZATION ===== function initMarketPrices() { Object.keys(ITEMS_DB).forEach(id => { if (!GS.market[id]) { const base = ITEMS_DB[id].basePrice; GS.market[id] = { currentPrice: base > 0 ? Math.round(base * (0.85 + Math.random() * 0.3)) : 0, supply: Math.floor(Math.random() * 20) + 5, demand: Math.floor(Math.random() * 20) + 5, trend: (Math.random() - 0.5) * 0.1 }; } }); } function initStockPrices() { Object.keys(STOCKS_DB).forEach(id => { if (!GS.stocks[id]) { GS.stocks[id] = { price: STOCKS_DB[id].price, shares: 0, history: [STOCKS_DB[id].price] }; } }); } // ===== UTILITY ===== function random(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; } function formatCredits(n) { return n.toLocaleString(); } function clamp(v, min, max) { return Math.max(min, Math.min(max, v)); } // ===== TOAST NOTIFICATION ===== function showToast(message, type = 'info') { const colors = { info: 'border-[#05d9e8] text-[#05d9e8]', success: 'border-green-400 text-green-400', warning: 'border-yellow-400 text-yellow-400', danger: 'border-red-400 text-red-400', error: 'border-[#ff2a6d] text-[#ff2a6d]' }; const existing = document.getElementById('toast-container'); if (!existing) { const container = document.createElement('div'); container.id = 'toast-container'; container.className = 'fixed top-20 right-4 z-[200] flex flex-col gap-2 max-w-sm'; document.body.appendChild(container); } const container = document.getElementById('toast-container'); const toast = document.createElement('div'); const colorClass = colors[type] || colors.info; toast.className = `border ${colorClass} bg-black bg-opacity-90 px-4 py-3 text-sm font-mono animate-slide-in pointer-events-auto cursor-pointer`; toast.style.animation = 'slideIn 0.3s ease, fadeOut 0.5s ease 3.5s forwards'; toast.textContent = message; toast.onclick = () => toast.remove(); container.appendChild(toast); setTimeout(() => { if (toast.parentNode) toast.remove(); }, 4000); } // Add animation styles const styleEl = document.createElement('style'); styleEl.textContent = ` @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } @keyframes modalIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } } .modal-animate { animation: modalIn 0.25s ease; } .tab-active { border-bottom: 2px solid #05d9e8; color: #05d9e8; } .tab-inactive { border-bottom: 2px solid transparent; color: #888; } .tab-inactive:hover { color: #aaa; } `; document.head.appendChild(styleEl); // ===== MODAL SYSTEM ===== function openModal(title, contentHTML) { const overlay = document.getElementById('modal-overlay'); const modalTitle = document.getElementById('modal-title'); const modalBody = document.getElementById('modal-body'); const modalContent = document.getElementById('modal-content'); overlay.classList.remove('hidden'); overlay.classList.add('flex'); modalTitle.textContent = title; modalBody.innerHTML = contentHTML; modalContent.classList.add('modal-animate'); setTimeout(() => modalContent.classList.remove('modal-animate'), 250); } function closeModal() { const overlay = document.getElementById('modal-overlay'); overlay.classList.add('hidden'); overlay.classList.remove('flex'); } // ===== CHARACTER SYSTEM ===== function openCharacterPanel() { const p = GS.player; const totalStats = Object.values(p.stats).reduce((a, b) => a + b, 0); const statRows = Object.entries(p.stats).map(([stat, val]) => { const maxVal = 30; const pct = Math.round((val / maxVal) * 100); const hasPoints = p.statPoints > 0; return `
${stat.toUpperCase()} ${val} / ${maxVal}
${hasPoints ? `` : ''}
`; }).join(''); const classPerks = { 'Smuggler': ['+20% evasion in encounters', 'Access to hidden trade routes', 'Reduced detection chance'], 'Fixer': ['+15% better prices', 'Unlock exclusive deals', 'Faction reputation gains doubled'], 'Enforcer': ['+30% combat damage', 'Intimidation dialogue options', 'Reduced combat injury'], 'ChemCook': ['+25% crafting success', 'Craft rare compounds', 'Immunity to drug side-effects'], 'Ghost Courier': ['Hack locked containers', 'Access Digital Sewers for free', 'Digital combat advantage'], 'Anarch Broker': ['+20% market manipulation', 'Cause market crashes for profit', 'Access anarchist quests'] }; const mutationSlots = GS.mutations.map(m => { const data = MUTATIONS_DB[m]; if (!data) return ''; return `
${data.name}
${data.description}
`; }).join(''); const content = `

${p.name}

Class: ${p.class}
Level: ${p.level} | XP: ${p.xp}/${p.xpToNext}
Credits: ${formatCredits(p.credits)}cr
HP: ${p.hp}/${p.maxHp}
${p.statPoints > 0 ? `
STAT POINTS: ${p.statPoints}
` : ''}
Day ${GS.day} | ${GS.time}:00h

STATISTICS

${statRows}

ACTIVE MUTATIONS (${GS.mutations.length}/6)

${mutationSlots || '
No mutations acquired yet.
'}

${p.class.toUpperCase()} PERKS

${(classPerks[p.class] || []).map(perk => `
${perk}
`).join('')}
`; openModal('CHARACTER SHEET', content); } function allocateStat(stat) { if (GS.player.statPoints <= 0) return; GS.player.stats[stat]++; GS.player.statPoints--; saveGame(); openCharacterPanel(); showToast(`${stat.toUpperCase()} increased to ${GS.player.stats[stat]}!`, 'success'); } function gainXP(amount) { GS.player.xp += amount; while (GS.player.xp >= GS.player.xpToNext) { GS.player.xp -= GS.player.xpToNext; GS.player.level++; GS.player.xpToNext = Math.floor(GS.player.xpToNext * 1.5); GS.player.statPoints += 2; GS.player.maxHp += 10; GS.player.hp = GS.player.maxHp; showToast(`LEVEL UP! You are now Level ${GS.player.level}! +2 stat points, +10 max HP`, 'success'); } saveGame(); } // ===== MARKET SYSTEM ===== function openMarket() { const district = DISTRICTS_DB[GS.currentDistrict]; const buyableItems = Object.keys(ITEMS_DB).filter(id => { const item = ITEMS_DB[id]; return item.basePrice > 0 && item.tradeable !== false; }); const sellableItems = GS.inventory.filter(inv => { return ITEMS_DB[inv.id] && ITEMS_DB[inv.id].basePrice > 0 && ITEMS_DB[inv.id].tradeable !== false; }); const content = `
LOCATION: ${district.name} | PRICE MOD: ${Math.round(district.priceModifier * 100)}% | CREDITS: ${formatCredits(GS.player.credits)}cr
${renderMarketBuy(buyableItems, district)}
`; openModal('MARKET', content); } function renderMarketBuy(items, district) { return `
${items.map(id => { const item = ITEMS_DB[id]; const market = GS.market[id]; const price = Math.round(market.currentPrice * district.priceModifier); const canAfford = GS.player.credits >= price; return `
${item.name}
${item.description}
${formatCredits(price)}cr ${market.trend > 0 ? '▲' : market.trend < 0 ? '▼' : '●'} ${item.category}
`; }).join('')}
`; } function renderMarketSell() { const sellable = GS.inventory.filter(inv => ITEMS_DB[inv.id] && ITEMS_DB[inv.id].basePrice > 0 && ITEMS_DB[inv.id].tradeable !== false); const district = DISTRICTS_DB[GS.currentDistrict]; if (sellable.length === 0) { return '
No items to sell.
'; } return `
${sellable.map(inv => { const item = ITEMS_DB[inv.id]; const market = GS.market[inv.id]; const sellPrice = Math.round(market.currentPrice * district.priceModifier * 0.7); return `
${item.name} x${inv.qty}
${item.description}
${formatCredits(sellPrice)}cr each
`; }).join('')}
`; } function renderMarketStocks() { return `
Invest in megacorp stocks. Prices fluctuate with market events and district conditions.
${Object.entries(GS.stocks).map(([id, stock]) => { const data = STOCKS_DB[id]; const prevPrice = stock.history.length > 1 ? stock.history[stock.history.length - 2] : stock.price; const change = stock.price - prevPrice; const changePct = prevPrice ? ((change / prevPrice) * 100).toFixed(1) : '0.0'; const isUp = change >= 0; return ` `; }).join('')}
SYMBOL NAME PRICE OWNED ACTIONS
${id} ${data.name} ${stock.price.toFixed(1)}cr ${isUp ? '▲' : '▼'}${changePct}% ${stock.shares}
Buy/Sell in lots of 10 shares. Prices update each game day.
`; } function renderMarketOptions() { return `
Speculate on price movements. Buy CALLS if you think prices will rise, PUTS if you think they'll fall.
${Object.keys(STOCKS_DB).map(id => { const data = STOCKS_DB[id]; const stock = GS.stocks[id]; return `
${id} - ${data.name} ${stock.price.toFixed(1)}cr
Options expire in 3 game days. Premium: ${Math.round(stock.price * 0.15)}cr per contract.
`; }).join('')}
`; } function marketTab(tab) { ['buy', 'sell', 'stocks', 'options'].forEach(t => { const el = document.getElementById('tab-' + t); if (el) { el.className = t === tab ? 'tab-active pb-2 px-3 text-sm font-bold cursor-pointer' : 'tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer'; } }); const contentEl = document.getElementById('market-content'); const district = DISTRICTS_DB[GS.currentDistrict]; if (tab === 'buy') { const items = Object.keys(ITEMS_DB).filter(id => ITEMS_DB[id].basePrice > 0 && ITEMS_DB[id].tradeable !== false); contentEl.innerHTML = renderMarketBuy(items, district); } else if (tab === 'sell') { contentEl.innerHTML = renderMarketSell(); } else if (tab === 'stocks') { contentEl.innerHTML = renderMarketStocks(); } else if (tab === 'options') { contentEl.innerHTML = renderMarketOptions(); } } function buyItem(itemId) { const district = DISTRICTS_DB[GS.currentDistrict]; const price = Math.round(GS.market[itemId].currentPrice * district.priceModifier); if (GS.player.credits < price) { showToast('Not enough credits!', 'error'); return; } GS.player.credits -= price; const existing = GS.inventory.find(i => i.id === itemId); if (existing) { existing.qty++; } else { GS.inventory.push({ id: itemId, qty: 1 }); } gainXP(5); showToast(`Bought ${ITEMS_DB[itemId].name} for ${formatCredits(price)}cr`, 'success'); saveGame(); refreshAllUI(); marketTab('buy'); } function sellItem(itemId, qty) { const district = DISTRICTS_DB[GS.currentDistrict]; const price = Math.round(GS.market[itemId].currentPrice * district.priceModifier * 0.7); const inv = GS.inventory.find(i => i.id === itemId); if (!inv || inv.qty <= 0) return; const sellQty = Math.min(qty, inv.qty); const total = price * sellQty; GS.player.credits += total; inv.qty -= sellQty; if (inv.qty <= 0) { GS.inventory = GS.inventory.filter(i => i.id !== itemId); } gainXP(3); showToast(`Sold ${sellQty}x ${ITEMS_DB[itemId].name} for ${formatCredits(total)}cr`, 'success'); saveGame(); refreshAllUI(); marketTab('sell'); } function buyStock(symbol) { const stock = GS.stocks[symbol]; const cost = Math.round(stock.price * 10); if (GS.player.credits < cost) { showToast('Not enough credits! Need ' + formatCredits(cost) + 'cr for 10 shares.', 'error'); return; } GS.player.credits -= cost; stock.shares += 10; showToast(`Bought 10 shares of ${symbol} for ${formatCredits(cost)}cr`, 'success'); saveGame(); refreshAllUI(); marketTab('stocks'); } function sellStock(symbol) { const stock = GS.stocks[symbol]; if (stock.shares < 10) { showToast('Need at least 10 shares to sell.', 'error'); return; } const revenue = Math.round(stock.price * 10); GS.player.credits += revenue; stock.shares -= 10; showToast(`Sold 10 shares of ${symbol} for ${formatCredits(revenue)}cr`, 'success'); saveGame(); refreshAllUI(); marketTab('stocks'); } function buyOption(symbol, type) { const stock = GS.stocks[symbol]; const premium = Math.round(stock.price * 1.5); if (GS.player.credits < premium) { showToast('Not enough credits! Need ' + formatCredits(premium) + 'cr premium.', 'error'); return; } GS.player.credits -= premium; showToast(`Bought ${type.toUpperCase()} option on ${symbol} for ${formatCredits(premium)}cr. Expires in 3 days.`, 'warning'); saveGame(); refreshAllUI(); } // ===== DISTRICT SYSTEM ===== function openDistricts() { const content = `
${Object.entries(DISTRICTS_DB).map(([id, d]) => { const isCurrent = id === GS.currentDistrict; const isUnlocked = GS.unlockedDistricts.includes(id); const borderColor = isCurrent ? '#05d9e8' : isUnlocked ? d.color : '#555'; return `

${d.name}

${isCurrent ? '◆ CURRENT LOCATION' : ''}

${d.description}

Threat: ${d.threatLevel} Price Mod: ${Math.round(d.priceModifier * 100)}%
${isUnlocked && !isCurrent ? `` : ''} ${!isUnlocked ? `` : ''}
`; }).join('')}
`; openModal('DISTRICTS', content); } function travelToDistrict(districtId) { if (GS.currentDistrict === districtId) return; GS.currentDistrict = districtId; GS.time += 2; if (GS.time >= 24) { advanceDay(); } showToast(`Traveled to ${DISTRICTS_DB[districtId].name}`, 'info'); saveGame(); refreshAllUI(); openDistricts(); } function unlockDistrict(districtId) { const district = DISTRICTS_DB[districtId]; if (GS.player.credits < district.unlockCost) { showToast(`Need ${formatCredits(district.unlockCost)}cr to unlock this district!`, 'error'); return; } GS.player.credits -= district.unlockCost; GS.unlockedDistricts.push(districtId); showToast(`Unlocked ${district.name}! You can now travel there.`, 'success'); saveGame(); refreshAllUI(); openDistricts(); } // ===== QUEST SYSTEM ===== function openQuestLog() { const content = `

ACTIVE QUESTS

${GS.quests.active.length === 0 ? '
No active quests. Check Available tab for new quests.
' : ''}
${GS.quests.active.map(q => { const quest = QUESTS_DB[q.id]; if (!quest) return ''; const pct = Math.round((q.progress / quest.steps) * 100); return `

${quest.name}

${quest.type.toUpperCase()}

${quest.description}

${q.progress}/${quest.steps} steps +${quest.rewards.credits}cr | +${quest.rewards.xp}XP
${q.progress >= quest.steps ? `` : ``}
`; }).join('')}

AVAILABLE QUESTS

${GS.quests.available.map(qId => { const quest = QUESTS_DB[qId]; if (!quest) return ''; return `

${quest.name}

${quest.description}

${quest.steps} steps | ${quest.type} +${quest.rewards.credits}cr | +${quest.rewards.xp}XP
`; }).join('')} ${GS.quests.available.length === 0 ? '
No new quests available right now.
' : ''}
${GS.quests.completed.length > 0 ? `

COMPLETED QUESTS

${GS.quests.completed.map(qId => { const quest = QUESTS_DB[qId]; if (!quest) return ''; return `
${quest.name}
`; }).join('')}
` : ''}
`; openModal('QUEST LOG', content); } function acceptQuest(questId) { const idx = GS.quests.available.indexOf(questId); if (idx === -1) return; GS.quests.available.splice(idx, 1); GS.quests.active.push({ id: questId, progress: 0 }); showToast(`Accepted quest: ${QUESTS_DB[questId].name}`, 'success'); saveGame(); openQuestLog(); } function advanceQuest(questId) { const quest = GS.quests.active.find(q => q.id === questId); if (!quest) return; quest.progress++; if (quest.progress >= QUESTS_DB[questId].steps) { showToast(`${QUESTS_DB[questId].name} is ready to complete!`, 'warning'); } else { showToast(`${QUESTS_DB[questId].name}: Step ${quest.progress}/${QUESTS_DB[questId].steps}`, 'info'); } saveGame(); openQuestLog(); } function completeQuest(questId) { const idx = GS.quests.active.findIndex(q => q.id === questId); if (idx === -1) return; GS.quests.active.splice(idx, 1); GS.quests.completed.push(questId); const quest = QUESTS_DB[questId]; GS.player.credits += quest.rewards.credits; gainXP(quest.rewards.xp); if (quest.rewards.faction) { Object.entries(quest.rewards.faction).forEach(([fId, amt]) => { changeReputation(fId, amt); }); } if (quest.rewards.item) { const existing = GS.inventory.find(i => i.id === quest.rewards.item); if (existing) existing.qty++; else GS.inventory.push({ id: quest.rewards.item, qty: 1 }); } if (quest.rewards.mutation) { if (!GS.mutations.includes(quest.rewards.mutation)) { GS.mutations.push(quest.rewards.mutation); showToast(`NEW MUTATION: ${MUTATIONS_DB[quest.rewards.mutation].name}!`, 'success'); } } showToast(`Quest completed: ${quest.name}! +${quest.rewards.credits}cr, +${quest.rewards.xp}XP`, 'success'); saveGame(); refreshAllUI(); openQuestLog(); } function changeReputation(factionId, amount) { if (!GS.factions[factionId]) return; GS.factions[factionId].reputation += amount; const rep = GS.factions[factionId].reputation; if (rep >= 50) GS.factions[factionId].status = 'Allied'; else if (rep >= 25) GS.factions[factionId].status = 'Friendly'; else if (rep > -25) GS.factions[factionId].status = 'Neutral'; else if (rep >= -50) GS.factions[factionId].status = 'Wary'; else GS.factions[factionId].status = 'Hostile'; } // ===== INVENTORY SYSTEM ===== function openInventory() { const content = `
Items: ${GS.inventory.reduce((a, i) => a + i.qty, 0)} | Credits: ${formatCredits(GS.player.credits)}cr
${GS.inventory.map(inv => { const item = ITEMS_DB[inv.id]; if (!item) return ''; const canUse = ['medical', 'drug', 'mutation-serum'].includes(item.category); return `
${item.name} x${inv.qty}
${item.category.toUpperCase()}
${item.description}
Value: ~${formatCredits(Math.round(GS.market[inv.id]?.currentPrice * 0.7 || 0))}cr
${canUse ? `` : ''} ${item.basePrice > 0 && item.tradeable !== false ? `` : ''}
`; }).join('')}
`; openModal('INVENTORY', content); } function useItem(itemId) { const inv = GS.inventory.find(i => i.id === itemId); if (!inv) return; const item = ITEMS_DB[itemId]; if (item.category === 'medical') { if (itemId === 'stim-pack') { GS.player.hp = Math.min(GS.player.maxHp, GS.player.hp + 30); showToast('Used Stim Pack. +30 HP!', 'success'); } else if (itemId === 'adrenal-shot') { Object.keys(GS.player.stats).forEach(s => GS.player.stats[s] += 3); showToast('Used Adrenal Shot! All stats +3 for this encounter!', 'success'); } } else if (item.category === 'drug') { if (itemId === 'synth-coke') { GS.player.stats.agility += 2; GS.player.stats.endurance -= 1; showToast('Used Synth-Coke. Agility +2, Endurance -1.', 'warning'); } } else if (item.category === 'mutation-serum') { const mKeys = Object.keys(MUTATIONS_DB).filter(m => !GS.mutations.includes(m)); if (mKeys.length > 0) { const newMut = pick(mKeys); GS.mutations.push(newMut); showToast(`Acquired mutation: ${MUTATIONS_DB[newMut].name}!`, 'warning'); } } inv.qty--; if (inv.qty <= 0) { GS.inventory = GS.inventory.filter(i => i.id !== itemId); } gainXP(2); saveGame(); refreshAllUI(); openInventory(); } function dropItem(itemId) { if (!confirm('Are you sure you want to drop this item?')) return; GS.inventory = GS.inventory.filter(i => i.id !== itemId); showToast('Item dropped.', 'info'); saveGame(); refreshAllUI(); openInventory(); } // ===== FACTION / CONTACTS SYSTEM ===== function openFactions() { const statusColors = { 'Allied': '#22c55e', 'Friendly': '#4ade80', 'Neutral': '#ffffff', 'Wary': '#facc15', 'Hostile': '#ef4444', 'Indebted': '#ffd700' }; // Add Mr. Bleak special const allFactions = { ...GS.factions }; const content = `
${Object.entries(allFactions).map(([fId, faction]) => { const data = FACTIONS_DB[fId]; if (!data) return ''; const color = statusColors[faction.status] || '#ffffff'; const repPct = clamp(((faction.reputation + 100) / 200) * 100, 0, 100); return `
${data.abbr}

${data.name}

${faction.status.toUpperCase()}

${data.description}

${data.bonus}

Reputation: ${faction.reputation} ${faction.status}
`; }).join('')}
MB

MR. BLEAK

INDEBTED

Albino loan shark king. Defaulting triggers world events and hunter mini-boss fights.

${GS.loans.length > 0 ? GS.loans.map((loan, i) => `
Loan: ${formatCredits(loan.amount)}cr | ${Math.round(loan.interest*100)}% interest | ${loan.daysLeft} days left
Owed: ${formatCredits(Math.round(loan.amount * (1 + loan.interest * (7 - loan.daysLeft) / 7)))}cr
`).join('') : ''}
`; openModal('CONTACTS & FACTIONS', content); } function takeNewLoan() { const amounts = [500, 1000, 2000, 5000]; const content = `
Mr. Bleak offers loans at 12% interest. Repay within 7 days or face the consequences.
${amounts.map(amt => ` `).join('')}
`; openModal('MR. BLEAK LOANS', content); } function confirmLoan(amount) { GS.loans.push({ lender: 'Mr. Bleak', amount, interest: 0.12, daysLeft: 7, dailyInterest: Math.round(amount * 0.12 / 7) }); GS.player.credits += amount; showToast(`Borrowed ${formatCredits(amount)}cr from Mr. Bleak. Repay within 7 days!`, 'warning'); saveGame(); refreshAllUI(); openFactions(); } function repayLoan(index) { const loan = GS.loans[index]; if (!loan) return; const owed = Math.round(loan.amount * (1 + loan.interest)); if (GS.player.credits < owed) { showToast(`You need ${formatCredits(owed)}cr to repay this loan!`, 'error'); return; } GS.player.credits -= owed; GS.loans.splice(index, 1); showToast(`Loan repaid! ${formatCredits(owed)}cr deducted.`, 'success'); changeReputation('dust-collective', 5); saveGame(); refreshAllUI(); openFactions(); } // ===== MUTATION SYSTEM ===== function openMutations() { const activeMutations = GS.mutations.map(m => MUTATIONS_DB[m]).filter(Boolean); const availableMutations = Object.entries(MUTATIONS_DB).filter(([id]) => !GS.mutations.includes(id)); const content = `

ACTIVE MUTATIONS (${GS.mutations.length}/6)

${activeMutations.map(m => `
${m.name}
${m.description}
${Object.entries(m.statBonus || {}).map(([s, v]) => `+${v} ${s}`).join(' ')} ${Object.entries(m.statPenalty || {}).map(([s, v]) => `${v} ${s}`).join(' ')}
`).join('')} ${GS.mutations.length === 0 ? '
No mutations active.
' : ''}

AVAILABLE MUTATIONS

Acquire mutations through quests, exposure to relics, or mutation serums.
${availableMutations.map(([id, m]) => `
${m.name}
Risk: ${m.risk.toUpperCase()}
${GS.mutations.length < 6 ? `` : 'MAX MUTATIONS'}
`).join('')}
WARNING: Mutations have both benefits and side effects. High-risk mutations may cause permanent stat penalties. Max 6 mutations.
`; openModal('MUTATIONS', content); } function attemptMutation(mutationId) { if (GS.mutations.length >= 6) { showToast('Maximum mutations reached (6/6)!', 'error'); return; } if (GS.mutations.includes(mutationId)) return; const mut = MUTATIONS_DB[mutationId]; const riskChance = mut.risk === 'high' ? 0.5 : mut.risk === 'medium' ? 0.25 : mut.risk === 'low' ? 0.1 : 0; if (Math.random() < riskChance) { // Bad outcome const statKeys = Object.keys(GS.player.stats); const randomStat = pick(statKeys); GS.player.stats[randomStat] = Math.max(1, GS.player.stats[randomStat] - 2); showToast(`Mutation attempt FAILED! -2 ${randomStat.toUpperCase()} due to side effects.`, 'error'); } GS.mutations.push(mutationId); // Apply stat bonuses if (mut.statBonus) { Object.entries(mut.statBonus).forEach(([s, v]) => { if (GS.player.stats[s] !== undefined) GS.player.stats[s] += v; }); } if (mut.statPenalty) { Object.entries(mut.statPenalty).forEach(([s, v]) => { if (GS.player.stats[s] !== undefined) GS.player.stats[s] += v; }); } showToast(`Acquired mutation: ${mut.name}!`, 'success'); gainXP(25); saveGame(); refreshAllUI(); openMutations(); } // ===== CRAFTING SYSTEM ===== function openCrafting() { const content = `
Combine components to craft valuable items. Required materials are deducted from your inventory.
${Object.entries(RECIPES_DB).map(([id, recipe]) => { const output = ITEMS_DB[id]; const canCraft = Object.entries(recipe.ingredients).every(([ingId, qty]) => { const inv = GS.inventory.find(i => i.id === ingId); return inv && inv.qty >= qty; }); const ingredientList = Object.entries(recipe.ingredients).map(([ingId, qty]) => { const inv = GS.inventory.find(i => i.id === ingId); const have = inv ? inv.qty : 0; const enough = have >= qty; return `${ITEMS_DB[ingId]?.name || ingId}: ${have}/${qty}`; }).join(', '); return `
${recipe.name} (x${recipe.output})
${output.description}
Materials: ${ingredientList}
+${recipe.xp} XP
`; }).join('')}
`; openModal('CRAFTING', content); } function craftItem(recipeId) { const recipe = RECIPES_DB[recipeId]; if (!recipe) return; // Check ingredients const canCraft = Object.entries(recipe.ingredients).every(([ingId, qty]) => { const inv = GS.inventory.find(i => i.id === ingId); return inv && inv.qty >= qty; }); if (!canCraft) { showToast('Missing required materials!', 'error'); return; } // Deduct ingredients Object.entries(recipe.ingredients).forEach(([ingId, qty]) => { const inv = GS.inventory.find(i => i.id === ingId); inv.qty -= qty; if (inv.qty <= 0) { GS.inventory = GS.inventory.filter(i => i.id !== ingId); } }); // Add output const existing = GS.inventory.find(i => i.id === recipeId); if (existing) { existing.qty += recipe.output; } else { GS.inventory.push({ id: recipeId, qty: recipe.output }); } gainXP(recipe.xp); showToast(`Crafted ${recipe.output}x ${recipe.name}! +${recipe.xp} XP`, 'success'); saveGame(); refreshAllUI(); openCrafting(); } // ===== SAFEHOUSE SYSTEM ===== function openSafehouse() { const owned = GS.safehouses[GS.currentDistrict]; const allSafehouses = Object.entries(DISTRICTS_DB).filter(([id]) => GS.unlockedDistricts.includes(id)); const content = `

CURRENT SAFEHOUSE: ${DISTRICTS_DB[GS.currentDistrict].name}

${owned ? `
Level ${owned.level} ${owned.bonus}
Storage: +${owned.level * 5} slots
Income: +${50 * owned.level}cr/day
Defense: ${owned.level * 10}%
Craft Bonus: +${owned.level * 5}%
` : `
No safehouse in this district.
`}

OTHER DISTRICT SAFEHOUSES

${allSafehouses.filter(([id]) => id !== GS.currentDistrict).map(([id, d]) => { const sh = GS.safehouses[id]; return `
${d.name} ${sh ? `Level ${sh.level}` : 'No safehouse'}
${!sh ? `` : ``}
`; }).join('')}
Safehouses provide passive income, extra storage, crafting bonuses, and defense against raids. Upgrade to increase bonuses.
`; openModal('SAFEHOUSE', content); } function buySafehouse(districtId) { const cost = 2000; if (GS.player.credits < cost) { showToast(`Need ${formatCredits(cost)}cr to buy a safehouse!`, 'error'); return; } GS.player.credits -= cost; GS.safehouses[districtId] = { owned: true, level: 1, bonus: 'Passive income: +50cr/day' }; showToast(`Purchased safehouse in ${DISTRICTS_DB[districtId].name}!`, 'success'); saveGame(); refreshAllUI(); openSafehouse(); } function upgradeSafehouse(districtId) { const sh = GS.safehouses[districtId]; if (!sh) return; const cost = 500 * sh.level; if (GS.player.credits < cost) { showToast(`Need ${formatCredits(cost)}cr to upgrade!`, 'error'); return; } GS.player.credits -= cost; sh.level++; sh.bonus = `Passive income: +${50 * sh.level}cr/day`; showToast(`Safehouse upgraded to Level ${sh.level}!`, 'success'); saveGame(); refreshAllUI(); openSafehouse(); } // ===== COMBAT / DISTRICT TAKEOVER ===== function openTakeover() { const district = DISTRICTS_DB[GS.currentDistrict]; const content = `

DISTRICT TAKEOVER

Attempt to seize control of ${district.name}

Threat Level: ${district.threatLevel}

Launch a takeover attempt to gain control of this district. Success grants passive income, reduced prices, and faction reputation. Failure costs HP and credits.

YOUR COMBAT STATS

🤜 Attack: ${GS.player.stats.strength + GS.player.stats.agility}
🛡 Defense: ${GS.player.stats.endurance + GS.player.stats.strength}
🎲 Luck: ${GS.player.stats.luck}
❤ HP: ${GS.player.hp}/${GS.player.maxHp}
⚡ Agility: ${GS.player.stats.agility}
🎯 Charisma: ${GS.player.stats.charisma}

SELECT APPROACH

`; openModal('DISTRICT TAKEOVER', content); } function startCombat(approach) { const district = DISTRICTS_DB[GS.currentDistrict]; let stat, successRate; if (approach === 'force') { stat = GS.player.stats.strength + GS.player.stats.endurance; successRate = 0.3 + stat / 100; } else if (approach === 'stealth') { stat = GS.player.stats.agility + GS.player.stats.luck; successRate = 0.4 + stat / 100; } else { stat = GS.player.stats.charisma + GS.player.stats.intelligence; successRate = 0.35 + stat / 100; } const luckBonus = GS.player.stats.luck / 200; successRate = Math.min(0.85, successRate + luckBonus); const success = Math.random() < successRate; const content = `
${success ? '⚔️' : '💀'}

${success ? 'TAKEOVER SUCCESSFUL!' : 'TAKEOVER FAILED!'}

Approach: ${approach.toUpperCase()} | Success Rate: ${Math.round(successRate * 100)}%
${success ? `
District Influence: ${district.name}
Credits Earned: +${random(200, 800)}cr
XP Earned: +150
Faction Bonus: Varies by allegiance
` : `
HP Lost: -${random(10, 30)}
Credits Lost: -${random(50, 200)}cr
Better prepare before your next attempt.
`}
`; if (success) { const creditsEarned = random(200, 800); GS.player.credits += creditsEarned; gainXP(150); } else { GS.player.hp = Math.max(1, GS.player.hp - random(10, 30)); GS.player.credits = Math.max(0, GS.player.credits - random(50, 200)); } saveGame(); refreshAllUI(); openModal('COMBAT RESULT', content); } // ===== AUCTION SYSTEM ===== function bidOnAuction(itemId) { const item = ITEMS_DB[itemId]; const currentBid = Math.round(GS.market[itemId]?.currentPrice || item.basePrice); const minBid = Math.round(currentBid * 1.05); const content = `

${item.name}

${item.description}

Category: ${item.category.toUpperCase()}

Current Bid: ${formatCredits(currentBid)}cr
Minimum Bid: ${formatCredits(minBid)}cr
Your Credits: ${formatCredits(GS.player.credits)}cr
Winning bids are final. Failed bids are refunded minus a 5% fee.
`; openModal('AUCTION: ' + item.name.toUpperCase(), content); } function submitBid(itemId) { const input = document.getElementById('auction-bid-input'); const bidAmount = parseInt(input.value); const currentPrice = Math.round(GS.market[itemId]?.currentPrice || ITEMS_DB[itemId].basePrice); const minBid = Math.round(currentPrice * 1.05); if (isNaN(bidAmount) || bidAmount < minBid) { showToast(`Minimum bid is ${formatCredits(minBid)}cr!`, 'error'); return; } if (bidAmount > GS.player.credits) { showToast('Not enough credits!', 'error'); return; } // 70% chance to win const won = Math.random() < 0.7; if (won) { GS.player.credits -= bidAmount; const existing = GS.inventory.find(i => i.id === itemId); if (existing) existing.qty++; else GS.inventory.push({ id: itemId, qty: 1 }); gainXP(50); showToast(`Won auction for ${ITEMS_DB[itemId].name}! Paid ${formatCredits(bidAmount)}cr`, 'success'); } else { const fee = Math.round(bidAmount * 0.05); GS.player.credits -= fee; showToast(`Lost the auction for ${ITEMS_DB[itemId].name}. Fee: ${formatCredits(fee)}cr`, 'warning'); } saveGame(); refreshAllUI(); closeModal(); } // ===== DIALOGUE SYSTEM ===== function sendAuctionMessage() { const input = document.getElementById('auction-chat-input'); if (!input) return; const message = input.value.trim(); if (!message) return; input.value = ''; const chatArea = document.getElementById('auction-chat'); if (!chatArea) return; // Player message chatArea.innerHTML += `

VEIL: "${message}"

`; // NPC response const responses = [ 'MADAME KARNA: "An interesting offer... but I\'ve seen more convincing bids from street rats."', 'MADAME KARNA: "Ah, you have spirit. But spirit doesn\'t pay the bills, does it?"', 'MADAME KARNA: "The Clownfather himself whispered about this item. Are you sure you can afford such attention?"', 'MADAME KARNA: "Interesting... The Digital Saints would pay triple for that information alone."', 'MADAME KARNA: "Mr. Bleak\'s collectors are circling this auction like vultures. Bid wisely."', 'MADAME KARNA: "I admire the ambition, darling. But ambition has a habit of getting people killed in this city."' ]; setTimeout(() => { chatArea.innerHTML += `

${pick(responses)}

`; chatArea.scrollTop = chatArea.scrollHeight; }, 500); chatArea.scrollTop = chatArea.scrollHeight; } // ===== MARKET PRICE UPDATES ===== function updateMarketPrices() { Object.keys(GS.market).forEach(id => { const item = ITEMS_DB[id]; if (!item || item.basePrice === 0) return; const market = GS.market[id]; // Random walk market.trend = market.trend * 0.95 + (Math.random() - 0.5) * 0.1; const change = 1 + market.trend + (Math.random() - 0.5) * 0.05 * (item.volatile ? 3 : 1); market.currentPrice = Math.max(Math.round(item.basePrice * 0.5), Math.round(market.currentPrice * change)); // Supply/demand shifts market.supply = clamp(market.supply + random(-2, 2), 1, 50); market.demand = clamp(market.demand + random(-2, 3), 1, 50); }); } function updateStockPrices() { Object.keys(GS.stocks).forEach(id => { const stock = GS.stocks[id]; const data = STOCKS_DB[id]; const change = (Math.random() - 0.48) * data.volatility; stock.price = Math.max(5, stock.price * (1 + change)); stock.history.push(stock.price); if (stock.history.length > 30) stock.history.shift(); }); } // ===== RANDOM EVENTS ===== function triggerRandomEvent() { const event = pick(EVENTS_POOL); const district = DISTRICTS_DB[GS.currentDistrict]; // Apply market effects if (event.effect) { Object.entries(event.effect).forEach(([category, modifier]) => { Object.keys(ITEMS_DB).forEach(id => { if (ITEMS_DB[id].category === category && GS.market[id]) { GS.market[id].currentPrice = Math.round(GS.market[id].currentPrice * modifier); GS.market[id].trend = (modifier - 1) * 0.5; } }); }); } // Show event in ticker const tickerTexts = document.querySelectorAll('.market-ticker span'); if (tickerTexts.length > 0) { const typeColors = { danger: '#ff2a6d', warning: '#ffd700', info: '#05d9e8', opportunity: '#22c55e' }; const color = typeColors[event.type] || '#ffffff'; const newSpan = document.createElement('span'); newSpan.className = 'mx-4'; newSpan.style.color = color; newSpan.textContent = event.text; const ticker = document.querySelector('.market-ticker'); if (ticker) { ticker.prepend(newSpan); } } showToast(event.text, event.type === 'danger' ? 'error' : event.type === 'opportunity' ? 'success' : 'info'); } // ===== TIME SYSTEM ===== function advanceDay() { GS.day++; GS.time = 8; updateMarketPrices(); updateStockPrices(); // Loan interest GS.loans.forEach(loan => { loan.daysLeft--; if (loan.daysLeft <= 0) { showToast(`⚠️ LOAN FROM ${loan.lender} OVERDUE! Hunters dispatched!`, 'error'); loan.daysLeft = 0; // Spawn debt collectors as events changeReputation('dust-collective', -5); } }); // Safehouse income Object.values(GS.safehouses).forEach(sh => { if (sh && sh.owned) { const income = 50 * sh.level; GS.player.credits += income; showToast(`Safehouse income: +${income}cr`, 'success'); } }); // Random event (30% chance) if (Math.random() < 0.3) { triggerRandomEvent(); } saveGame(); refreshAllUI(); } // ===== REFRESH UI ===== function refreshAllUI() { // Player profile const profileEl = document.getElementById('player-profile'); if (profileEl) { const levelXpPct = Math.round((GS.player.xp / GS.player.xpToNext) * 100); profileEl.innerHTML = `

PLAYER PROFILE

LEVEL ${GS.player.level}
${GS.player.class.toUpperCase()}

ALIAS: "${GS.player.name}"

CREDITS: ${formatCredits(GS.player.credits)}

HP: ${GS.player.hp}/${GS.player.maxHp}

XP: ${GS.player.xp}/${GS.player.xpToNext} ${levelXpPct}%
${GS.player.statPoints > 0 ? `
⬆ ${GS.player.statPoints} STAT POINTS AVAILABLE!
` : ''}`; } // Stats const statsEl = document.getElementById('player-stats'); if (statsEl) { const statNames = { charisma: 'CHARISMA', agility: 'AGILITY', intelligence: 'INTELLIGENCE', strength: 'STRENGTH', endurance: 'ENDURANCE', luck: 'LUCK' }; statsEl.innerHTML = Object.entries(GS.player.stats).map(([stat, val]) => `
${statNames[stat] || stat.toUpperCase()} ${val}
` ).join(''); } // Mutations count const mutCount = document.getElementById('mutation-count'); if (mutCount) mutCount.textContent = GS.mutations.length; // Credits in footer const creditsFooter = document.getElementById('footer-credits'); if (creditsFooter) creditsFooter.textContent = formatCredits(GS.player.credits); // Location in footer const locFooter = document.getElementById('footer-location'); if (locFooter) locFooter.textContent = DISTRICTS_DB[GS.currentDistrict]?.name || 'Unknown'; // Day in footer const dayFooter = document.getElementById('footer-day'); if (dayFooter) dayFooter.textContent = `Day ${GS.day}`; saveGame(); } // ===== INITIALIZATION ===== function init() { loadGame(); // Wire up buttons const buttonMap = { 'btn-character': () => openCharacterPanel(), 'btn-market': () => openMarket(), 'btn-districts': () => openDistricts(), 'btn-mutations': () => openMutations(), 'btn-quests': () => openQuestLog(), 'btn-inventory': () => openInventory(), 'btn-factions': () => openFactions(), 'btn-buy': () => { openMarket(); setTimeout(() => marketTab('buy'), 50); }, 'btn-sell': () => { openMarket(); setTimeout(() => marketTab('sell'), 50); }, 'btn-craft': () => openCrafting(), 'btn-safehouse': () => openSafehouse(), 'btn-takeover': () => openTakeover() }; Object.entries(buttonMap).forEach(([id, handler]) => { const el = document.getElementById(id); if (el) el.addEventListener('click', handler); }); // Wire up auction bid buttons document.querySelectorAll('[data-auction-bid]').forEach(btn => { btn.addEventListener('click', () => bidOnAuction(btn.dataset.auctionBid)); }); // Wire district markers document.querySelectorAll('[data-travel-district]').forEach(el => { el.addEventListener('click', () => travelToDistrict(el.dataset.travelDistrict)); }); // Refresh UI refreshAllUI(); // Game loop - update every 60 seconds setInterval(() => { updateMarketPrices(); updateStockPrices(); if (Math.random() < 0.2) triggerRandomEvent(); }, 60000); // Auto-save every 30 seconds setInterval(saveGame, 30000); } document.addEventListener('DOMContentLoaded', init); // Close modal on overlay click document.addEventListener('click', (e) => { if (e.target.id === 'modal-overlay') closeModal(); }); // Keyboard support document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal(); if (e.key === 'Enter') { const auctionInput = document.getElementById('auction-chat-input'); if (document.activeElement === auctionInput) { sendAuctionMessage(); } } });