Spaces:
Running
Running
🐳 05/05 - 23:21 - Review this code and start connecting and building the back end for each button and section.
1129bce verified Download script.js from Euphoricdoom/cybertraderrpg: direct link, hf CLI and curl.
- Browser
- Download file 83.8 kB
-
https://huggingface.co/spaces/Euphoricdoom/cybertraderrpg/resolve/main/script.js
- Command line
-
hf download hf://spaces/Euphoricdoom/cybertraderrpg/script.js
-
curl -L -o script.js https://huggingface.co/spaces/Euphoricdoom/cybertraderrpg/resolve/main/script.js
83.8 kB
// ============================================
// 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 `
<div class="mb-2">
<div class="flex justify-between text-xs mb-1">
<span class="neon-pink">${stat.toUpperCase()}</span>
<span>${val} <span class="text-gray-500">/ ${maxVal}</span></span>
</div>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: ${pct}%"></div>
</div>
${hasPoints ? `<button onclick="allocateStat('${stat}')" class="mt-1 text-xs bg-black border border-[#05d9e8] text-[#05d9e8] px-2 py-0.5 hover:bg-[#05d9e8] hover:text-black transition-colors">+ ADD POINT</button>` : ''}
</div>`;
}).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 `
<div class="border border-[#d300c5] bg-gray-900 p-2 flex items-center gap-3">
<div class="${data.color} text-2xl"><i class="fas ${data.icon}"></i></div>
<div>
<div class="text-sm font-bold neon-purple">${data.name}</div>
<div class="text-xs text-gray-400">${data.description}</div>
</div>
</div>`;
}).join('');
const content = `
<div class="space-y-6">
<!-- Character Header -->
<div class="flex items-center gap-4 flex-wrap">
<div class="w-24 h-24 bg-gray-800 border-2 border-[#ff2a6d] flex items-center justify-center">
<i class="fas fa-skull text-4xl text-[#ff2a6d]"></i>
</div>
<div>
<h3 class="title-font text-2xl neon-pink">${p.name}</h3>
<div class="text-gray-400 text-sm">Class: <span class="text-white">${p.class}</span></div>
<div class="text-gray-400 text-sm">Level: <span class="neon-cyan">${p.level}</span> | XP: <span class="text-white">${p.xp}/${p.xpToNext}</span></div>
<div class="text-gray-400 text-sm">Credits: <span class="text-yellow-400">${formatCredits(p.credits)}cr</span></div>
<div class="text-gray-400 text-sm">HP: <span class="text-green-400">${p.hp}/${p.maxHp}</span>
<div class="inline-block w-32 ml-2 progress-bar"><div class="progress-bar-fill" style="width:${(p.hp/p.maxHp)*}%; background: linear-gradient(90deg, #22c55e, #16a34a)"></div></div>
</div>
</div>
<div class="ml-auto text-right">
${p.statPoints > 0 ? `<div class="text-yellow-400 text-sm font-bold pixel-font">STAT POINTS: ${p.statPoints}</div>` : ''}
<div class="text-gray-500 text-xs">Day ${GS.day} | ${GS.time}:00h</div>
</div>
</div>
<!-- Stats -->
<div>
<h3 class="neon-cyan text-lg font-bold mb-3 flex items-center"><i class="fas fa-chart-bar mr-2"></i> STATISTICS</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
${statRows}
</div>
</div>
<!-- Mutations -->
<div>
<h3 class="neon-purple text-lg font-bold mb-3 flex items-center"><i class="fas fa-dna mr-2"></i> ACTIVE MUTATIONS (${GS.mutations.length}/6)</h3>
<div class="space-y-2">
${mutationSlots || '<div class="text-gray-500 text-sm">No mutations acquired yet.</div>'}
</div>
</div>
<!-- Class Perks -->
<div>
<h3 class="neon-cyan text-lg font-bold mb-3 flex items-center"><i class="fas fa-star mr-2"></i> ${p.class.toUpperCase()} PERKS</h3>
<div class="space-y-1">
${(classPerks[p.class] || []).map(perk => `<div class="text-sm text-gray-300"><i class="fas fa-check text-green-400 mr-2"></i>${perk}</div>`).join('')}
</div>
</div>
<div class="flex gap-3 flex-wrap">
<button onclick="openMutations()" class="neon-btn bg-black text-[#d300c5] border border-[#d300c5] px-4 py-2 text-sm">MANAGE MUTATIONS</button>
<button onclick="openInventory()" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-4 py-2 text-sm">VIEW INVENTORY</button>
<button onclick="resetGame()" class="neon-btn bg-black text-red-400 border border-red-400 px-4 py-2 text-sm">RESET GAME</button>
</div>
</div>`;
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 = `
<div>
<!-- Market Tabs -->
<div class="flex gap-4 mb-4 border-b border-gray-700">
<button onclick="marketTab('buy')" id="tab-buy" class="tab-active pb-2 px-3 text-sm font-bold cursor-pointer">BLACK MARKET</button>
<button onclick="marketTab('sell')" id="tab-sell" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">SELL ITEMS</button>
<button onclick="marketTab('stocks')" id="tab-stocks" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">STOCK EXCHANGE</button>
<button onclick="marketTab('options')" id="tab-options" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">OPTIONS</button>
</div>
<div class="mb-3 text-xs text-gray-400">
<span class="neon-cyan">LOCATION:</span> ${district.name} |
<span class="neon-pink">PRICE MOD:</span> ${Math.round(district.priceModifier * 100)}% |
<span class="text-yellow-400">CREDITS:</span> ${formatCredits(GS.player.credits)}cr
</div>
<div id="market-content">
${renderMarketBuy(buyableItems, district)}
</div>
</div>`;
openModal('MARKET', content);
}
function renderMarketBuy(items, district) {
return `
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[50vh] overflow-y-auto">
${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 `
<div class="border border-gray-700 bg-gray-900 p-3 flex gap-3 hover:border-[#05d9e8] transition-colors">
<div class="${item.color} text-3xl self-center"><i class="fas ${item.icon}"></i></div>
<div class="flex-1">
<div class="text-sm font-bold neon-cyan">${item.name}</div>
<div class="text-xs text-gray-400">${item.description}</div>
<div class="flex justify-between items-center mt-1">
<div>
<span class="text-yellow-400 text-sm">${formatCredits(price)}cr</span>
<span class="text-xs ${market.trend > 0 ? 'text-green-400' : market.trend < 0 ? 'text-red-400' : 'text-gray-500'} ml-2">
${market.trend > 0 ? '▲' : market.trend < 0 ? '▼' : '●'} ${item.category}
</span>
</div>
<button onclick="buyItem('${id}')" class="neon-btn bg-black ${canAfford ? 'text-[#ff2a6d] border-[#ff2a6d]' : 'text-gray-600 border-gray-600 cursor-not-allowed'} border px-3 py-1 text-xs" ${canAfford ? '' : 'disabled'}>BUY</button>
</div>
</div>
</div>`;
}).join('')}
</div>`;
}
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 '<div class="text-center text-gray-500 py-8">No items to sell.</div>';
}
return `
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[50vh] overflow-y-auto">
${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 `
<div class="border border-gray-700 bg-gray-900 p-3 flex gap-3 hover:border-[#ff2a6d] transition-colors">
<div class="${item.color} text-3xl self-center"><i class="fas ${item.icon}"></i></div>
<div class="flex-1">
<div class="text-sm font-bold neon-pink">${item.name} <span class="text-gray-400">x${inv.qty}</span></div>
<div class="text-xs text-gray-400">${item.description}</div>
<div class="flex justify-between items-center mt-1">
<span class="text-yellow-400 text-sm">${formatCredits(sellPrice)}cr each</span>
<div class="flex gap-1">
<button onclick="sellItem('${inv.id}', 1)" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-2 py-1 text-xs">SELL 1</button>
<button onclick="sellItem('${inv.id}', ${inv.qty})" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-2 py-1 text-xs">SELL ALL</button>
</div>
</div>
</div>
</div>`;
}).join('')}
</div>`;
}
function renderMarketStocks() {
return `
<div class="max-h-[50vh] overflow-y-auto">
<div class="mb-3 text-xs text-gray-400">Invest in megacorp stocks. Prices fluctuate with market events and district conditions.</div>
<table class="w-full text-sm">
<thead>
<tr class="border-b border-gray-700">
<th class="text-left neon-cyan py-2">SYMBOL</th>
<th class="text-left neon-cyan py-2">NAME</th>
<th class="text-right neon-cyan py-2">PRICE</th>
<th class="text-right neon-cyan py-2">OWNED</th>
<th class="text-center neon-cyan py-2">ACTIONS</th>
</tr>
</thead>
<tbody>
${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 `
<tr class="border-b border-gray-800 hover:bg-gray-900">
<td class="py-2 font-bold ${isUp ? 'text-green-400' : 'text-red-400'}">${id}</td>
<td class="py-2 text-gray-300">${data.name}</td>
<td class="py-2 text-right text-white">${stock.price.toFixed(1)}cr <span class="text-xs ${isUp ? 'text-green-400' : 'text-red-400'}">${isUp ? '▲' : '▼'}${changePct}%</span></td>
<td class="py-2 text-right text-yellow-400">${stock.shares}</td>
<td class="py-2 text-center">
<button onclick="buyStock('${id}')" class="bg-black text-green-400 border border-green-400 px-2 py-0.5 text-xs mr-1 hover:bg-green-900">BUY</button>
<button onclick="sellStock('${id}')" class="bg-black text-red-400 border border-red-400 px-2 py-0.5 text-xs hover:bg-red-900" ${stock.shares > 0 ? '' : 'disabled style="opacity:0.3;cursor:not-allowed"'}>SELL</button>
</td>
</tr>`;
}).join('')}
</tbody>
</table>
<div class="mt-3 text-xs text-gray-500">Buy/Sell in lots of 10 shares. Prices update each game day.</div>
</div>`;
}
function renderMarketOptions() {
return `
<div class="max-h-[50vh] overflow-y-auto">
<div class="mb-4 text-xs text-gray-400">Speculate on price movements. Buy CALLS if you think prices will rise, PUTS if you think they'll fall.</div>
<div class="space-y-3">
${Object.keys(STOCKS_DB).map(id => {
const data = STOCKS_DB[id];
const stock = GS.stocks[id];
return `
<div class="border border-gray-700 bg-gray-900 p-3">
<div class="flex justify-between items-center mb-2">
<span class="font-bold text-white">${id} - ${data.name}</span>
<span class="text-yellow-400">${stock.price.toFixed(1)}cr</span>
</div>
<div class="text-xs text-gray-500 mb-2">Options expire in 3 game days. Premium: ${Math.round(stock.price * 0.15)}cr per contract.</div>
<div class="flex gap-2">
<button onclick="buyOption('${id}', 'call')" class="bg-black text-green-400 border border-green-400 px-3 py-1 text-xs hover:bg-green-900">BUY CALL (↑)</button>
<button onclick="buyOption('${id}', 'put')" class="bg-black text-red-400 border border-red-400 px-3 py-1 text-xs hover:bg-red-900">BUY PUT (↓)</button>
</div>
</div>`;
}).join('')}
</div>
</div>`;
}
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 = `
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
${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 `
<div class="border-2 p-4 ${isCurrent ? 'bg-gray-800' : 'bg-gray-900'} transition-all hover:bg-gray-800" style="border-color:${borderColor}">
<div class="flex items-center gap-3 mb-2">
<div class="w-10 h-10 rounded-full flex items-center justify-center" style="background:${d.color};${isUnlocked && !isCurrent ? 'box-shadow:0 0 10px ' + d.color : ''}">
<i class="fas ${d.icon} text-black"></i>
</div>
<div>
<h3 class="font-bold ${isCurrent ? 'neon-cyan' : isUnlocked ? 'text-white' : 'text-gray-600'}">${d.name}</h3>
${isCurrent ? '<span class="text-xs neon-cyan">◆ CURRENT LOCATION</span>' : ''}
</div>
</div>
<p class="text-xs text-gray-400 mb-2">${d.description}</p>
<div class="flex justify-between text-xs mb-2">
<span class="text-gray-500">Threat: <span style="color:${d.color}">${d.threatLevel}</span></span>
<span class="text-gray-500">Price Mod: ${Math.round(d.priceModifier * 100)}%</span>
</div>
${isUnlocked && !isCurrent ? `<button onclick="travelToDistrict('${id}')" class="neon-btn bg-black text-white border px-4 py-1 text-xs w-full" style="border-color:${d.color}">TRAVEL HERE</button>` : ''}
${!isUnlocked ? `<button onclick="unlockDistrict('${id}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-1 text-xs w-full">UNLOCK (${formatCredits(d.unlockCost)}cr)</button>` : ''}
</div>`;
}).join('')}
</div>`;
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 = `
<div class="space-y-6">
<!-- Active Quests -->
<div>
<h3 class="neon-pink text-lg font-bold mb-3"><i class="fas fa-scroll mr-2"></i>ACTIVE QUESTS</h3>
${GS.quests.active.length === 0 ? '<div class="text-gray-500 text-sm">No active quests. Check Available tab for new quests.</div>' : ''}
<div class="space-y-3">
${GS.quests.active.map(q => {
const quest = QUESTS_DB[q.id];
if (!quest) return '';
const pct = Math.round((q.progress / quest.steps) * 100);
return `
<div class="border border-gray-700 bg-gray-900 p-3">
<div class="flex justify-between items-start mb-2">
<h4 class="text-sm font-bold neon-cyan">${quest.name}</h4>
<span class="text-xs text-gray-500">${quest.type.toUpperCase()}</span>
</div>
<p class="text-xs text-gray-400 mb-2">${quest.description}</p>
<div class="progress-bar mb-1"><div class="progress-bar-fill" style="width:${pct}%"></div></div>
<div class="flex justify-between text-xs">
<span class="text-gray-500">${q.progress}/${quest.steps} steps</span>
<span class="text-yellow-400">+${quest.rewards.credits}cr | +${quest.rewards.xp}XP</span>
</div>
${q.progress >= quest.steps ? `<button onclick="completeQuest('${q.id}')" class="mt-2 neon-btn bg-black text-green-400 border border-green-400 px-4 py-1 text-xs w-full">COMPLETE QUEST</button>` : `<button onclick="advanceQuest('${q.id}')" class="mt-2 neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-4 py-1 text-xs w-full">ADVANCE (+1 step)</button>`}
</div>`;
}).join('')}
</div>
</div>
<!-- Available Quests -->
<div>
<h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-plus-circle mr-2"></i>AVAILABLE QUESTS</h3>
<div class="space-y-3">
${GS.quests.available.map(qId => {
const quest = QUESTS_DB[qId];
if (!quest) return '';
return `
<div class="border border-gray-700 bg-gray-900 p-3">
<h4 class="text-sm font-bold neon-purple">${quest.name}</h4>
<p class="text-xs text-gray-400 mb-2">${quest.description}</p>
<div class="flex justify-between text-xs">
<span class="text-gray-500">${quest.steps} steps | ${quest.type}</span>
<span class="text-yellow-400">+${quest.rewards.credits}cr | +${quest.rewards.xp}XP</span>
</div>
<button onclick="acceptQuest('${qId}')" class="mt-2 neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-4 py-1 text-xs w-full">ACCEPT QUEST</button>
</div>`;
}).join('')}
${GS.quests.available.length === 0 ? '<div class="text-gray-500 text-sm">No new quests available right now.</div>' : ''}
</div>
</div>
<!-- Completed Quests -->
${GS.quests.completed.length > 0 ? `
<div>
<h3 class="text-green-400 text-lg font-bold mb-3"><i class="fas fa-check-circle mr-2"></i>COMPLETED QUESTS</h3>
<div class="space-y-2">
${GS.quests.completed.map(qId => {
const quest = QUESTS_DB[qId];
if (!quest) return '';
return `<div class="text-xs text-gray-500 border-b border-gray-800 pb-1"><i class="fas fa-check text-green-400 mr-1"></i>${quest.name}</div>`;
}).join('')}
</div>
</div>` : ''}
</div>`;
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 = `
<div>
<div class="flex justify-between items-center mb-4">
<div class="text-xs text-gray-400">Items: ${GS.inventory.reduce((a, i) => a + i.qty, 0)} | Credits: <span class="text-yellow-400">${formatCredits(GS.player.credits)}cr</span></div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 max-h-[60vh] overflow-y-auto">
${GS.inventory.map(inv => {
const item = ITEMS_DB[inv.id];
if (!item) return '';
const canUse = ['medical', 'drug', 'mutation-serum'].includes(item.category);
return `
<div class="border border-gray-700 bg-gray-900 p-3 hover:border-[#05d9e8] transition-colors">
<div class="flex items-center gap-2 mb-2">
<div class="${item.color} text-2xl"><i class="fas ${item.icon}"></i></div>
<div>
<div class="text-sm font-bold text-white">${item.name} <span class="text-gray-500">x${inv.qty}</span></div>
<div class="text-xs text-gray-500">${item.category.toUpperCase()}</div>
</div>
</div>
<div class="text-xs text-gray-400 mb-2">${item.description}</div>
<div class="text-xs text-yellow-400 mb-2">Value: ~${formatCredits(Math.round(GS.market[inv.id]?.currentPrice * 0.7 || 0))}cr</div>
<div class="flex gap-1">
${canUse ? `<button onclick="useItem('${inv.id}')" class="neon-btn bg-black text-green-400 border border-green-400 px-2 py-1 text-xs flex-1">USE</button>` : ''}
${item.basePrice > 0 && item.tradeable !== false ? `<button onclick="openMarket(); setTimeout(()=>marketTab('sell'), 100);" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-2 py-1 text-xs flex-1">SELL</button>` : ''}
<button onclick="dropItem('${inv.id}')" class="neon-btn bg-black text-red-400 border border-red-400 px-2 py-1 text-xs">DROP</button>
</div>
</div>`;
}).join('')}
</div>
</div>`;
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 = `
<div class="space-y-4">
${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 `
<div class="border border-gray-700 bg-gray-900 p-4">
<div class="flex items-center gap-3 mb-3">
<div class="w-12 h-12 ${data.color} rounded-full flex items-center justify-center text-white font-bold">${data.abbr}</div>
<div>
<h3 class="font-bold text-white">${data.name}</h3>
<span class="text-xs" style="color:${color}">${faction.status.toUpperCase()}</span>
</div>
</div>
<p class="text-xs text-gray-400 mb-2">${data.description}</p>
<p class="text-xs text-gray-500 mb-2"><i class="fas fa-star text-yellow-400 mr-1"></i>${data.bonus}</p>
<div class="progress-bar mb-1"><div class="progress-bar-fill" style="width:${repPct}%"></div></div>
<div class="flex justify-between text-xs">
<span class="text-gray-500">Reputation: ${faction.reputation}</span>
<span style="color:${color}">${faction.status}</span>
</div>
</div>`;
}).join('')}
<!-- Mr. Bleak -->
<div class="border-2 border-yellow-400 bg-gray-900 p-4" style="box-shadow:0 0 10px #ffd700">
<div class="flex items-center gap-3 mb-3">
<div class="w-12 h-12 bg-white rounded-full flex items-center justify-center text-black font-bold text-sm">MB</div>
<div>
<h3 class="font-bold gold-text">MR. BLEAK</h3>
<span class="text-xs gold-text">INDEBTED</span>
</div>
</div>
<p class="text-xs text-gray-400 mb-2">Albino loan shark king. Defaulting triggers world events and hunter mini-boss fights.</p>
${GS.loans.length > 0 ? GS.loans.map((loan, i) => `
<div class="border border-yellow-400 bg-black p-2 mt-2">
<div class="text-xs text-yellow-400">Loan: ${formatCredits(loan.amount)}cr | ${Math.round(loan.interest*100)}% interest | ${loan.daysLeft} days left</div>
<div class="text-xs text-gray-500">Owed: ${formatCredits(Math.round(loan.amount * (1 + loan.interest * (7 - loan.daysLeft) / 7)))}cr</div>
<div class="flex gap-2 mt-1">
<button onclick="repayLoan(${i})" class="bg-black text-green-400 border border-green-400 px-2 py-1 text-xs">REPAY</button>
<button onclick="takeNewLoan()" class="bg-black text-yellow-400 border border-yellow-400 px-2 py-1 text-xs">BORROW MORE</button>
</div>
</div>
`).join('') : '<button onclick="takeNewLoan()" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-2 text-xs mt-2">TAKE A LOAN</button>'}
</div>
</div>`;
openModal('CONTACTS & FACTIONS', content);
}
function takeNewLoan() {
const amounts = [500, 1000, 2000, 5000];
const content = `
<div class="space-y-3">
<div class="text-sm text-gray-400 mb-4">Mr. Bleak offers loans at <span class="text-red-400">12% interest</span>. Repay within 7 days or face the consequences.</div>
${amounts.map(amt => `
<button onclick="confirmLoan(${amt})" class="w-full border border-yellow-400 bg-gray-900 p-3 text-left hover:bg-gray-800">
<div class="flex justify-between">
<span class="text-yellow-400 font-bold">${formatCredits(amt)}cr</span>
<span class="text-gray-400">Repay: ${formatCredits(Math.round(amt * 1.12))}cr in 7 days</span>
</div>
</button>
`).join('')}
<button onclick="openFactions()" class="w-full border border-gray-600 bg-black text-gray-400 p-2 text-sm">CANCEL</button>
</div>`;
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 = `
<div class="space-y-6">
<div>
<h3 class="neon-purple text-lg font-bold mb-3"><i class="fas fa-dna mr-2"></i>ACTIVE MUTATIONS (${GS.mutations.length}/6)</h3>
<div class="space-y-3">
${activeMutations.map(m => `
<div class="border border-[#d300c5] bg-gray-900 p-3">
<div class="flex items-center gap-3">
<div class="${m.color} text-3xl"><i class="fas ${m.icon}"></i></div>
<div class="flex-1">
<div class="font-bold neon-purple">${m.name}</div>
<div class="text-xs text-gray-400">${m.description}</div>
<div class="text-xs mt-1">
${Object.entries(m.statBonus || {}).map(([s, v]) => `<span class="text-green-400">+${v} ${s}</span>`).join(' ')}
${Object.entries(m.statPenalty || {}).map(([s, v]) => `<span class="text-red-400">${v} ${s}</span>`).join(' ')}
</div>
</div>
</div>
</div>
`).join('')}
${GS.mutations.length === 0 ? '<div class="text-gray-500 text-sm">No mutations active.</div>' : ''}
</div>
</div>
<div>
<h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-flask mr-2"></i>AVAILABLE MUTATIONS</h3>
<div class="text-xs text-gray-400 mb-3">Acquire mutations through quests, exposure to relics, or mutation serums.</div>
<div class="space-y-2">
${availableMutations.map(([id, m]) => `
<div class="border border-gray-700 bg-gray-900 p-3 flex justify-between items-center">
<div class="flex items-center gap-3">
<div class="${m.color} text-2xl"><i class="fas ${m.icon}"></i></div>
<div>
<div class="text-sm font-bold text-white">${m.name}</div>
<div class="text-xs text-gray-400">Risk: <span class="${m.risk === 'high' ? 'text-red-400' : m.risk === 'medium' ? 'text-yellow-400' : 'text-green-400'}">${m.risk.toUpperCase()}</span></div>
</div>
</div>
${GS.mutations.length < 6 ? `<button onclick="attemptMutation('${id}')" class="neon-btn bg-black text-[#d300c5] border border-[#d300c5] px-3 py-1 text-xs">ACQUIRE</button>` : '<span class="text-xs text-red-400">MAX MUTATIONS</span>'}
</div>
`).join('')}
</div>
</div>
<div class="border border-yellow-400 bg-black p-3 text-xs text-yellow-400">
<i class="fas fa-exclamation-triangle mr-1"></i> WARNING: Mutations have both benefits and side effects. High-risk mutations may cause permanent stat penalties. Max 6 mutations.
</div>
</div>`;
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 = `
<div class="space-y-4">
<div class="text-xs text-gray-400 mb-4">Combine components to craft valuable items. Required materials are deducted from your inventory.</div>
${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 `<span class="${enough ? 'text-green-400' : 'text-red-400'}">${ITEMS_DB[ingId]?.name || ingId}: ${have}/${qty}</span>`;
}).join(', ');
return `
<div class="border ${canCraft ? 'border-[#05d9e8]' : 'border-gray-700'} bg-gray-900 p-4">
<div class="flex items-center gap-3 mb-2">
<div class="${output.color} text-3xl"><i class="fas ${output.icon}"></i></div>
<div class="flex-1">
<div class="font-bold neon-cyan">${recipe.name} <span class="text-gray-500 text-xs">(x${recipe.output})</span></div>
<div class="text-xs text-gray-400 mb-1">${output.description}</div>
<div class="text-xs">Materials: ${ingredientList}</div>
</div>
<div class="text-right">
<div class="text-xs text-gray-500 mb-1">+${recipe.xp} XP</div>
<button onclick="craftItem('${id}')" class="neon-btn bg-black ${canCraft ? 'text-green-400 border-green-400' : 'text-gray-600 border-gray-600 cursor-not-allowed'} border px-4 py-2 text-xs" ${canCraft ? '' : 'disabled'}>${canCraft ? 'CRAFT' : 'MISSING'}</button>
</div>
</div>
</div>`;
}).join('')}
</div>`;
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 = `
<div class="space-y-6">
<div>
<h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-home mr-2"></i>CURRENT SAFEHOUSE: ${DISTRICTS_DB[GS.currentDistrict].name}</h3>
${owned ? `
<div class="border border-[#05d9e8] bg-gray-900 p-4">
<div class="flex justify-between items-center mb-3">
<div>
<span class="text-yellow-400 font-bold">Level ${owned.level}</span>
<span class="text-gray-400 text-sm ml-2">${owned.bonus}</span>
</div>
<button onclick="upgradeSafehouse('${GS.currentDistrict}')" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-3 py-1 text-xs">UPGRADE (${formatCredits(500 * owned.level)}cr)</button>
</div>
<div class="grid grid-cols-2 gap-3 text-sm">
<div><span class="text-gray-500">Storage:</span> <span class="text-white">+${owned.level * 5} slots</span></div>
<div><span class="text-gray-500">Income:</span> <span class="text-green-400">+${50 * owned.level}cr/day</span></div>
<div><span class="text-gray-500">Defense:</span> <span class="text-white">${owned.level * 10}%</span></div>
<div><span class="text-gray-500">Craft Bonus:</span> <span class="text-white">+${owned.level * 5}%</span></div>
</div>
</div>
` : `
<div class="border border-gray-700 bg-gray-900 p-4 text-center">
<div class="text-gray-500 mb-3">No safehouse in this district.</div>
<button onclick="buySafehouse('${GS.currentDistrict}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-2 text-sm">BUY SAFEHOUSE (${formatCredits(2000)}cr)</button>
</div>
`}
</div>
<div>
<h3 class="neon-pink text-lg font-bold mb-3"><i class="fas fa-building mr-2"></i>OTHER DISTRICT SAFEHOUSES</h3>
<div class="space-y-2">
${allSafehouses.filter(([id]) => id !== GS.currentDistrict).map(([id, d]) => {
const sh = GS.safehouses[id];
return `
<div class="border border-gray-700 bg-gray-900 p-3 flex justify-between items-center">
<div>
<span class="text-white font-bold">${d.name}</span>
${sh ? `<span class="text-xs text-green-400 ml-2">Level ${sh.level}</span>` : '<span class="text-xs text-red-400 ml-2">No safehouse</span>'}
</div>
${!sh ? `<button onclick="buySafehouse('${id}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-3 py-1 text-xs">BUY (${formatCredits(2000)}cr)</button>` : `<button onclick="upgradeSafehouse('${id}')" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-3 py-1 text-xs">UPGRADE (L${sh.level + 1})</button>`}
</div>`;
}).join('')}
</div>
</div>
<div class="border border-gray-700 bg-black p-3 text-xs text-gray-400">
<i class="fas fa-info-circle mr-1"></i> Safehouses provide passive income, extra storage, crafting bonuses, and defense against raids. Upgrade to increase bonuses.
</div>
</div>`;
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 = `
<div class="space-y-6">
<div class="text-center border border-[#ff2a6d] bg-gray-900 p-6" style="box-shadow:0 0 15px #ff2a6d">
<h3 class="title-font text-2xl neon-pink mb-2">DISTRICT TAKEOVER</h3>
<p class="text-gray-400 text-sm">Attempt to seize control of <span class="text-white">${district.name}</span></p>
<p class="text-xs text-gray-500 mt-2">Threat Level: <span style="color:${district.color}">${district.threatLevel}</span></p>
</div>
<div class="text-sm text-gray-300">
<p>Launch a takeover attempt to gain control of this district. Success grants passive income, reduced prices, and faction reputation. Failure costs HP and credits.</p>
</div>
<div class="border border-gray-700 bg-gray-900 p-4">
<h4 class="font-bold neon-cyan mb-2">YOUR COMBAT STATS</h4>
<div class="grid grid-cols-3 gap-2 text-sm">
<div>🤜 Attack: <span class="text-white">${GS.player.stats.strength + GS.player.stats.agility}</span></div>
<div>🛡 Defense: <span class="text-white">${GS.player.stats.endurance + GS.player.stats.strength}</span></div>
<div>🎲 Luck: <span class="text-white">${GS.player.stats.luck}</span></div>
<div>❤ HP: <span class="text-green-400">${GS.player.hp}/${GS.player.maxHp}</span></div>
<div>⚡ Agility: <span class="text-white">${GS.player.stats.agility}</span></div>
<div>🎯 Charisma: <span class="text-white">${GS.player.stats.charisma}</span></div>
</div>
</div>
<div>
<h4 class="font-bold neon-pink mb-2">SELECT APPROACH</h4>
<div class="space-y-2">
<button onclick="startCombat('force')" class="w-full border border-red-400 bg-gray-900 p-3 text-left hover:bg-gray-800">
<div class="font-bold text-red-400"><i class="fas fa-fist-raised mr-2"></i>BRUTE FORCE</div>
<div class="text-xs text-gray-500">Strength-focused. High damage, high risk.</div>
</button>
<button onclick="startCombat('stealth')" class="w-full border border-[#05d9e8] bg-gray-900 p-3 text-left hover:bg-gray-800">
<div class="font-bold neon-cyan"><i class="fas fa-eye-slash mr-2"></i>STEALTH INFILTRATION</div>
<div class="text-xs text-gray-500">Agility-focused. Lower reward, lower risk.</div>
</button>
<button onclick="startCombat('diplomacy')" class="w-full border border-[#d300c5] bg-gray-900 p-3 text-left hover:bg-gray-800">
<div class="font-bold neon-purple"><i class="fas fa-handshake mr-2"></i>DIPLOMATIC COUP</div>
<div class="text-xs text-gray-500">Charisma-focused. Can gain allies, but slower.</div>
</button>
</div>
</div>
</div>`;
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 = `
<div class="text-center space-y-4">
<div class="text-6xl mb-4">${success ? '⚔️' : '💀'}</div>
<h3 class="title-font text-2xl ${success ? 'neon-cyan' : 'neon-pink'}">${success ? 'TAKEOVER SUCCESSFUL!' : 'TAKEOVER FAILED!'}</h3>
<div class="text-gray-400 text-sm">
Approach: ${approach.toUpperCase()} | Success Rate: ${Math.round(successRate * 100)}%
</div>
${success ? `
<div class="border border-[#05d9e8] bg-gray-900 p-4">
<div class="text-sm mb-2"><span class="neon-cyan">District Influence:</span> <span class="text-white">${district.name}</span></div>
<div class="text-sm"><span class="text-yellow-400">Credits Earned:</span> <span class="text-white">+${random(200, 800)}cr</span></div>
<div class="text-sm"><span class="text-green-400">XP Earned:</span> <span class="text-white">+150</span></div>
<div class="text-sm"><span class="text-purple-400">Faction Bonus:</span> <span class="text-white">Varies by allegiance</span></div>
</div>
` : `
<div class="border border-[#ff2a6d] bg-gray-900 p-4">
<div class="text-sm"><span class="neon-pink">HP Lost:</span> <span class="text-white">-${random(10, 30)}</span></div>
<div class="text-sm"><span class="text-red-400">Credits Lost:</span> <span class="text-white">-${random(50, 200)}cr</span></div>
<div class="text-sm mt-2 text-gray-500">Better prepare before your next attempt.</div>
</div>
`}
<button onclick="closeModal()" class="neon-btn bg-black ${success ? 'text-[#05d9e8] border-[#05d9e8]' : 'text-[#ff2a6d] border-[#ff2a6d]'} border px-6 py-2">CONTINUE</button>
</div>`;
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 = `
<div class="space-y-4">
<div class="flex items-center gap-4">
<div class="${item.color} text-5xl"><i class="fas ${item.icon}"></i></div>
<div>
<h3 class="font-bold text-white text-lg">${item.name}</h3>
<p class="text-gray-400 text-sm">${item.description}</p>
<p class="text-xs text-gray-500 mt-1">Category: ${item.category.toUpperCase()}</p>
</div>
</div>
<div class="border border-[#d300c5] bg-black p-4">
<div class="flex justify-between mb-2">
<span class="text-gray-400">Current Bid:</span>
<span class="text-yellow-400 font-bold">${formatCredits(currentBid)}cr</span>
</div>
<div class="flex justify-between mb-2">
<span class="text-gray-400">Minimum Bid:</span>
<span class="text-white">${formatCredits(minBid)}cr</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Your Credits:</span>
<span class="${GS.player.credits >= minBid ? 'text-green-400' : 'text-red-400'}">${formatCredits(GS.player.credits)}cr</span>
</div>
</div>
<div class="flex gap-3">
<input type="number" id="auction-bid-input" value="${minBid}" min="${minBid}" class="flex-1 bg-gray-800 border border-[#05d9e8] px-3 py-2 text-white focus:outline-none" style="color-scheme:dark">
<button onclick="submitBid('${itemId}')" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-6 py-2">PLACE BID</button>
</div>
<div class="text-xs text-gray-500"><i class="fas fa-info-circle mr-1"></i> Winning bids are final. Failed bids are refunded minus a 5% fee.</div>
</div>`;
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 += `<p class="text-[#ff2a6d] mb-1">VEIL: <span class="text-gray-300">"${message}"</span></p>`;
// 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 += `<p class="text-[#05d9e8] mb-1">${pick(responses)}</p>`;
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 = `
<div class="flex justify-between items-center mb-2">
<h2 class="neon-cyan text-lg font-bold">PLAYER PROFILE</h2>
<span class="text-xs gold-text">LEVEL ${GS.player.level}</span>
</div>
<div class="flex items-center space-x-3 mb-4">
<div class="w-16 h-16 bg-gray-800 border-2 border-neon-pink relative overflow-hidden">
<i class="fas fa-skull text-3xl text-[#ff2a6d] absolute inset-0 flex items-center justify-center"></i>
<div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-70 text-center py-1">
<span class="text-xs neon-pink">${GS.player.class.toUpperCase()}</span>
</div>
</div>
<div>
<h3 class="neon-pink text-sm">ALIAS: <span class="text-white">"${GS.player.name}"</span></h3>
<h3 class="neon-cyan text-sm">CREDITS: <span class="text-white">${formatCredits(GS.player.credits)}</span></h3>
<h3 class="text-sm text-green-400">HP: <span class="text-white">${GS.player.hp}/${GS.player.maxHp}</span></h3>
</div>
</div>
<div class="mb-3">
<div class="flex justify-between text-xs mb-1">
<span class="neon-pink">XP: ${GS.player.xp}/${GS.player.xpToNext}</span>
<span class="neon-cyan">${levelXpPct}%</span>
</div>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: ${levelXpPct}%"></div>
</div>
</div>
${GS.player.statPoints > 0 ? `<div class="text-xs text-yellow-400 pixel-font mb-2">⬆ ${GS.player.statPoints} STAT POINTS AVAILABLE!</div>` : ''}`;
}
// 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]) => `
<div>
<div class="flex justify-between text-xs">
<span class="neon-pink">${statNames[stat] || stat.toUpperCase()}</span>
<span>${val}</span>
</div>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: ${Math.min(100, Math.round((val / 30) * 100))}%"></div>
</div>
</div>`
).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();
}
}
});
// ============================================
// 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' },