async function api(action, value) {
const res = await fetch('game.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, value })
});
if (!res.ok) throw new Error('Network error: ' + res.status);
return res.json();
}
function appendLog(lines) {
const log = document.getElementById('log');
const atBottom = Math.abs(log.scrollHeight - log.scrollTop - log.clientHeight) < 4;
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
log.appendChild(div);
}
if (atBottom) log.scrollTop = log.scrollHeight;
}
function setState(state) {
if (!state) return;
const s = document.getElementById('state');
s.innerHTML = ''+`
Day: ${state.day}
Hours Left Today: ${state.hours_left}
Meals Today: ${state.meals}
Earned Today: ${state.earned}
Total Earned: ${state.earned_total}
Debt: ${state.debt}
Interest: ${(state.interest * 100).toFixed(0)}%
Wage: ${state.wage}
Efficiency: ${state.eff}
Enhancements: ${state.mods}
`;
const m = document.getElementById('miniState');
if (m) {
m.innerHTML = ''+`
Day${state.day}
Hours Left Today${state.hours_left}
Debt${state.debt}
Interest${(state.interest*100).toFixed(0)}%
Wage${state.wage}
Earned Today${state.earned}
Total Earned${state.earned_total}
Efficiency${state.eff}
Mods${state.mods}
`;
}
}
function setGameOver(summary) {
if (!summary) return;
appendLog(['', 'GAME OVER', summary]);
for (const btn of document.querySelectorAll('button[data-action]')) btn.disabled = true;
}
async function doAction(action, value) {
try {
const data = await api(action, value);
if (data.messages) appendLog(data.messages);
if (data.state) setState(data.state);
if (data.game_over) setGameOver(data.final_summary || '');
return data;
} catch (e) {
appendLog(['Error: ' + e.message]);
}
}
async function onLoad() {
await doAction('start');
}
async function handleWork() {
const s = prompt('How many hours would you like to work?');
if (s == null) return;
const hours = parseInt(s, 10);
if (!Number.isFinite(hours)) return appendLog(['Invalid entry.']);
await doAction('work', hours);
}
async function handleSleep() {
const s = prompt('How many hours would you like to sleep?');
if (s == null) return;
const hours = parseInt(s, 10);
if (!Number.isFinite(hours)) return appendLog(['Invalid entry.']);
await doAction('sleep', hours);
}
async function handleEnhance() {
const resp = await doAction('enhance');
if (resp && resp.can_install) {
const ok = confirm('Install an enhancement?');
if (ok) await doAction('install_enhancement');
}
}
async function resetGame() {
// Clear log and re-enable action buttons
const log = document.getElementById('log');
log.innerHTML = '';
for (const btn of document.querySelectorAll('button[data-action]')) btn.disabled = false;
await doAction('reset');
await doAction('start');
}
window.addEventListener('DOMContentLoaded', onLoad);