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>
);
}
+1
View File
@@ -1,2 +1,3 @@
export { GameEngine } from './engine';
export { processTick } from './tick';
export type { TickNotification } from './tick';
@@ -10,6 +10,7 @@ export interface MarketTickResult {
marketState: MarketState;
apiRevenue: number;
subscriptionRevenue: number;
totalTokenDemand: number;
}
export function processMarket(state: GameState, compute: ComputeState): MarketTickResult {
@@ -21,40 +22,68 @@ export function processMarket(state: GameState, compute: ComputeState): MarketTi
const chatProduct = state.models.productLines.find(p => p.type === 'chat-product');
const textApi = state.models.productLines.find(p => p.type === 'text-api');
// --- Consumer market (subscription product) ---
const consumers = { ...state.market.consumers };
let subscriptionRevenue = 0;
if (chatProduct?.isActive && bestModel) {
const growthRate = CONSUMER_BASE_GROWTH + modelQuality * CONSUMER_QUALITY_GROWTH_MULTIPLIER;
const churnRate = CONSUMER_BASE_CHURN * (1 + (1 - consumers.satisfaction));
const priceAttractiveness = Math.max(0, 1 - chatProduct.pricing.subscriptionPrice / 100);
const growthRate = (CONSUMER_BASE_GROWTH + modelQuality * CONSUMER_QUALITY_GROWTH_MULTIPLIER) * (0.5 + priceAttractiveness * 0.5);
const churnRate = CONSUMER_BASE_CHURN * (1 + (1 - consumers.satisfaction) * 2);
consumers.growthRatePerTick = growthRate;
consumers.churnRatePerTick = churnRate;
const newSubs = consumers.totalSubscribers * growthRate;
const lostSubs = consumers.totalSubscribers * churnRate;
consumers.totalSubscribers = Math.max(0, consumers.totalSubscribers + newSubs - lostSubs);
if (consumers.totalSubscribers < 10 && modelQuality > 0) {
consumers.totalSubscribers += 1;
if (consumers.totalSubscribers < 50 && modelQuality > 0.1) {
consumers.totalSubscribers += 2 + modelQuality * 5;
}
const loadPenalty = compute.inferenceUtilization > 0.9
? (compute.inferenceUtilization - 0.9) * 5
: 0;
consumers.satisfaction = Math.min(1, Math.max(0,
0.3 + modelQuality * 0.5 + (1 - compute.inferenceUtilization) * 0.2,
0.3 + modelQuality * 0.5 + (1 - Math.min(1, compute.inferenceUtilization)) * 0.2 - loadPenalty,
));
consumers.viralCoefficient = modelQuality > 0.5 ? 1 + (modelQuality - 0.5) * 2 : 0;
subscriptionRevenue = consumers.totalSubscribers * (chatProduct.pricing.subscriptionPrice / 2592000);
}
const subscriptionRevenue = chatProduct?.isActive
? consumers.totalSubscribers * (chatProduct.pricing.subscriptionPrice / 30 / 24 / 3600)
: 0;
// --- B2B API market (organic demand based on model quality + reputation) ---
const enterprise = { ...state.market.enterprise };
let apiRevenue = 0;
let organicApiTokens = 0;
if (textApi?.isActive && bestModel) {
let totalTokens = 0;
const reputationFactor = state.reputation.score / 100;
const qualityFactor = modelQuality;
const priceFactor = Math.max(0.1, 1 - (textApi.pricing.outputTokenPrice / 20));
organicApiTokens = Math.floor(
qualityFactor * reputationFactor * priceFactor * 50000 * (1 + state.meta.tickCount * 0.0001),
);
let contractTokens = 0;
for (const contract of enterprise.activeContracts) {
totalTokens += contract.tokensPerTick;
contractTokens += contract.tokensPerTick;
apiRevenue += (contract.tokensPerTick / 1_000_000) * contract.pricePerMToken;
}
enterprise.totalApiCallsPerTick = totalTokens / API_TOKENS_PER_REQUEST;
const totalApiTokens = organicApiTokens + contractTokens;
apiRevenue += (organicApiTokens / 1_000_000) * textApi.pricing.outputTokenPrice;
enterprise.totalApiCallsPerTick = totalApiTokens / API_TOKENS_PER_REQUEST;
}
const totalTokenDemand = organicApiTokens +
consumers.totalSubscribers * 100 +
enterprise.activeContracts.reduce((s, c) => s + c.tokensPerTick, 0);
return {
marketState: {
...state.market,
@@ -63,5 +92,6 @@ export function processMarket(state: GameState, compute: ComputeState): MarketTi
},
apiRevenue,
subscriptionRevenue,
totalTokenDemand,
};
}
@@ -0,0 +1,92 @@
import type { GameState, ModelsState, TrainedModel, ModelCapabilities } from '@ai-tycoon/shared';
export interface ModelTickResult {
modelsState: ModelsState;
modelCompleted: TrainedModel | null;
}
export function processModels(state: GameState): ModelTickResult {
const active = state.models.activeTraining;
if (!active) {
return { modelsState: state.models, modelCompleted: null };
}
const researcherBoost = state.talent.departments.research.headcount *
state.talent.departments.research.effectiveness;
const engineerBoost = state.talent.departments.engineering.headcount *
state.talent.departments.engineering.effectiveness;
const speedMultiplier = 1 + (researcherBoost + engineerBoost) * 0.05;
const newProgress = active.progressTicks + speedMultiplier;
if (newProgress >= active.totalTicks) {
const model = createTrainedModel(active.modelName, active.generation, active.allocatedCompute, active.allocatedDataTokens, state);
return {
modelsState: {
...state.models,
trainedModels: [...state.models.trainedModels, model],
activeTraining: null,
},
modelCompleted: model,
};
}
return {
modelsState: {
...state.models,
activeTraining: { ...active, progressTicks: newProgress },
},
modelCompleted: null,
};
}
function createTrainedModel(
name: string,
generation: number,
compute: number,
dataTokens: number,
state: GameState,
): TrainedModel {
const computeFactor = Math.log10(1 + compute) * 15;
const dataFactor = Math.log10(1 + dataTokens / 1e8) * 10;
const researchBonus = state.research.completedResearch.length * 3;
const efficiencyBonus = state.research.completedResearch.filter(r => r.includes('efficiency')).length * 5;
const baseCapability = Math.min(95, computeFactor + dataFactor + researchBonus + efficiencyBonus);
const researcherQuality = state.talent.departments.research.effectiveness;
const capabilities: ModelCapabilities = {
reasoning: clamp(baseCapability * (0.8 + Math.random() * 0.4) * (1 + researcherQuality * 0.2)),
coding: clamp(baseCapability * (0.7 + Math.random() * 0.5)),
creative: clamp(baseCapability * (0.6 + Math.random() * 0.6)),
multimodal: clamp(baseCapability * (0.3 + Math.random() * 0.3)),
agents: clamp(baseCapability * (0.2 + Math.random() * 0.3)),
speed: Math.max(1, 100 - compute * 0.5 + efficiencyBonus * 2),
};
const benchmarkScore = (capabilities.reasoning * 0.3 + capabilities.coding * 0.25 +
capabilities.creative * 0.2 + capabilities.multimodal * 0.15 + capabilities.agents * 0.1);
const safetyScore = 50 + Math.random() * 20;
const parameterCount = Math.pow(10, generation) * (0.5 + Math.random());
return {
id: crypto.randomUUID(),
name,
generation,
parameterCount,
trainingDataSize: dataTokens,
capabilities,
safetyScore,
benchmarkScore,
tuning: { preset: 'helpful-safe' },
isDeployed: false,
trainedAtTick: state.meta.tickCount,
};
}
function clamp(n: number): number {
return Math.min(100, Math.max(0, n));
}
@@ -0,0 +1,22 @@
import type { GameState, TalentState } from '@ai-tycoon/shared';
const SALARY_PER_HEADCOUNT_PER_TICK = 0.03;
export function processTalent(state: GameState): TalentState {
const departments = { ...state.talent.departments };
let totalSalary = 0;
for (const [id, dept] of Object.entries(departments)) {
totalSalary += dept.headcount * SALARY_PER_HEADCOUNT_PER_TICK;
totalSalary += dept.budget / 2592000;
}
for (const hire of state.talent.keyHires) {
totalSalary += hire.salary / 2592000;
}
return {
...state.talent,
totalSalaryPerTick: totalSalary,
};
}
+47 -5
View File
@@ -3,20 +3,56 @@ import { processEconomy } from './systems/economySystem';
import { processInfrastructure } from './systems/infrastructureSystem';
import { processCompute } from './systems/computeSystem';
import { processResearch } from './systems/researchSystem';
import { processModels } from './systems/modelSystem';
import { processMarket } from './systems/marketSystem';
import { processReputation } from './systems/reputationSystem';
import { processTalent } from './systems/talentSystem';
export interface TickResult {
state: Partial<GameState>;
notifications: TickNotification[];
}
export interface TickNotification {
title: string;
message: string;
type: 'info' | 'success' | 'warning' | 'danger';
}
export function processTick(state: GameState): Partial<GameState> {
const notifications: TickNotification[] = [];
const infrastructure = processInfrastructure(state);
const stateWithInfra = { ...state, infrastructure };
const modelResult = processModels(stateWithInfra);
if (modelResult.modelCompleted) {
notifications.push({
title: 'Training Complete',
message: `${modelResult.modelCompleted.name} is ready! Benchmark: ${modelResult.modelCompleted.benchmarkScore.toFixed(1)}/100`,
type: 'success',
});
}
const stateWithModels = { ...stateWithInfra, models: modelResult.modelsState };
const market = processMarket(stateWithModels, state.compute);
const compute = processCompute(state, infrastructure);
const research = processResearch(state, compute);
const market = processMarket(state, compute);
const reputation = processReputation(state);
const economy = processEconomy(state, market, infrastructure);
compute.tokensPerSecondDemand = market.totalTokenDemand;
compute.inferenceUtilization = compute.tokensPerSecondCapacity > 0
? Math.min(1, market.totalTokenDemand / compute.tokensPerSecondCapacity)
: 0;
const talent = processTalent(stateWithModels);
const stateWithTalent = { ...stateWithModels, talent };
const research = processResearch(stateWithTalent, compute);
const reputation = processReputation(stateWithTalent);
const economy = processEconomy(stateWithTalent, market, infrastructure);
const tickCount = state.meta.tickCount + 1;
return {
const result: Partial<GameState> = {
meta: {
...state.meta,
tickCount,
@@ -27,7 +63,13 @@ export function processTick(state: GameState): Partial<GameState> {
infrastructure,
compute,
research,
models: modelResult.modelsState,
market: market.marketState,
talent,
reputation,
};
(result as Record<string, unknown>)['_notifications'] = notifications;
return result;
}