Add complete game loop: training, revenue, market, offline catch-up

- Model training system: training jobs produce TrainedModels with
  calculated capabilities based on compute, data, and research
- Market system: organic API demand and consumer subscriptions now
  generate real revenue from deployed models
- Talent system: salary costs calculated from department headcount
- Toast notification system for game events (training complete, etc.)
- Offline catch-up: progress bar + summary screen when returning
- Market page: pricing controls for API and subscription products
- Finance page: income statement, cash charts, funding history
- Tick processor now runs all 7 systems in correct dependency order

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-24 17:02:58 -04:00
parent fdc8e544ae
commit 9a48c188ad
12 changed files with 757 additions and 21 deletions
+28 -1
View File
@@ -1,15 +1,42 @@
import { useState, useEffect } from 'react';
import { useGameStore } from '@/store';
import { MainLayout } from '@/components/layout/MainLayout';
import { NewGameScreen } from '@/components/game/NewGameScreen';
import { OfflineCatchUp } from '@/components/game/OfflineCatchUp';
import { useGameLoop } from '@/hooks/useGameLoop';
import { TICK_INTERVAL_MS } from '@ai-tycoon/shared';
export function App() {
const companyName = useGameStore((s) => s.meta.companyName);
useGameLoop();
const lastTickTimestamp = useGameStore((s) => s.meta.lastTickTimestamp);
const [catchUpTicks, setCatchUpTicks] = useState<number | null>(null);
const [catchUpDone, setCatchUpDone] = useState(false);
useEffect(() => {
if (!companyName || catchUpDone) return;
const elapsed = Date.now() - lastTickTimestamp;
const missed = Math.floor(elapsed / TICK_INTERVAL_MS);
if (missed > 10) {
setCatchUpTicks(missed);
} else {
setCatchUpDone(true);
}
}, [companyName, lastTickTimestamp, catchUpDone]);
useGameLoop(!catchUpDone);
if (!companyName) {
return <NewGameScreen />;
}
if (catchUpTicks !== null && !catchUpDone) {
return (
<OfflineCatchUp
missedTicks={catchUpTicks}
onComplete={() => setCatchUpDone(true)}
/>
);
}
return <MainLayout />;
}
@@ -0,0 +1,83 @@
import { useEffect, useState } from 'react';
import { X, CheckCircle, AlertTriangle, Info, AlertCircle } from 'lucide-react';
import { useGameStore, type GameNotification } from '@/store';
interface Toast extends GameNotification {
exiting: boolean;
}
export function ToastContainer() {
const notifications = useGameStore((s) => s.notifications);
const dismissNotification = useGameStore((s) => s.dismissNotification);
const [toasts, setToasts] = useState<Toast[]>([]);
const [seen, setSeen] = useState(new Set<string>());
useEffect(() => {
const newNotifs = notifications.filter(n => !n.read && !seen.has(n.id));
if (newNotifs.length === 0) return;
setSeen(prev => {
const next = new Set(prev);
for (const n of newNotifs) next.add(n.id);
return next;
});
setToasts(prev => [
...newNotifs.map(n => ({ ...n, exiting: false })),
...prev,
].slice(0, 5));
}, [notifications, seen]);
useEffect(() => {
if (toasts.length === 0) return;
const timer = setTimeout(() => {
setToasts(prev => {
if (prev.length === 0) return prev;
const last = prev[prev.length - 1];
dismissNotification(last.id);
return prev.slice(0, -1);
});
}, 4000);
return () => clearTimeout(timer);
}, [toasts, dismissNotification]);
if (toasts.length === 0) return null;
return (
<div className="fixed top-16 right-4 z-50 flex flex-col gap-2 w-80">
{toasts.map((toast) => (
<div
key={toast.id}
className={`bg-surface-800 border rounded-lg p-3 shadow-lg transition-all duration-300 ${
toast.type === 'success' ? 'border-success/50' :
toast.type === 'warning' ? 'border-warning/50' :
toast.type === 'danger' ? 'border-danger/50' :
'border-surface-600'
}`}
>
<div className="flex items-start gap-2">
<div className="mt-0.5">
{toast.type === 'success' && <CheckCircle size={16} className="text-success" />}
{toast.type === 'warning' && <AlertTriangle size={16} className="text-warning" />}
{toast.type === 'danger' && <AlertCircle size={16} className="text-danger" />}
{toast.type === 'info' && <Info size={16} className="text-accent-light" />}
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium">{toast.title}</div>
<div className="text-xs text-surface-400">{toast.message}</div>
</div>
<button
onClick={() => {
dismissNotification(toast.id);
setToasts(prev => prev.filter(t => t.id !== toast.id));
}}
className="text-surface-500 hover:text-surface-300"
>
<X size={14} />
</button>
</div>
</div>
))}
</div>
);
}
@@ -0,0 +1,121 @@
import { useState, useEffect, useRef } from 'react';
import { formatMoney, formatDuration, formatNumber, MAX_OFFLINE_TICKS, TICK_INTERVAL_MS } from '@ai-tycoon/shared';
import { GameEngine } from '@ai-tycoon/game-engine';
import { useGameStore } from '@/store';
interface OfflineResult {
ticksProcessed: number;
revenue: number;
expenses: number;
duration: number;
}
export function OfflineCatchUp({ missedTicks, onComplete }: { missedTicks: number; onComplete: () => void }) {
const [progress, setProgress] = useState(0);
const [result, setResult] = useState<OfflineResult | null>(null);
const processingRef = useRef(false);
useEffect(() => {
if (processingRef.current) return;
processingRef.current = true;
const capped = Math.min(missedTicks, MAX_OFFLINE_TICKS);
const batchSize = 100;
let processed = 0;
let totalRevenue = 0;
let totalExpenses = 0;
const engine = new GameEngine({
getState: () => {
const s = useGameStore.getState();
return {
meta: s.meta, economy: s.economy, infrastructure: s.infrastructure,
compute: s.compute, research: s.research, models: s.models,
market: s.market, competitors: s.competitors, talent: s.talent,
data: s.data, reputation: s.reputation, events: s.events,
achievements: s.achievements,
};
},
setState: (partial) => useGameStore.getState().updateState(partial),
});
function processBatch() {
const end = Math.min(processed + batchSize, capped);
const batchResult = engine.processOfflineTicks(end - processed);
totalRevenue += batchResult.revenue;
totalExpenses += batchResult.expenses;
processed = end;
setProgress(processed / capped);
if (processed < capped) {
requestAnimationFrame(processBatch);
} else {
setResult({
ticksProcessed: processed,
revenue: totalRevenue,
expenses: totalExpenses,
duration: missedTicks,
});
}
}
requestAnimationFrame(processBatch);
}, [missedTicks]);
if (result) {
return (
<div className="min-h-screen flex items-center justify-center bg-surface-950">
<div className="max-w-md w-full bg-surface-900 border border-surface-700 rounded-xl p-6 mx-4">
<h2 className="text-xl font-bold mb-4">Welcome Back!</h2>
<p className="text-sm text-surface-400 mb-4">
You were away for {formatDuration(result.duration)}. Here's what happened:
</p>
<div className="space-y-2 mb-6">
<div className="flex justify-between bg-surface-800 rounded-lg p-3">
<span className="text-sm text-surface-300">Revenue earned</span>
<span className="text-sm font-mono text-success">+{formatMoney(result.revenue)}</span>
</div>
<div className="flex justify-between bg-surface-800 rounded-lg p-3">
<span className="text-sm text-surface-300">Expenses</span>
<span className="text-sm font-mono text-danger">-{formatMoney(result.expenses)}</span>
</div>
<div className="flex justify-between bg-surface-800 rounded-lg p-3">
<span className="text-sm text-surface-300">Net</span>
<span className={`text-sm font-mono ${result.revenue - result.expenses >= 0 ? 'text-success' : 'text-danger'}`}>
{formatMoney(result.revenue - result.expenses)}
</span>
</div>
<div className="flex justify-between bg-surface-800 rounded-lg p-3">
<span className="text-sm text-surface-300">Time simulated</span>
<span className="text-sm font-mono">{formatNumber(result.ticksProcessed)} ticks</span>
</div>
</div>
<button
onClick={onComplete}
className="w-full bg-accent hover:bg-accent-dark text-white font-semibold py-3 rounded-lg transition-colors"
>
Continue
</button>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-surface-950">
<div className="max-w-md w-full mx-4 text-center">
<h2 className="text-xl font-bold mb-2">Catching up...</h2>
<p className="text-sm text-surface-400 mb-4">
Simulating {formatNumber(Math.min(missedTicks, MAX_OFFLINE_TICKS))} ticks
</p>
<div className="h-2 bg-surface-800 rounded-full overflow-hidden mb-2">
<div
className="h-full bg-accent rounded-full transition-all duration-100"
style={{ width: `${progress * 100}%` }}
/>
</div>
<span className="text-xs text-surface-500">{Math.floor(progress * 100)}%</span>
</div>
</div>
);
}
@@ -1,10 +1,13 @@
import { Sidebar } from './Sidebar';
import { TopBar } from './TopBar';
import { ToastContainer } from '@/components/common/ToastContainer';
import { useGameStore } from '@/store';
import { DashboardPage } from '@/pages/DashboardPage';
import { InfrastructurePage } from '@/pages/InfrastructurePage';
import { ModelsPage } from '@/pages/ModelsPage';
import { SettingsPage } from '@/pages/SettingsPage';
import { MarketPage } from '@/pages/MarketPage';
import { FinancePage } from '@/pages/FinancePage';
export function MainLayout() {
const activePage = useGameStore((s) => s.activePage);
@@ -18,6 +21,7 @@ export function MainLayout() {
<PageRouter page={activePage} />
</main>
</div>
<ToastContainer />
</div>
);
}
@@ -27,6 +31,8 @@ function PageRouter({ page }: { page: string }) {
case 'dashboard': return <DashboardPage />;
case 'infrastructure': return <InfrastructurePage />;
case 'models': return <ModelsPage />;
case 'market': return <MarketPage />;
case 'finance': return <FinancePage />;
case 'settings': return <SettingsPage />;
default: return <PlaceholderPage name={page} />;
}
+19 -3
View File
@@ -1,14 +1,15 @@
import { useEffect, useRef } from 'react';
import { GameEngine } from '@ai-tycoon/game-engine';
import type { TickNotification } from '@ai-tycoon/game-engine';
import { useGameStore } from '@/store';
export function useGameLoop() {
export function useGameLoop(skip = false) {
const engineRef = useRef<GameEngine | null>(null);
const companyName = useGameStore((s) => s.meta.companyName);
const gameSpeed = useGameStore((s) => s.meta.gameSpeed);
useEffect(() => {
if (!companyName) return;
if (!companyName || skip) return;
const engine = new GameEngine({
getState: () => {
@@ -30,7 +31,22 @@ export function useGameLoop() {
};
},
setState: (partial) => {
const notifications = (partial as Record<string, unknown>)['_notifications'] as TickNotification[] | undefined;
delete (partial as Record<string, unknown>)['_notifications'];
useGameStore.getState().updateState(partial);
if (notifications?.length) {
const store = useGameStore.getState();
for (const n of notifications) {
store.addNotification({
title: n.title,
message: n.message,
type: n.type,
tick: store.meta.tickCount,
});
}
}
},
});
@@ -41,7 +57,7 @@ export function useGameLoop() {
engine.stop();
engineRef.current = null;
};
}, [companyName]);
}, [companyName, skip]);
useEffect(() => {
if (engineRef.current) {
+151
View File
@@ -0,0 +1,151 @@
import { useGameStore } from '@/store';
import { formatMoney, formatPercent } from '@ai-tycoon/shared';
import { TrendingUp, TrendingDown, DollarSign, PiggyBank, BarChart3 } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, BarChart, Bar, CartesianGrid } from 'recharts';
export function FinancePage() {
const money = useGameStore((s) => s.economy.money);
const revenuePerTick = useGameStore((s) => s.economy.revenuePerTick);
const expensesPerTick = useGameStore((s) => s.economy.expensesPerTick);
const totalRevenue = useGameStore((s) => s.economy.totalRevenue);
const totalExpenses = useGameStore((s) => s.economy.totalExpenses);
const funding = useGameStore((s) => s.economy.funding);
const history = useGameStore((s) => s.economy.financialHistory);
const infrastructure = useGameStore((s) => s.infrastructure);
const talent = useGameStore((s) => s.talent);
const netIncome = revenuePerTick - expensesPerTick;
const burnRate = expensesPerTick > revenuePerTick ? expensesPerTick - revenuePerTick : 0;
const runway = burnRate > 0 ? money / burnRate : Infinity;
const infraCosts = infrastructure.dataCenters.reduce(
(s, dc) => s + dc.energyCostPerTick + dc.maintenanceCostPerTick, 0,
);
const talentCosts = talent.totalSalaryPerTick;
return (
<div className="space-y-6">
<h2 className="text-2xl font-bold">Finance</h2>
<div className="grid grid-cols-4 gap-4">
<FinanceCard icon={DollarSign} label="Cash" value={formatMoney(money)} color="text-green-400" />
<FinanceCard
icon={TrendingUp}
label="Net Income/s"
value={formatMoney(netIncome)}
color={netIncome >= 0 ? 'text-green-400' : 'text-red-400'}
/>
<FinanceCard icon={PiggyBank} label="Valuation" value={formatMoney(funding.valuation)} color="text-purple-400" />
<FinanceCard
icon={BarChart3}
label="Runway"
value={runway === Infinity ? 'Infinite' : `${Math.floor(runway / 3600)}h`}
color={runway < 3600 ? 'text-red-400' : 'text-blue-400'}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<h3 className="text-sm font-medium text-surface-400 mb-4">Cash Over Time</h3>
{history.length > 1 ? (
<ResponsiveContainer width="100%" height={200}>
<AreaChart data={history}>
<defs>
<linearGradient id="cashGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#6366f1" stopOpacity={0.3} />
<stop offset="100%" stopColor="#6366f1" stopOpacity={0} />
</linearGradient>
</defs>
<XAxis dataKey="tick" hide />
<YAxis hide />
<Tooltip
contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
formatter={(v: number) => [formatMoney(v)]}
/>
<Area type="monotone" dataKey="money" stroke="#6366f1" fill="url(#cashGrad)" />
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-[200px] flex items-center justify-center text-surface-500 text-sm">
Data will appear as time passes
</div>
)}
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<h3 className="text-sm font-medium text-surface-400 mb-4">Income Statement (per second)</h3>
<div className="space-y-3">
<div className="flex justify-between text-sm">
<span className="text-surface-300">Revenue</span>
<span className="font-mono text-success">{formatMoney(revenuePerTick)}</span>
</div>
<div className="border-t border-surface-700" />
<div className="flex justify-between text-sm">
<span className="text-surface-400 pl-4">Infrastructure</span>
<span className="font-mono text-danger">-{formatMoney(infraCosts)}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-surface-400 pl-4">Talent</span>
<span className="font-mono text-danger">-{formatMoney(talentCosts)}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-surface-400 pl-4">Total Expenses</span>
<span className="font-mono text-danger">-{formatMoney(expensesPerTick)}</span>
</div>
<div className="border-t border-surface-700" />
<div className="flex justify-between text-sm font-semibold">
<span>Net Income</span>
<span className={`font-mono ${netIncome >= 0 ? 'text-success' : 'text-danger'}`}>
{formatMoney(netIncome)}
</span>
</div>
</div>
</div>
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<h3 className="text-sm font-medium text-surface-400 mb-3">Funding History</h3>
<div className="flex items-center gap-4 mb-3">
<div className="text-sm">
Founder Equity: <span className="font-mono font-semibold">{formatPercent(funding.founderEquity)}</span>
</div>
<div className="text-sm">
Total Raised: <span className="font-mono font-semibold">{formatMoney(funding.totalRaised)}</span>
</div>
</div>
{funding.completedRounds.length === 0 ? (
<p className="text-sm text-surface-500">No funding rounds completed yet.</p>
) : (
<div className="space-y-2">
{funding.completedRounds.map((round, i) => (
<div key={i} className="bg-surface-800 rounded-lg p-3 flex items-center justify-between">
<span className="text-sm font-medium capitalize">{round.type}</span>
<div className="flex items-center gap-4 text-sm">
<span className="font-mono text-success">{formatMoney(round.amount)}</span>
<span className="text-surface-400">{formatPercent(round.dilution)} dilution</span>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}
function FinanceCard({ icon: Icon, label, value, color }: {
icon: typeof DollarSign;
label: string;
value: string;
color: string;
}) {
return (
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<div className="flex items-center gap-2 mb-2">
<Icon size={16} className={color} />
<span className="text-xs text-surface-400 uppercase">{label}</span>
</div>
<div className="text-xl font-bold font-mono">{value}</div>
</div>
);
}
+145
View File
@@ -0,0 +1,145 @@
import { useGameStore } from '@/store';
import { formatNumber, formatMoney, formatPercent } from '@ai-tycoon/shared';
import { Users, Zap, Shield, TrendingUp, Settings2 } from 'lucide-react';
export function MarketPage() {
const consumers = useGameStore((s) => s.market.consumers);
const enterprise = useGameStore((s) => s.market.enterprise);
const overloadPolicy = useGameStore((s) => s.market.overloadPolicy);
const productLines = useGameStore((s) => s.models.productLines);
const inferenceUtil = useGameStore((s) => s.compute.inferenceUtilization);
const tokensCapacity = useGameStore((s) => s.compute.tokensPerSecondCapacity);
const tokensDemand = useGameStore((s) => s.compute.tokensPerSecondDemand);
const setProductPricing = useGameStore((s) => s.setProductPricing);
const chatProduct = productLines.find(p => p.type === 'chat-product');
const textApi = productLines.find(p => p.type === 'text-api');
return (
<div className="space-y-6">
<h2 className="text-2xl font-bold">Market</h2>
<div className="grid grid-cols-3 gap-4">
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<div className="flex items-center gap-2 mb-2">
<Users size={16} className="text-orange-400" />
<span className="text-xs text-surface-400 uppercase">Subscribers</span>
</div>
<div className="text-2xl font-bold font-mono">{formatNumber(consumers.totalSubscribers)}</div>
<div className="text-xs text-surface-400 mt-1">
Growth: {formatPercent(consumers.growthRatePerTick)}/s
{' '}Churn: {formatPercent(consumers.churnRatePerTick)}/s
</div>
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<div className="flex items-center gap-2 mb-2">
<Shield size={16} className="text-green-400" />
<span className="text-xs text-surface-400 uppercase">Satisfaction</span>
</div>
<div className="text-2xl font-bold font-mono">{formatPercent(consumers.satisfaction)}</div>
<div className="h-1.5 bg-surface-800 rounded-full mt-2 overflow-hidden">
<div
className={`h-full rounded-full ${consumers.satisfaction > 0.7 ? 'bg-success' : consumers.satisfaction > 0.4 ? 'bg-warning' : 'bg-danger'}`}
style={{ width: `${consumers.satisfaction * 100}%` }}
/>
</div>
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
<div className="flex items-center gap-2 mb-2">
<Zap size={16} className="text-blue-400" />
<span className="text-xs text-surface-400 uppercase">Load</span>
</div>
<div className="text-2xl font-bold font-mono">{formatPercent(inferenceUtil)}</div>
<div className="text-xs text-surface-400 mt-1">
{formatNumber(tokensDemand)} / {formatNumber(tokensCapacity)} tok/s
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
{chatProduct && (
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4 space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-semibold">Chat Product Pricing</h3>
<span className={`text-xs px-2 py-1 rounded-full ${chatProduct.isActive ? 'bg-success/20 text-success' : 'bg-surface-700 text-surface-400'}`}>
{chatProduct.isActive ? 'Active' : 'Inactive'}
</span>
</div>
<div>
<label className="block text-xs text-surface-400 mb-1">Monthly Subscription Price</label>
<div className="flex items-center gap-2">
<span className="text-sm">$</span>
<input
type="number"
value={chatProduct.pricing.subscriptionPrice}
onChange={(e) => setProductPricing(chatProduct.id, 'subscriptionPrice', Number(e.target.value))}
className="w-24 bg-surface-800 border border-surface-600 rounded px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-accent/50"
min={0}
step={5}
/>
<span className="text-xs text-surface-400">/month</span>
</div>
</div>
</div>
)}
{textApi && (
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4 space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-semibold">API Pricing</h3>
<span className={`text-xs px-2 py-1 rounded-full ${textApi.isActive ? 'bg-success/20 text-success' : 'bg-surface-700 text-surface-400'}`}>
{textApi.isActive ? 'Active' : 'Inactive'}
</span>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-surface-400 mb-1">Input ($/M tokens)</label>
<input
type="number"
value={textApi.pricing.inputTokenPrice}
onChange={(e) => setProductPricing(textApi.id, 'inputTokenPrice', Number(e.target.value))}
className="w-full bg-surface-800 border border-surface-600 rounded px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-accent/50"
min={0}
step={0.5}
/>
</div>
<div>
<label className="block text-xs text-surface-400 mb-1">Output ($/M tokens)</label>
<input
type="number"
value={textApi.pricing.outputTokenPrice}
onChange={(e) => setProductPricing(textApi.id, 'outputTokenPrice', Number(e.target.value))}
className="w-full bg-surface-800 border border-surface-600 rounded px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-accent/50"
min={0}
step={0.5}
/>
</div>
</div>
</div>
)}
</div>
<div className="bg-surface-900 border border-surface-700 rounded-xl p-4 space-y-3">
<h3 className="font-semibold flex items-center gap-2">
<Settings2 size={16} />
API Contracts
</h3>
{enterprise.activeContracts.length === 0 ? (
<p className="text-sm text-surface-500">No enterprise contracts yet. Improve your model quality and reputation to attract enterprise customers.</p>
) : (
<div className="space-y-2">
{enterprise.activeContracts.map(c => (
<div key={c.id} className="bg-surface-800 rounded-lg p-3 flex items-center justify-between">
<div>
<div className="text-sm font-medium">{c.customerName}</div>
<div className="text-xs text-surface-400">{formatNumber(c.tokensPerTick)} tok/s · SLA: {formatPercent(c.slaUptime)}</div>
</div>
<div className="text-sm font-mono text-success">{formatMoney(c.pricePerMToken)}/M tok</div>
</div>
))}
</div>
)}
</div>
</div>
);
}