Prompt specification
Build or customize the Three.js 3D scene "Limited-stock shop management game" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Limited-stock shop management game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/limited-stock-shop-management-game-x0536
Scene Description Prompt:
A voxel shop game with finite stock, scheduled demand, replenishment, empty shelves, and waiting carts. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (limited-stock-shop-management-game-x0536):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Block & Cart — Voxel Shop Game</title>
<style>
:root {
--ink: #24332d;
--muted: #66756f;
--paper: #fffdf7;
--line: #d7ded6;
--green: #397a59;
--green-dark: #28583f;
--yellow: #f5c84b;
--orange: #ed8c45;
--red: #d85d61;
--shadow: 0 14px 35px rgba(40, 58, 49, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
cursor: pointer;
}
#game, #game canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#game canvas {
display: block;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 45%, rgba(35, 56, 46, 0.08) 100%);
}
.topbar {
position: fixed;
z-index: 10;
top: 16px;
left: 18px;
right: 18px;
min-height: 68px;
display: flex;
align-items: center;
gap: 18px;
padding: 10px 14px 12px;
border: 2px solid rgba(255,255,255,.8);
border-radius: 18px;
background: rgba(255,253,247,.94);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand {
min-width: 185px;
display: flex;
align-items: center;
gap: 11px;
font-weight: 900;
letter-spacing: -.04em;
font-size: 21px;
}
.brand-mark {
width: 39px;
height: 39px;
position: relative;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
border-radius: 3px;
box-shadow: 0 3px 0 rgba(35,50,43,.12);
}
.brand-mark i:nth-child(1) {
width: 20px; height: 20px; left: 0; top: 0;
background: #5c9c6d;
}
.brand-mark i:nth-child(2) {
width: 20px; height: 20px; right: 0; bottom: 0;
background: #f2bd46;
}
.brand-mark i:nth-child(3) {
width: 13px; height: 13px; right: 1px; top: 2px;
background: #e76f51;
}
.brand small {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 9px;
letter-spacing: .18em;
font-weight: 800;
}
.metrics {
display: flex;
align-items: stretch;
justify-content: flex-end;
gap: 8px;
flex: 1;
}
.metric {
min-width: 88px;
padding: 7px 11px;
border-radius: 12px;
background: #f0f3ed;
border: 1px solid #e0e6df;
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: .12em;
}
.metric-value {
margin-top: 2px;
font-size: 18px;
line-height: 1;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.metric.alert .metric-value { color: var(--red); }
.goal-metric {
position: relative;
min-width: 155px;
overflow: hidden;
}
.goal-track {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 5px;
background: #dfe6df;
}
#goalFill {
height: 100%;
width: 0;
background: var(--green);
transition: width .25s ease;
}
.panel {
position: fixed;
z-index: 9;
top: 102px;
width: 286px;
padding: 16px;
border: 2px solid rgba(255,255,255,.9);
border-radius: 18px;
background: rgba(255,253,247,.95);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
#forecastPanel { left: 18px; }
#supplyPanel {
right: 18px;
width: 310px;
max-height: calc(100vh - 184px);
overflow: auto;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
}
.panel-title h2 {
margin: 0;
font-size: 14px;
letter-spacing: -.02em;
}
.eyebrow {
color: var(--green);
font-size: 9px;
font-weight: 900;
letter-spacing: .16em;
}
.clock-pill {
padding: 4px 7px;
border-radius: 999px;
color: var(--green-dark);
background: #e3eee5;
font-size: 10px;
font-weight: 900;
}
.next-wave {
padding: 14px;
border-radius: 14px;
color: #fff;
background: linear-gradient(135deg, #397a59, #28583f);
box-shadow: inset 0 0 0 1px rgba(255,255,255,.12);
}
.next-wave .caption {
color: #cde4d5;
font-size: 9px;
font-weight: 900;
letter-spacing: .14em;
}
.next-wave .countdown {
margin: 2px 0 7px;
font-size: 31px;
line-height: 1;
font-weight: 900;
letter-spacing: -.05em;
}
.next-wave .countdown span {
font-size: 12px;
letter-spacing: 0;
opacity: .75;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 5px 7px;
border-radius: 8px;
background: rgba(255,255,255,.15);
font-size: 10px;
font-weight: 800;
}
.chip-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--c);
box-shadow: inset 2px 2px 0 rgba(255,255,255,.3);
}
.forecast-list {
margin-top: 12px;
}
.forecast-row {
display: grid;
grid-template-columns: 42px 1fr;
gap: 9px;
align-items: center;
padding: 8px 2px;
border-bottom: 1px dashed #d9dfd8;
}
.forecast-row:last-child { border-bottom: 0; }
.forecast-time {
color: var(--muted);
font-size: 10px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.forecast-items {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.mini-item {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px 6px;
border-radius: 6px;
background: #edf1eb;
font-size: 9px;
font-weight: 800;
}
.mini-item i {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--c);
}
.panel-note {
margin-top: 11px;
padding: 9px 10px;
border-radius: 10px;
color: #6d654b;
background: #fff5cf;
font-size: 10px;
line-height: 1.45;
}
.supply-list {
display: grid;
gap: 9px;
}
.supply-row {
display: grid;
grid-template-columns: 38px 1fr 67px;
gap: 9px;
align-items: center;
padding: 10px;
border: 1px solid #e0e5de;
border-radius: 13px;
background: #f8f8f3;
transition: transform .15s, border-color .15s, background .15s;
cursor: pointer;
}
.supply-row:hover {
transform: translateY(-1px);
border-color: #bfcac0;
}
.supply-row.actionable {
border-color: var(--yellow);
background: #fff9de;
box-shadow: 0 0 0 2px rgba(245,200,75,.18);
}
.product-icon {
width: 36px;
height: 36px;
position: relative;
border-radius: 10px;
background: color-mix(in srgb, var(--c) 28%, white);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--c) 50%, white);
}
.product-icon::before,
.product-icon::after {
content: "";
position: absolute;
width: 14px;
height: 14px;
border-radius: 3px;
background: var(--c);
box-shadow: inset 3px 3px 0 rgba(255,255,255,.24), 0 3px 0 rgba(0,0,0,.08);
}
.product-icon::before { left: 6px; top: 6px; }
.product-icon::after { right: 5px; bottom: 5px; }
.supply-name {
display: flex;
justify-content: space-between;
gap: 5px;
font-size: 11px;
font-weight: 900;
}
.supply-name span {
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.stock-row {
display: flex;
align-items: center;
gap: 7px;
margin-top: 5px;
}
.stock-number {
min-width: 28px;
font-size: 10px;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.stock-bar {
height: 7px;
flex: 1;
overflow: hidden;
border-radius: 999px;
background: #e1e6df;
}
.stock-bar i {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--c);
transition: width .2s ease;
}
.supply-note {
min-height: 12px;
margin-top: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
}
.order-button {
padding: 8px 4px;
border: 0;
border-radius: 9px;
color: #fff;
background: var(--green);
line-height: 1.1;
}
.order-button strong,
.order-button small {
display: block;
}
.order-button strong { font-size: 9px; }
.order-button small { margin-top: 2px; opacity: .8; font-size: 8px; }
.order-button:hover:not(:disabled) { background: var(--green-dark); }
.order-button:disabled { opacity: .38; cursor: not-allowed; }
#hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 76px;
transform: translateX(-50%);
max-width: min(540px, calc(100vw - 40px));
padding: 10px 15px;
border-radius: 999px;
color: #fff;
background: rgba(36,51,45,.9);
box-shadow: 0 8px 24px rgba(35,50,43,.18);
font-size: 11px;
font-weight: 700;
text-align: center;
pointer-events: none;
}
#eventBar {
position: fixed;
z-index: 8;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
min-width: 340px;
max-width: calc(100vw - 330px);
padding: 11px 16px;
display: flex;
align-items: center;
gap: 10px;
border: 2px solid rgba(255,255,255,.85);
border-radius: 15px;
background: rgba(255,253,247,.95);
box-shadow: var(--shadow);
font-size: 11px;
}
.live-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(57,122,89,.13);
}
#controls {
position: fixed;
z-index: 9;
right: 18px;
bottom: 20px;
display: flex;
gap: 7px;
}
.control-button {
min-width: 48px;
height: 44px;
padding: 0 11px;
border: 2px solid rgba(255,255,255,.85);
border-radius: 12px;
color: var(--ink);
background: rgba(255,253,247,.95);
box-shadow: 0 8px 20px rgba(35,50,43,.12);
font-size: 10px;
font-weight: 900;
}
.control-button:hover { transform: translateY(-1px); }
#labels {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -100%);
white-space: nowrap;
padding: 5px 7px;
border: 2px solid rgba(255,255,255,.9);
border-radius: 8px;
color: #26352e;
background: rgba(255,253,247,.91);
box-shadow: 0 5px 12px rgba(30,47,39,.16);
font-size: 9px;
font-weight: 900;
letter-spacing: .02em;
will-change: transform, left, top;
}
.world-label .label-dot {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 4px;
border-radius: 2px;
background: var(--c);
box-shadow: inset 2px 2px 0 rgba(255,255,255,.3);
}
.world-label.cart-label {
color: #fff;
border-color: rgba(255,255,255,.75);
background: rgba(40,58,49,.94);
}
.world-label.selected {
color: #3c3517;
border-color: #f5c84b;
background: #fff0a8;
box-shadow: 0 0 0 3px rgba(245,200,75,.3);
}
.float-money {
position: fixed;
z-index: 15;
pointer-events: none;
color: #2d7a4c;
font-size: 21px;
font-weight: 1000;
text-shadow: 0 2px 0 white, 0 3px 8px rgba(0,0,0,.15);
animation: floatUp 1.15s ease-out forwards;
}
@keyframes floatUp {
from { opacity: 1; transform: translate(-50%, -50%) scale(.8); }
to { opacity: 0; transform: translate(-50%, -130%) scale(1.1); }
}
#toast {
position: fixed;
z-index: 30;
top: 96px;
left: 50%;
transform: translate(-50%, -15px);
max-width: 430px;
padding: 10px 16px;
border-radius: 12px;
color: #fff;
background: #263c32;
box-shadow: 0 10px 30px rgba(30,45,38,.25);
font-size: 11px;
font-weight: 800;
text-align: center;
opacity: 0;
pointer-events: none;
transition: opacity .2s, transform .2s;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.modal {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
padding: 24px;
background: rgba(32,49,41,.42);
backdrop-filter: blur(8px);
}
.modal.hidden { display: none; }
.modal-card {
width: min(530px, 100%);
padding: 28px;
border: 3px solid rgba(255,255,255,.92);
border-radius: 24px;
background: #fffdf7;
box-shadow: 0 28px 70px rgba(24,40,33,.28);
}
.modal-kicker {
color: var(--green);
font-size: 10px;
font-weight: 900;
letter-spacing: .2em;
}
.modal-card h1 {
margin: 7px 0 12px;
font-size: clamp(30px, 6vw, 48px);
line-height: .98;
letter-spacing: -.065em;
}
.modal-card p {
color: #5f6e67;
font-size: 13px;
line-height: 1.65;
}
.instructions {
display: grid;
gap: 9px;
margin: 20px 0;
}
.instruction {
display: grid;
grid-template-columns: 31px 1fr;
gap: 10px;
align-items: center;
padding: 10px;
border-radius: 11px;
background: #eef2eb;
font-size: 11px;
line-height: 1.4;
}
.instruction b {
display: grid;
place-items: center;
width: 29px;
height: 29px;
border-radius: 8px;
color: #fff;
background: var(--green);
}
.primary-button {
width: 100%;
padding: 14px 18px;
border: 0;
border-radius: 13px;
color: #fff;
background: var(--green);
box-shadow: 0 6px 0 var(--green-dark);
font-weight: 900;
letter-spacing: .04em;
}
.primary-button:hover { background: #438763; }
.primary-button:active { transform: translateY(4px); box-shadow: 0 2px 0 var(--green-dark); }
.result-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 9px;
margin: 20px 0;
}
.result-stat {
padding: 12px 8px;
border-radius: 11px;
background: #eef2eb;
text-align: center;
}
.result-stat strong {
display: block;
font-size: 22px;
}
.result-stat span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .08em;
}
@media (max-width: 1050px) {
.panel { width: 245px; }
#supplyPanel { width: 278px; }
.brand { min-width: 145px; }
.metric { min-width: 70px; padding: 7px 8px; }
.goal-metric { min-width: 125px; }
#eventBar { max-width: calc(100vw - 300px); }
}
@media (max-width: 760px) {
.topbar {
top: 8px;
left: 8px;
right: 8px;
padding: 8px;
gap: 7px;
}
.brand { min-width: 0; }
.brand > span { display: none; }
.brand-mark { width: 34px; height: 34px; transform: scale(.86); }
.metrics { gap: 4px; }
.metric { min-width: 0; padding: 6px; }
.metric-label { font-size: 7px; }
.metric-value { font-size: 13px; }
.metric:nth-child(3), .metric:nth-child(4) { display: none; }
.goal-metric { min-width: 92px; }
.panel {
top: 82px;
width: calc(50vw - 12px);
padding: 10px;
max-height: 38vh;
overflow: auto;
}
#forecastPanel { left: 8px; }
#supplyPanel { right: 8px; width: calc(50vw - 12px); }
.panel-title h2 { font-size: 11px; }
.next-wave { padding: 9px; }
.next-wave .countdown { font-size: 23px; }
.forecast-list, .panel-note { display: none; }
.supply-row {
grid-template-columns: 29px 1fr 55px;
gap: 5px;
padding: 7px;
}
.product-icon { width: 28px; height: 28px; }
.product-icon::before, .product-icon::after { transform: scale(.72); }
.supply-name { font-size: 9px; }
.supply-name span, .supply-note { display: none; }
.order-button { padding: 6px 2px; }
#hint { bottom: 70px; width: calc(100vw - 20px); border-radius: 11px; }
#eventBar {
left: 8px;
right: 144px;
bottom: 16px;
transform: none;
min-width: 0;
max-width: none;
padding: 10px;
font-size: 9px;
}
#controls { right: 8px; bottom: 16px; }
.control-button { min-width: 42px; height: 40px; padding: 0 8px; }
}
</style>
</head>
<body>
<div id="game"></div>
<div class="vignette"></div>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark"><i></i><i></i><i></i></div>
<span>BLOCK & CART<small>NEIGHBORHOOD MARKET</small></span>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">SHIFT</div>
<div class="metric-value" id="timeValue">4:00</div>
</div>
<div class="metric">
<div class="metric-label">CASH</div>
<div class="metric-value" id="cashValue">$180</div>
</div>
<div class="metric">
<div class="metric-label">FILLED</div>
<div class="metric-value" id="filledValue">0</div>
</div>
<div class="metric alert">
<div class="metric-label">MISSED</div>
<div class="metric-value" id="missedValue">0</div>
</div>
<div class="metric alert">
<div class="metric-label">WAITING</div>
<div class="metric-value" id="waitingValue">0</div>
</div>
<div class="metric goal-metric">
<div class="metric-label">DAILY GOAL</div>
<div class="metric-value" id="goalValue">$0 / $300</div>
<div class="goal-track"><div id="goalFill"></div></div>
</div>
</div>
</header>
<aside class="panel" id="forecastPanel">
<div class="panel-title">
<h2>Demand forecast</h2>
<span class="eyebrow">PUBLISHED</span>
</div>
<div class="next-wave">
<div class="caption">NEXT SHOPPING WAVE</div>
<div class="countdown" id="nextCount">0:10 <span>until arrival</span></div>
<div class="chips" id="nextItems"></div>
</div>
<div class="forecast-list" id="forecastList"></div>
<div class="panel-note">
Orders are finite. A scheduled truck needs lead time, so watch the forecast before stock runs out.
</div>
</aside>
<aside class="panel" id="supplyPanel">
<div class="panel-title">
<h2>Stock & supply</h2>
<span class="eyebrow">TRUCK DELIVERY</span>
</div>
<div class="supply-list" id="supplyList"></div>
</aside>
<div id="hint">Start the shift to begin receiving scheduled customers.</div>
<div id="eventBar">
<span class="live-dot"></span>
<span id="eventText">The shop is closed. Ready for opening time.</span>
</div>
<div id="controls">
<button class="control-button" id="pauseButton" title="Pause / resume">PAUSE</button>
<button class="control-button" id="speedButton" title="Change simulation speed">1×</button>
<button class="control-button" id="cameraButton" title="Reset camera">CAM</button>
</div>
<div id="toast"></div>
<div class="modal" id="modal">
<div class="modal-card">
<div class="modal-kicker" id="modalKicker">A FOUR-MINUTE VOXEL SHOP SIM</div>
<h1 id="modalTitle">Small shop.<br>Big schedule.</h1>
<p id="modalCopy">
Customers arrive on a published schedule, but your shelves are not infinite.
Keep the shelves stocked and make sure nobody leaves empty-handed.
</p>
<div class="instructions" id="instructions">
<div class="instruction">
<b>1</b>
<span><strong>Read the forecast.</strong> The next shopping wave and its products are always visible.</span>
</div>
<div class="instruction">
<b>2</b>
<span><strong>Order replenishment.</strong> Each truck order brings 10 units after a short lead time.</span>
</div>
<div class="instruction">
<b>3</b>
<span><strong>Help waiting carts.</strong> Click a cart, then click its matching shelf or inventory card.</span>
</div>
</div>
<div class="result-stats" id="resultStats" style="display:none">
<div class="result-stat"><strong id="resultEarned">$0</strong><span>TAKINGS</span></div>
<div class="result-stat"><strong id="resultFilled">0</strong><span>FILLED</span></div>
<div class="result-stat"><strong id="resultMissed">0</strong><span>MISSED</span></div>
</div>
<button class="primary-button" id="primaryButton">OPEN THE SHOP</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
Game data
--------------------------------------------------------------------------- */
const products = [
{ id: "bread", name: "Bread", short: "BREAD", color: "#dfa34f", price: 9, stock: 5, reserve: 0 },
{ id: "berry", name: "Berries", short: "BERRY", color: "#d95b79", price: 11, stock: 4, reserve: 0 },
{ id: "milk", name: "Milk", short: "MILK", color: "#e8eadf", price: 7, stock: 4, reserve: 0 },
{ id: "cheese", name: "Cheese", short: "CHEESE", color: "#efc73e", price: 12, stock: 3, reserve: 0 },
{ id: "coffee", name: "Coffee", short: "COFFEE", color: "#80553e", price: 10, stock: 4, reserve: 0 },
{ id: "avocado", name: "Avocado", short: "AVOCADO", color: "#78a84e", price: 14, stock: 3, reserve: 0 }
];
const productMap = Object.fromEntries(products.map(p => [p.id, p]));
const CAPACITY = 20;
const DAY_LENGTH = 240;
const QUOTA = 300;
const waves = [
{ t: 10, items: [["bread", 2], ["milk", 1]] },
{ t: 28, items: [["berry", 2], ["coffee", 1]] },
{ t: 46, items: [["bread", 2], ["avocado", 1]] },
{ t: 64, items: [["milk", 2], ["cheese", 1]] },
{ t: 82, items: [["coffee", 2], ["berry", 1]] },
{ t: 100, items: [["avocado", 2], ["milk", 1]] },
{ t: 118, items: [["bread", 2], ["berry", 1]] },
{ t: 136, items: [["cheese", 2], ["coffee", 1]] },
{ t: 154, items: [["milk", 2], ["avocado", 1]] },
{ t: 172, items: [["berry", 2], ["bread", 1]] },
{ t: 190, items: [["coffee", 2], ["cheese", 1]] },
{ t: 208, items: [["avocado", 2], ["bread", 1]] }
];
const state = {
started: false,
running: false,
paused: false,
speed: 1,
elapsed: 0,
cash: 180,
earned: 0,
served: 0,
missed: 0,
nextWave: 0,
carts: [],
cartSerial: 0,
selectedCart: null,
orders: [],
activeDelivery: null,
toastTimer: 0
};
const $ = id => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const easeOut = t => 1 - Math.pow(1 - t, 3);
function formatTime(seconds) {
seconds = Math.max(0, Math.ceil(seconds));
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
/* --------------------------------------------------------------------------
Three.js setup
--------------------------------------------------------------------------- */
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce8df");
scene.fog = new THREE.Fog("#dce8df", 38, 70);
const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
$("game").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight("#fff9e8", "#7e9a87", 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight("#fff4d5", 3.1);
sun.position.set(9, 18, 13);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -23;
sun.shadow.camera.right = 23;
sun.shadow.camera.top = 23;
sun.shadow.camera.bottom = -23;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.00035;
scene.add(sun);
const materialCache = new Map();
function material(color, options = {}) {
const key = `${color}-${JSON.stringify(options)}`;
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0,
...options
}));
}
return materialCache.get(key);
}
function box(w, h, d, color, x = 0, y = 0, z = 0, parent = scene, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
material(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinder(radius, height, color, x, y, z, parent = scene, segments = 12) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, height, segments),
material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTextTexture(text, bg = "#28583f", fg = "#fff9df", width = 1024, height = 256) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = fg;
ctx.font = "900 112px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, width / 2, height / 2 + 4);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
/* --------------------------------------------------------------------------
Shop geometry
--------------------------------------------------------------------------- */
const shelfItems = new Map();
const shelfIndicators = new Map();
const shelfLabels = [];
const pickables = [];
function buildShop() {
box(26.8, 0.6, 20.8, "#b8c8b9", 0, -0.45, 0);
const tileColors = ["#eee8d8", "#e9e2d0", "#f1ecdf", "#e4dfce"];
for (let ix = -6; ix <= 6; ix++) {
for (let iz = -5; iz <= 4; iz++) {
const color = tileColors[(ix * 3 + iz * 5 + 20) % tileColors.length];
box(1.96, 0.08, 1.96, color, ix * 2, -0.1, iz * 2, scene, { roughness: 1 });
}
}
// Back and left walls.
box(26.5, 5.3, 0.45, "#f1e8d4", 0, 2.55, -9.75);
box(0.45, 5.3, 20.3, "#e7ddc8", -13.25, 2.55, 0);
box(26.6, 0.25, 0.65, "#84a88d", 0, 0.05, -9.45);
box(0.65, 0.25, 20.4, "#84a88d", -13.05, 0.05, 0);
// Decorative wall tiles and windows.
for (let i = -5; i <= 5; i++) {
box(1.65, 1.2, 0.08, "#dfe8d9", i * 2.2, 3.55, -9.48);
}
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(7.2, 1.55),
new THREE.MeshBasicMaterial({ map: makeTextTexture("BLOCK & CART") })
);
sign.position.set(0, 4.2, -9.42);
scene.add(sign);
// Checkout counter.
box(12.8, 1.25, 1.65, "#b47b4e", -2.4, 0.57, 7.25);
box(13.1, 0.18, 1.88, "#f2d69d", -2.4, 1.28, 7.25);
box(1.35, 0.8, 1.05, "#3e5c50", -6.3, 1.77, 7.2);
box(1.0, 0.5, 0.08, "#91d2bb", -6.3, 1.85, 7.76);
box(0.7, 0.18, 0.65, "#e85f51", -3.7, 1.47, 7.25);
box(0.62, 0.16, 0.55, "#f5c84b", -1.8, 1.45, 7.2);
// Entrance mat.
box(2.8, 0.1, 1.7, "#527b65", 11.1, 0.02, 7.3);
box(2.3, 0.03, 0.15, "#e7d991", 11.1, 0.08, 7.3);
// Produce display on the counter.
for (let i = 0; i < 3; i++) {
box(1.25, 0.25, 1.05, "#9e7048", 0.1 + i * 1.35, 1.45, 7.2);
for (let j = 0; j < 4; j++) {
box(0.26, 0.23, 0.26,
["#d85d61", "#e9a84e", "#79a74e"][i],
-0.25 + j * 0.28, 1.68, 7.2
);
}
}
// Voxel plant.
box(0.9, 0.8, 0.9, "#d47c56", -11.3, 0.35, 6.4);
box(0.18, 2.3, 0.18, "#547849", -11.3, 1.55, 6.4);
box(1.5, 0.75, 0.75, "#5c914e", -11.6, 2.25, 6.35);
box(1.05, 0.9, 0.7, "#73a95b", -10.85, 2.8, 6.4);
box(0.85, 0.65, 0.65, "#4f8248", -11.4, 3.25, 6.4);
// Wall clock.
const clockFace = cylinder(0.62, 0.12, "#f9f2df", -10.5, 3.65, -9.35);
clockFace.rotation.x = Math.PI / 2;
box(0.08, 0.4, 0.08, "#34463d", -10.5, 3.73, -9.23);
box(0.32, 0.08, 0.08, "#34463d", -10.35, 3.65, -9.22);
// Road and loading strip on the open right side.
box(3.5, 0.1, 21, "#7d8982", 15.3, -0.02, 0);
for (let z = -9; z <= 9; z += 3) {
box(0.12, 0.03, 1.5, "#e7dca7", 15.3, 0.05, z);
}
}
function buildShelves() {
const xs = [-8.75, -5.25, -1.75, 1.75, 5.25, 8.75];
products.forEach((product, index) => {
const x = xs[index];
const group = new THREE.Group();
group.position.set(x, 0, -7.25);
scene.add(group);
// Shelf carcass.
box(2.75, 2.8, 0.18, "#9f704b", 0, 1.45, -0.72, group);
box(0.16, 2.85, 1.55, "#b67e50", -1.36, 1.45, 0, group);
box(0.16, 2.85, 1.55, "#b67e50", 1.36, 1.45, 0, group);
[0.42, 1.18, 1.94, 2.7].forEach(y => {
box(2.8, 0.12, 1.58, "#d4a66f", 0, y, 0, group);
});
const indicator = box(
2.4, 0.28, 0.09, product.color, 0, 2.92, 0.72, group,
{ emissive: product.color, emissiveIntensity: 0.04 }
);
shelfIndicators.set(product.id, indicator);
const items = [];
let itemIndex = 0;
for (let level = 0; level < 3; level++) {
for (let row = 0; row < 2; row++) {
for (let col = 0; col < 4; col++) {
if (itemIndex >= 20) break;
const item = box(
0.48, 0.46, 0.48,
product.color,
-0.93 + col * 0.62,
0.76 + level * 0.76,
row === 0 ? 0.28 : -0.3,
group,
{ roughness: product.id === "milk" ? 0.45 : 0.8 }
);
// Tiny product-specific voxel details.
if (product.id === "bread") {
box(0.32, 0.035, 0.5, "#f0c579", item.position.x, item.position.y + 0.245, item.position.z, group);
} else if (product.id === "berry") {
box(0.16, 0.15, 0.16, "#f07891", item.position.x, item.position.y + 0.29, item.position.z, group);
} else if (product.id === "milk") {
box(0.27, 0.08, 0.27, "#8fc8b4", item.position.x, item.position.y + 0.27, item.position.z, group);
} else if (product.id === "cheese") {
box(0.2, 0.1, 0.2, "#f6dc66", item.position.x, item.position.y + 0.27, item.position.z, group);
} else if (product.id === "coffee") {
box(0.36, 0.07, 0.36, "#4e352b", item.position.x, item.position.y + 0.26, item.position.z, group);
} else if (product.id === "avocado") {
box(0.16, 0.2, 0.16, "#426f3d", item.position.x, item.position.y + 0.31, item.position.z, group);
}
items.push(item);
itemIndex++;
}
}
}
shelfItems.set(product.id, items);
const hitbox = new THREE.Mesh(
new THREE.BoxGeometry(2.85, 3.1, 1.7),
new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, colorWrite: false })
);
hitbox.position.set(x, 1.45, -7.2);
hitbox.userData.pid = product.id;
scene.add(hitbox);
pickables.push(hitbox);
const label = document.createElement("div");
label.className = "world-label shelf-label";
label.innerHTML = `<span class="label-dot" style="--c:${product.color}"></span>${product.short} <b>${product.stock}</b>`;
$("labels").appendChild(label);
shelfLabels.push({ element: label, product, position: new THREE.Vector3(x, 3.35, -6.85) });
});
}
function buildTruck() {
const truck = new THREE.Group();
truck.position.set(15.3, 0, -8);
scene.add(truck);
box(2.2, 1.55, 3.1, "#f7f1de", 0, 1.12, -0.35, truck);
box(2.15, 1.45, 1.15, "#e9894e", 0, 1.0, 1.5, truck);
box(1.72, 0.62, 0.06, "#8cc2c8", 0, 1.35, 2.09, truck, { roughness: 0.3 });
box(2.35, 0.16, 4.1, "#6f8c7b", 0, 1.97, 0.25, truck);
[-1.08, 1.08].forEach(x => {
[-1.2, 1.35].forEach(z => {
const wheel = cylinder(0.42, 0.3, "#303b36", x, 0.45, z, truck);
wheel.rotation.z = Math.PI / 2;
});
});
box(1.25, 0.12, 1.3, "#d4a66f", 0, 2.13, -0.45, truck);
box(1.05, 0.65, 1.0, "#efc773", 0, 2.52, -0.45, truck);
box(0.08, 0.08, 0.08, "#e76f51", 0, 2.95, -0.45, truck);
truck.visible = false;
return truck;
}
buildShop();
buildShelves();
const truck = buildTruck();
/* --------------------------------------------------------------------------
Inventory UI
--------------------------------------------------------------------------- */
const supplyRows = new Map();
products.forEach(product => {
const row = document.createElement("div");
row.className = "supply-row";
row.dataset.pid = product.id;
row.innerHTML = `
<div class="product-icon" style="--c:${product.color}"></div>
<div>
<div class="supply-name">${product.name}<span>$${product.price}</span></div>
<div class="stock-row">
<span class="stock-number">${product.stock}/${CAPACITY}</span>
<div class="stock-bar"><i style="--c:${product.color}"></i></div>
</div>
<div class="supply-note"></div>
</div>
<button class="order-button" type="button">
<strong>ORDER 10</strong>
<small>$${Math.round(product.price * 0.6 * 10)}</small>
</button>
`;
row.addEventListener("click", event => {
if (event.target.closest("button")) return;
handleInventoryClick(product.id);
});
row.querySelector("button").addEventListener("click", event => {
event.stopPropagation();
placeOrder(product.id);
});
$("supplyList").appendChild(row);
supplyRows.set(product.id, {
row,
count: row.querySelector(".stock-number"),
bar: row.querySelector(".stock-bar i"),
note: row.querySelector(".supply-note"),
button: row.querySelector("button")
});
});
function refreshStockVisuals() {
for (const product of products) {
const items = shelfItems.get(product.id);
items.forEach((item, index) => item.visible = index < product.stock);
const label = shelfLabels.find(s => s.product.id === product.id);
if (label) {
label.element.innerHTML =
`<span class="label-dot" style="--c:${product.color}"></span>${product.short} <b>${product.stock}</b>`;
}
}
}
/* --------------------------------------------------------------------------
Orders and truck delivery
--------------------------------------------------------------------------- */
function placeOrder(pid) {
if (!state.started) return;
const product = productMap[pid];
const pending = state.orders.filter(order => order.pid === pid);
const cost = Math.round(product.price * 0.6 * 10);
if (pending.length >= 2) {
toast(`You already have two ${product.name.toLowerCase()} deliveries in the queue.`);
return;
}
if (state.cash < cost) {
toast(`Not enough cash. This delivery costs $${cost}.`);
return;
}
state.cash -= cost;
const due = state.elapsed + 16 + state.orders.length * 3;
state.orders.push({
pid,
qty: 10,
due,
status: "pending"
});
toast(`${product.name} ordered · 10 units arriving in ${Math.max(1, Math.ceil(due - state.elapsed))}s.`);
updateUI();
}
function updateDeliveries() {
if (!state.activeDelivery) {
const next = state.orders.find(order => order.status === "pending" && order.due <= state.elapsed);
if (next) {
next.status = "active";
state.activeDelivery = { order: next, start: state.elapsed };
truck.visible = true;
}
}
if (!state.activeDelivery) return;
const delivery = state.activeDelivery;
const progress = clamp((state.elapsed - delivery.start) / 4, 0, 1);
const travel = clamp(progress / 0.72, 0, 1);
truck.position.z = lerp(-8, 2.4, easeOut(travel));
truck.position.x = 15.3 + Math.sin(travel * Math.PI) * 0.25;
truck.rotation.y = Math.sin(travel * Math.PI) * 0.025;
if (progress >= 1) {
const product = productMap[delivery.order.pid];
const space = Math.max(0, CAPACITY - product.stock);
const delivered = Math.min(space, delivery.order.qty);
product.stock += delivered;
product.reserve += delivery.order.qty - delivered;
state.orders = state.orders.filter(order => order !== delivery.order);
state.activeDelivery = null;
truck.visible = false;
refreshStockVisuals();
toast(`${product.name} delivery unloaded · +${delivered} on shelf${product.reserve ? ` · ${product.reserve} in back stock` : ""}.`);
updateUI();
}
}
/* --------------------------------------------------------------------------
Customers and carts
--------------------------------------------------------------------------- */
const cartSlots = [];
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 5; col++) {
cartSlots.push(new THREE.Vector3(-8 + col * 4, 0, -0.1 + row * 2.35));
}
}
function createCartMesh(pid) {
const product = productMap[pid];
const group = new THREE.Group();
scene.add(group);
// Shopping cart basket.
box(0.95, 0.12, 1.0, "#8ea79c", 0, 0.58, 0.35, group);
box(0.95, 0.11, 0.1, "#6f8d81", 0, 1.34, 0.78, group);
box(0.95, 0.11, 0.1, "#6f8d81", 0, 1.34, -0.08, group);
box(0.1, 0.8, 0.1, "#6f8d81", -0.43, 0.96, 0.78, group);
box(0.1, 0.8, 0.1, "#6f8d81", 0.43, 0.96, 0.78, group);
box(0.1, 0.8, 0.1, "#6f8d81", -0.43, 0.96, -0.08, group);
box(0.1, 0.8, 0.1, "#6f8d81", 0.43, 0.96, -0.08, group);
box(0.9, 0.08, 0.08, "#89a397", 0, 0.98, 0.78, group);
box(0.9, 0.08, 0.08, "#89a397", 0, 0.98, -0.08, group);
[-0.4, 0.4].forEach(x => {
[-0.02, 0.72].forEach(z => {
const wheel = cylinder(0.15, 0.12, "#3a4841", x, 0.17, z, group);
wheel.rotation.z = Math.PI / 2;
});
});
// Voxel shopper.
const shirtColors = ["#5c8db2", "#d16f5c", "#8b74a8", "#d99d42", "#4e9a86"];
const shirt = shirtColors[state.cartSerial % shirtColors.length];
box(0.72, 0.9, 0.58, shirt, 0, 1.33, -0.63, group);
box(0.58, 0.58, 0.56, "#e4ae83", 0, 2.05, -0.63, group);
box(0.64, 0.24, 0.62, product.color, 0, 2.3, -0.63, group);
box(0.18, 0.7, 0.2, "#e4ae83", -0.49, 1.35, -0.48, group);
box(0.18, 0.7, 0.2, "#e4ae83", 0.49, 1.35, -0.48, group);
box(0.24, 0.65, 0.25, "#43536a", -0.2, 0.52, -0.62, group);
box(0.24, 0.65, 0.25, "#43536a", 0.2, 0.52, -0.62, group);
// Selection outline, built from four voxel bars.
const ring = new THREE.Group();
box(1.25, 0.035, 0.08, "#f5c84b", 0, 0.035, 0.65, ring);
box(1.25, 0.035, 0.08, "#f5c84b", 0, 0.035, -0.65, ring);
box(0.08, 0.035, 1.3, "#f5c84b", -0.63, 0.035, 0, ring);
box(0.08, 0.035, 1.3, "#f5c84b", 0.63, 0.035, 0, ring);
ring.visible = false;
group.add(ring);
const hitbox = new THREE.Mesh(
new THREE.BoxGeometry(1.45, 2.6, 1.6),
new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, colorWrite: false })
);
hitbox.position.y = 1.25;
hitbox.userData.cartId = null;
group.add(hitbox);
pickables.push(hitbox);
const label = document.createElement("div");
label.className = "world-label cart-label";
$("labels").appendChild(label);
return { group, ring, hitbox, label };
}
function spawnWave(wave) {
wave.items.forEach(([pid, qty]) => {
const id = ++state.cartSerial;
const model = createCartMesh(pid);
const slot = cartSlots[(id - 1) % cartSlots.length].clone();
model.group.position.set(12, 0, 7.1);
model.hitbox.userData.cartId = id;
const cart = {
id,
pid,
qty,
...model,
target: slot,
spawnAt: state.elapsed,
arrivedAt: null,
leaveStart: null,
phase: "arriving",
patience: 55
};
state.carts.push(cart);
updateCartLabel(cart);
});
toast(`Shopping wave arrived · ${wave.items.map(([pid, qty]) => `${qty} ${productMap[pid].name}`).join(", ")}.`);
}
function updateCartLabel(cart) {
const product = productMap[cart.pid];
cart.label.innerHTML =
`<span class="label-dot" style="--c:${product.color}"></span>${product.short} ×${cart.qty}`;
cart.label.classList.toggle("selected", state.selectedCart === cart.id);
}
function autoFulfill(cart) {
const product = productMap[cart.pid];
const amount = Math.min(product.stock, cart.qty);
if (amount > 0) {
product.stock -= amount;
cart.qty -= amount;
state.earned += amount * product.price;
state.served += amount;
refreshStockVisuals();
const pos = cart.group.position.clone();
pos.y = 2.5;
floatingMoney(`+$${amount * product.price}`, pos);
}
if (cart.qty <= 0) {
completeCart(cart);
}
}
function completeCart(cart) {
if (cart.phase === "leaving") return;
cart.phase = "leaving";
cart.leaveStart = state.elapsed;
cart.ring.visible = false;
if (state.selectedCart === cart.id) {
state.selectedCart = null;
}
}
function selectCart(cart) {
if (!cart || cart.phase !== "waiting") return;
state.selectedCart = state.selectedCart === cart.id ? null : cart.id;
for (const item of state.carts) {
item.ring.visible = item.id === state.selectedCart;
updateCartLabel(item);
}
if (state.selectedCart) {
const product = productMap[cart.pid];
toast(`${product.name} cart selected. Click a matching shelf or stock card to hand over one unit.`);
}
updateUI();
}
function fulfillSelected(pid) {
const cart = state.carts.find(item => item.id === state.selectedCart);
if (!cart || cart.phase !== "waiting") {
toast("Select a waiting cart first.");
return;
}
if (cart.pid !== pid) {
toast(`This cart needs ${productMap[cart.pid].name.toLowerCase()}, not ${productMap[pid].name.toLowerCase()}.`);
return;
}
const product = productMap[pid];
if (product.stock <= 0) {
toast(`${product.name} is out of stock. Order a truck delivery.`);
return;
}
product.stock--;
cart.qty--;
state.earned += product.price;
state.served++;
refreshStockVisuals();
updateCartLabel(cart);
const pos = cart.group.position.clone();
pos.y = 2.5;
floatingMoney(`+$${product.price}`, pos);
if (cart.qty <= 0) completeCart(cart);
updateUI();
}
function handleInventoryClick(pid) {
if (state.selectedCart) {
fulfillSelected(pid);
return;
}
const product = productMap[pid];
if (product.reserve > 0 && product.stock < CAPACITY) {
const amount = Math.min(product.reserve, CAPACITY - product.stock);
product.reserve -= amount;
product.stock += amount;
refreshStockVisuals();
toast(`${amount} ${product.name.toLowerCase()} moved from back stock to the shelf.`);
} else {
toast(`${product.name}: ${product.stock} on the shelf. Use ORDER 10 for replenishment.`);
}
}
function updateCarts() {
const toRemove = [];
for (const cart of state.carts) {
if (cart.phase === "arriving") {
const progress = clamp((state.elapsed - cart.spawnAt) / 1.25, 0, 1);
cart.group.position.x = lerp(12, cart.target.x, easeOut(progress));
cart.group.position.z = lerp(7.1, cart.target.z, easeOut(progress));
cart.group.rotation.y = lerp(-0.25, 0, easeOut(progress));
if (progress >= 1) {
cart.phase = "waiting";
cart.arrivedAt = state.elapsed;
autoFulfill(cart);
}
} else if (cart.phase === "waiting") {
const age = state.elapsed - cart.arrivedAt;
const urgency = clamp(1 - age / cart.patience, 0, 1);
cart.group.position.y = Math.sin(state.elapsed * 2.4 + cart.id) * 0.025;
cart.label.style.borderColor = urgency < 0.25 ? "#e56c61" : "";
if (age > cart.patience) {
state.missed += cart.qty;
toast(`A ${productMap[cart.pid].name.toLowerCase()} shopper left empty-handed.`);
completeCart(cart);
}
} else if (cart.phase === "leaving") {
const progress = clamp((state.elapsed - cart.leaveStart) / 1.65, 0, 1);
const eased = easeOut(progress);
cart.group.position.x = lerp(cart.target.x, 13.2, eased);
cart.group.position.z = lerp(cart.target.z, 8.3, eased);
cart.group.rotation.y = eased * 0.28;
cart.label.style.opacity = String(1 - progress);
if (progress >= 1) toRemove.push(cart);
}
}
for (const cart of toRemove) {
scene.remove(cart.group);
cart.label.remove();
const pickIndex = pickables.indexOf(cart.hitbox);
if (pickIndex >= 0) pickables.splice(pickIndex, 1);
state.carts = state.carts.filter(item => item !== cart);
}
}
/* --------------------------------------------------------------------------
Picking and direct camera controls
--------------------------------------------------------------------------- */
const cameraState = {
target: new THREE.Vector3(0, 0.6, -0.3),
radius: 30,
phi: 0.94,
theta: 0.72
};
function resetCamera() {
cameraState.radius = 30;
cameraState.phi = 0.94;
cameraState.theta = 0.72;
}
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let pointerStart = { x: 0, y: 0 };
let dragDistance = 0;
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerStart = { x: event.clientX, y: event.clientY };
dragDistance = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - pointerStart.x;
const dy = event.clientY - pointerStart.y;
dragDistance = Math.max(dragDistance, Math.hypot(dx, dy));
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi - dy * 0.004, 0.62, 1.2);
pointerStart = { x: event.clientX, y: event.clientY };
} else {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(pickables, false)[0];
renderer.domElement.style.cursor = hit ? "pointer" : "grab";
}
});
renderer.domElement.addEventListener("pointerup", event => {
pointerDown = false;
if (dragDistance > 6) return;
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
if (!intersections.length) return;
const object = intersections[0].object;
if (object.userData.cartId != null) {
const cart = state.carts.find(item => item.id === object.userData.cartId);
selectCart(cart);
} else if (object.userData.pid) {
if (state.selectedCart) {
fulfillSelected(object.userData.pid);
} else {
const product = productMap[object.userData.pid];
toast(`${product.name}: ${product.stock} on the shelf. Click a waiting cart to serve it.`);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => pointerDown = false);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(cameraState.radius + event.deltaY * 0.018, 20, 42);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
/* --------------------------------------------------------------------------
UI updates, feedback, and game flow
--------------------------------------------------------------------------- */
function toast(message) {
$("toast").textContent = message;
$("toast").classList.add("show");
clearTimeout(state.toastTimer);
state.toastTimer = setTimeout(() => $("toast").classList.remove("show"), 2600);
}
function floatingMoney(text, worldPosition) {
const projected = worldPosition.clone().project(camera);
if (projected.z < -1 || projected.z > 1) return;
const element = document.createElement("div");
element.className = "float-money";
element.textContent = text;
element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
document.body.appendChild(element);
setTimeout(() => element.remove(), 1200);
}
function updateForecastUI() {
const next = waves[state.nextWave];
if (next) {
const seconds = Math.max(0, Math.ceil(next.t - state.elapsed));
$("nextCount").innerHTML = `${formatTime(seconds)} <span>until arrival</span>`;
$("nextItems").innerHTML = next.items.map(([pid, qty]) => `
<span class="chip">
<i class="chip-dot" style="--c:${productMap[pid].color}"></i>
${qty} ${productMap[pid].name}
</span>
`).join("");
} else {
$("nextCount").innerHTML = `Done <span>for today's schedule</span>`;
$("nextItems").innerHTML = "";
}
$("forecastList").innerHTML = waves.slice(state.nextWave, state.nextWave + 5).map(wave => `
<div class="forecast-row">
<div class="forecast-time">${formatTime(wave.t)}</div>
<div class="forecast-items">
${wave.items.map(([pid, qty]) => `
<span class="mini-item" style="--c:${productMap[pid].color}">
<i></i>${qty} ${productMap[pid].name}
</span>
`).join("")}
</div>
</div>
`).join("");
}
function updateSupplyUI() {
for (const product of products) {
const ui = supplyRows.get(product.id);
const pending = state.orders.filter(order => order.pid === product.id);
const active = state.activeDelivery?.order.pid === product.id;
const matchingCart = state.carts.find(cart =>
cart.id === state.selectedCart && cart.pid === product.id
);
ui.count.textContent = `${product.stock}/${CAPACITY}`;
ui.bar.style.width = `${product.stock / CAPACITY * 100}%`;
ui.row.classList.toggle("actionable", Boolean(matchingCart));
const cost = Math.round(product.price * 0.6 * 10);
ui.button.disabled = pending.length >= 2 || state.cash < cost || !state.running;
if (active) {
ui.note.textContent = "TRUCK UNLOADING";
} else if (pending.length) {
const due = Math.min(...pending.map(order => order.due));
ui.note.textContent = `TRUCK ETA ${Math.max(0, Math.ceil(due - state.elapsed))}s`;
} else if (product.reserve > 0) {
ui.note.textContent = `${product.reserve} IN BACK STOCK`;
} else {
ui.note.textContent = matchingCart ? "CLICK TO SERVE" : "SHELF STOCK";
}
}
}
function updateUI() {
const waiting = state.carts.filter(cart => cart.phase === "waiting").length;
$("timeValue").textContent = formatTime(DAY_LENGTH - state.elapsed);
$("cashValue").textContent = `$${state.cash}`;
$("filledValue").textContent = state.served;
$("missedValue").textContent = state.missed;
$("waitingValue").textContent = waiting;
$("goalValue").textContent = `$${state.earned} / $${QUOTA}`;
$("goalFill").style.width = `${Math.min(100, state.earned / QUOTA * 100)}%`;
$("pauseButton").textContent = state.paused ? "PLAY" : "PAUSE";
$("speedButton").textContent = `${state.speed}×`;
updateForecastUI();
updateSupplyUI();
const selected = state.carts.find(cart => cart.id === state.selectedCart);
if (selected) {
$("hint").textContent = `Serving ${productMap[selected.pid].name}: click its shelf or stock card to hand over one unit.`;
$("eventText").textContent = `${productMap[selected.pid].name} cart selected · ${selected.qty} unit${selected.qty === 1 ? "" : "s"} remaining.`;
} else if (waiting > 0) {
$("hint").textContent = `${waiting} cart${waiting === 1 ? " is" : "s are"} waiting. Click a cart, then its matching shelf or inventory card.`;
$("eventText").textContent = `${waiting} waiting cart${waiting === 1 ? "" : "s"} · Keep serving before patience runs out.`;
} else if (state.orders.length) {
const pending = state.orders.filter(order => order.status === "pending");
const eta = pending.length ? Math.max(0, Math.ceil(Math.min(...pending.map(order => order.due)) - state.elapsed)) : 0;
$("hint").textContent = `A replenishment truck is ${eta > 0 ? `${eta}s away` : "arriving"}. You can order more stock while it drives.`;
$("eventText").textContent = `Replenishment scheduled · ${pending.length + (state.activeDelivery ? 1 : 0)} truck load${pending.length + (state.activeDelivery ? 1 : 0) === 1 ? "" : "s"} in transit.`;
} else {
$("hint").textContent = "Read the demand forecast and order stock before the next wave arrives.";
$("eventText").textContent = "The next shopping wave is approaching.";
}
}
function startGame() {
if (state.started) return;
state.started = true;
state.running = true;
$("modal").classList.add("hidden");
toast("Shop open! Review the forecast and order before the first wave.");
updateUI();
}
function endGame() {
if (!state.running) return;
state.running = false;
state.paused = false;
const passed = state.earned >= QUOTA;
const grade = passed
? (state.missed === 0 ? "A+" : state.missed < 4 ? "A" : "B")
: (state.earned >= QUOTA * 0.75 ? "C" : "D");
$("modalKicker").textContent = passed ? "SHIFT COMPLETE · GOAL MET" : "SHIFT COMPLETE · GOAL MISSED";
$("modalTitle").innerHTML = passed
? "Shelves cleared.<br>Nice work!"
: "The bell rang.<br>Try another shift.";
$("modalCopy").textContent = passed
? `You earned $${state.earned} and filled ${state.served} units. Final grade: ${grade}.`
: `You earned $${state.earned} of the $${QUOTA} goal and filled ${state.served} units. Final grade: ${grade}.`;
$("instructions").style.display = "none";
$("resultStats").style.display = "grid";
$("resultEarned").textContent = `$${state.earned}`;
$("resultFilled").textContent = state.served;
$("resultMissed").textContent = state.missed;
$("primaryButton").textContent = "RUN ANOTHER SHIFT";
$("modal").classList.remove("hidden");
}
$("primaryButton").addEventListener("click", () => {
if (state.started) location.reload();
else startGame();
});
$("pauseButton").addEventListener("click", () => {
if (!state.running) return;
state.paused = !state.paused;
updateUI();
});
$("speedButton").addEventListener("click", () => {
state.speed = state.speed === 1 ? 2 : state.speed === 2 ? 3 : 1;
updateUI();
});
$("cameraButton").addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.code === "Space" && state.running) {
event.preventDefault();
state.paused = !state.paused;
updateUI();
}
if (event.key === "r" || event.key === "R") resetCamera();
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
/* --------------------------------------------------------------------------
Labels and main loop
--------------------------------------------------------------------------- */
const projected = new THREE.Vector3();
function positionWorldLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
if (projected.z < -1 || projected.z > 1 ||
projected.x < -1.15 || projected.x > 1.15 ||
projected.y < -1.15 || projected.y > 1.15) {
element.style.opacity = "0";
return;
}
element.style.opacity = "1";
element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
function updateLabels() {
for (const shelf of shelfLabels) {
positionWorldLabel(shelf.element, shelf.position);
}
for (const cart of state.carts) {
const position = cart.group.position.clone();
position.y += 2.9;
positionWorldLabel(cart.label, position);
}
}
let lastTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const rawDelta = Math.min(0.05, (now - lastTime) / 1000);
lastTime = now;
const simulationDelta = state.running && !state.paused ? rawDelta * state.speed : 0;
if (simulationDelta > 0) {
state.elapsed += simulationDelta;
while (state.nextWave < waves.length && state.elapsed >= waves[state.nextWave].t) {
spawnWave(waves[state.nextWave]);
state.nextWave++;
}
updateCarts();
updateDeliveries();
if (state.elapsed >= DAY_LENGTH) {
state.elapsed = DAY_LENGTH;
endGame();
}
}
updateCamera();
updateLabels();
renderer.render(scene, camera);
uiAccumulator += rawDelta;
if (uiAccumulator > 0.15) {
uiAccumulator = 0;
if (state.running) updateUI();
}
}
refreshStockVisuals();
updateCamera();
updateUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```