Prompt specification
Build or customize the Three.js 3D scene "Cooperative Orchard Turn 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: Cooperative Orchard Turn Game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/cooperative-orchard-turn-game-x3591
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring turn order and competing simultaneous moves. Build an original orchard board with harvest, carry, and refill actions. Use deterministic turn rules and show how coordinated order avoids wasted moves. Voxel style.
Working Three.js Starter (cooperative-orchard-turn-game-x3591):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orchard Protocol — Voxel Turn Coordinator</title>
<style>
:root {
--ink: #27342f;
--muted: #6d776f;
--paper: #f4efe3;
--paper-2: #ebe3d2;
--line: #c9bea9;
--poppy: #e66d52;
--moss: #3f9b83;
--gold: #e2ae45;
--danger: #c94f46;
--success: #3c916d;
--shadow: 0 12px 30px rgba(54, 48, 34, .14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e7dfce;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 11px 15px;
border: 1px solid rgba(255,255,255,.62);
border-radius: 14px;
background: rgba(247, 242, 231, .91);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
pointer-events: auto;
}
.brand-mark {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 8px;
background: var(--poppy);
color: #fff8e9;
font-weight: 900;
transform: rotate(-4deg);
}
.brand h1 {
margin: 0;
font-size: 15px;
letter-spacing: .08em;
text-transform: uppercase;
}
.brand small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
letter-spacing: .15em;
text-transform: uppercase;
}
.round-box {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border-radius: 12px;
background: rgba(39,52,47,.9);
color: #fff8e9;
box-shadow: var(--shadow);
pointer-events: auto;
}
.round-box span {
color: #bfc8c0;
font-size: 10px;
letter-spacing: .12em;
text-transform: uppercase;
}
.round-box strong {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 14px;
}
.panel {
position: fixed;
z-index: 8;
top: 88px;
width: 310px;
max-height: calc(100vh - 215px);
overflow: auto;
padding: 16px;
border: 1px solid rgba(255,255,255,.64);
border-radius: 17px;
background: rgba(247, 242, 231, .93);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
scrollbar-width: thin;
scrollbar-color: #b7ad99 transparent;
}
.panel.left { left: 20px; }
.panel.right { right: 20px; width: 272px; }
.eyebrow {
margin: 0 0 7px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .16em;
text-transform: uppercase;
}
h2 {
margin: 0;
font-size: 22px;
line-height: 1.05;
letter-spacing: -.035em;
}
.intro {
margin: 9px 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.section {
margin-top: 15px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
font-size: 10px;
font-weight: 850;
letter-spacing: .13em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-weight: 700;
letter-spacing: .05em;
text-transform: none;
}
.scenario-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.scenario {
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: #faf6ed;
text-align: left;
transition: .18s ease;
}
.scenario:hover,
.scenario.active {
border-color: var(--ink);
transform: translateY(-1px);
box-shadow: 0 5px 12px rgba(54,48,34,.08);
}
.scenario strong {
display: block;
font-size: 11px;
}
.scenario span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
#orderList {
display: grid;
gap: 8px;
}
.worker-card {
display: grid;
grid-template-columns: 28px 34px 1fr auto;
gap: 8px;
align-items: center;
padding: 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,.42);
cursor: pointer;
transition: .16s ease;
}
.worker-card:hover { border-color: #9e947f; }
.worker-card.selected {
border-color: var(--ink);
background: rgba(255,255,255,.72);
box-shadow: inset 3px 0 0 var(--worker-color);
}
.rank {
display: grid;
place-items: center;
width: 26px;
height: 26px;
border-radius: 7px;
background: var(--ink);
color: #fff8e9;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 800;
}
.avatar {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 8px;
background: var(--worker-color);
color: white;
font-size: 12px;
font-weight: 900;
}
.worker-main { min-width: 0; }
.worker-name {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 5px;
font-size: 11px;
font-weight: 800;
}
.worker-name small {
color: var(--muted);
font-size: 8px;
letter-spacing: .08em;
text-transform: uppercase;
}
.worker-controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
}
select {
width: 100%;
min-width: 0;
padding: 5px 20px 5px 6px;
border: 1px solid #d2c8b7;
border-radius: 7px;
background: #f8f4eb;
color: var(--ink);
font-size: 9px;
font-weight: 700;
outline: none;
}
select:focus { border-color: var(--ink); }
.order-buttons {
display: grid;
gap: 4px;
}
.order-buttons button {
width: 24px;
height: 22px;
padding: 0;
border: 1px solid var(--line);
border-radius: 6px;
background: #f8f4eb;
font-size: 10px;
line-height: 1;
}
.order-buttons button:disabled {
opacity: .3;
cursor: default;
}
.inventory {
grid-column: 2 / 5;
display: flex;
gap: 5px;
margin-top: -2px;
}
.inventory span {
padding: 3px 6px;
border-radius: 5px;
background: #e9e1d3;
color: #667068;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 8px;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.metric {
padding: 9px 7px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,.42);
text-align: center;
}
.metric strong {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 17px;
}
.metric span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: .09em;
text-transform: uppercase;
}
.claim {
margin-top: 7px;
padding: 9px 10px;
border-left: 3px solid var(--danger);
border-radius: 7px;
background: rgba(201,79,70,.08);
font-size: 10px;
line-height: 1.4;
}
.claim.good {
border-color: var(--success);
background: rgba(60,145,109,.09);
}
.claim strong { font-weight: 850; }
.rules {
margin: 0;
padding-left: 18px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.rules li { margin: 5px 0; }
.rules b { color: var(--ink); }
#log {
display: grid;
gap: 7px;
}
.log-entry {
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,.42);
font-size: 10px;
line-height: 1.4;
}
.log-entry.good { border-left: 3px solid var(--success); }
.log-entry.bad { border-left: 3px solid var(--danger); }
.log-entry.info { border-left: 3px solid var(--gold); }
.log-entry strong {
display: block;
margin-bottom: 3px;
font-size: 10px;
}
.log-entry span { color: var(--muted); }
.bottom {
position: fixed;
z-index: 9;
left: 50%;
bottom: 18px;
width: min(760px, calc(100vw - 40px));
transform: translateX(-50%);
padding: 12px;
border: 1px solid rgba(255,255,255,.65);
border-radius: 17px;
background: rgba(247,242,231,.95);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.timeline {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 10px;
}
.phase {
position: relative;
padding: 8px 9px;
overflow: hidden;
border-radius: 8px;
background: #e8e0d2;
color: #858b84;
font-size: 9px;
font-weight: 850;
letter-spacing: .1em;
text-transform: uppercase;
transition: .2s ease;
}
.phase::after {
content: "";
position: absolute;
inset: auto 0 0;
height: 3px;
background: transparent;
}
.phase.active {
background: var(--ink);
color: #fff8e9;
}
.phase.active::after { background: var(--gold); }
.phase.done {
background: #d8e5d9;
color: #376d58;
}
.control-row {
display: grid;
grid-template-columns: minmax(150px, 1fr) auto auto;
gap: 10px;
align-items: center;
}
.selection-info {
min-width: 0;
}
.selection-info strong {
display: block;
font-size: 12px;
}
.selection-info span {
display: block;
margin-top: 3px;
overflow: hidden;
color: var(--muted);
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.quick-actions {
display: flex;
gap: 4px;
}
.quick-actions button {
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: #faf6ed;
font-size: 9px;
font-weight: 800;
}
.quick-actions button.active {
border-color: var(--ink);
background: var(--ink);
color: #fff8e9;
}
.primary {
padding: 10px 16px;
border: 0;
border-radius: 9px;
background: var(--poppy);
color: white;
font-size: 10px;
font-weight: 900;
letter-spacing: .07em;
text-transform: uppercase;
box-shadow: 0 5px 12px rgba(230,109,82,.25);
}
.primary:hover { filter: brightness(1.05); }
.primary:disabled { opacity: .45; cursor: wait; }
.ghost {
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: transparent;
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.tooltip {
position: fixed;
z-index: 20;
display: none;
pointer-events: none;
padding: 7px 9px;
border-radius: 7px;
background: rgba(39,52,47,.93);
color: #fff8e9;
font-size: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,.16);
}
.loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: #e7dfce;
color: var(--ink);
font-size: 12px;
font-weight: 800;
letter-spacing: .14em;
text-transform: uppercase;
transition: opacity .3s;
}
.loading.done { opacity: 0; pointer-events: none; }
@media (max-width: 1000px) {
.panel.right { display: none; }
.panel.left { width: 285px; }
}
@media (max-width: 680px) {
.topbar { top: 10px; left: 10px; right: 10px; }
.brand { padding: 9px 11px; }
.brand h1 { font-size: 11px; }
.brand small { display: none; }
.round-box { padding: 9px 11px; }
.panel.left {
top: 64px;
left: 10px;
width: calc(100vw - 20px);
max-height: 35vh;
padding: 12px;
}
.panel.left .intro, .panel.left .rules-wrap { display: none; }
.bottom {
bottom: 10px;
width: calc(100vw - 20px);
padding: 9px;
}
.control-row { grid-template-columns: 1fr; gap: 7px; }
.quick-actions { justify-content: center; }
.primary { width: 100%; }
.selection-info { display: none; }
.timeline { margin-bottom: 7px; }
.phase { padding: 6px; font-size: 8px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel orchard board"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark">O</div>
<div>
<h1>Orchard Protocol</h1>
<small>Voxel coordination table</small>
</div>
</div>
<div class="round-box">
<span>Round</span>
<strong id="roundLabel">01</strong>
<span>Crates</span>
<strong id="crateLabel">00</strong>
</div>
</header>
<aside class="panel left">
<p class="eyebrow">Season 04 · Shared Grove</p>
<h2>Coordinate the<br>simultaneous shift.</h2>
<p class="intro">
Every worker moves at once. If two workers claim the same fruit, bay,
or pump, the order above breaks the tie deterministically.
</p>
<div class="scenario-buttons">
<button class="scenario active" id="clashScenario">
<strong>Stage a clash</strong>
<span>Two workers race for the same ripe slot.</span>
</button>
<button class="scenario" id="coordinateScenario">
<strong>Coordinate plan</strong>
<span>Unique targets. No wasted actions.</span>
</button>
</div>
<section class="section">
<div class="section-title">
Turn order
<small>Top wins ties</small>
</div>
<div id="orderList"></div>
</section>
<section class="section">
<div class="section-title">
Live claim analysis
<small id="analysisMode">Clash plan</small>
</div>
<div class="metric-grid">
<div class="metric"><strong id="plannedMetric">4</strong><span>Planned</span></div>
<div class="metric"><strong id="conflictMetric">1</strong><span>Collisions</span></div>
<div class="metric"><strong id="successMetric">75%</strong><span>Possible</span></div>
</div>
<div id="claims"></div>
</section>
<section class="section rules-wrap">
<div class="section-title">Deterministic rules</div>
<ol class="rules">
<li><b>Move:</b> all assigned workers travel simultaneously.</li>
<li><b>Claim:</b> each tree, delivery bay, and pump has one slot.</li>
<li><b>Tie:</b> priority is read from the top of the order.</li>
<li><b>Deliver:</b> carried fruit becomes a crate at the barn.</li>
</ol>
</section>
</aside>
<aside class="panel right">
<div class="section-title">
Resolution log
<button class="ghost" id="resetButton">Reset</button>
</div>
<div id="log"></div>
<section class="section rules-wrap">
<div class="section-title">Legend</div>
<ol class="rules">
<li><b>Orange blocks:</b> ripe fruit slots.</li>
<li><b>Blue blocks:</b> worker water supply.</li>
<li><b>Brown blocks:</b> carried fruit.</li>
<li><b>Green outline:</b> current target.</li>
</ol>
<p class="intro">
Drag the board to orbit. Scroll to zoom. Select a worker, choose an
action, then click a target in the orchard.
</p>
</section>
</aside>
<footer class="bottom">
<div class="timeline">
<div class="phase active" data-phase="plan">1 · Plan</div>
<div class="phase" data-phase="move">2 · Move together</div>
<div class="phase" data-phase="resolve">3 · Resolve claims</div>
</div>
<div class="control-row">
<div class="selection-info">
<strong id="selectedName">Pip · Poppy team</strong>
<span id="selectedTarget">Harvest at Amber Crown</span>
</div>
<div class="quick-actions" id="quickActions">
<button data-action="harvest">Harvest</button>
<button data-action="carry">Carry</button>
<button data-action="refill">Refill</button>
<button data-action="idle">Rest</button>
</div>
<button class="primary" id="resolveButton">Resolve round</button>
</div>
</footer>
<div class="tooltip" id="tooltip"></div>
<div class="loading" id="loading">Growing the orchard…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Data
// ---------------------------------------------------------------------
const $ = (selector) => document.querySelector(selector);
const N = 6;
const TILE = 1.2;
const DEFAULT_ORDER = ["p1", "m1", "m2", "p2"];
const workers = [
{
id: "p1", name: "Pip", team: "Poppy", color: "#e66d52", initial: [0, 3],
pos: [0, 3], action: "harvest", target: "T1", fruit: 0, water: 2,
mesh: null, marker: null, ring: null, fruitMesh: null, waterMesh: null
},
{
id: "m1", name: "Mira", team: "Moss", color: "#3f9b83", initial: [5, 3],
pos: [5, 3], action: "harvest", target: "T1", fruit: 0, water: 2,
mesh: null, marker: null, ring: null, fruitMesh: null, waterMesh: null
},
{
id: "m2", name: "Moss", team: "Moss", color: "#3f9b83", initial: [3, 5],
pos: [3, 5], action: "refill", target: "W1", fruit: 1, water: 1,
mesh: null, marker: null, ring: null, fruitMesh: null, waterMesh: null
},
{
id: "p2", name: "Pesto", team: "Poppy", color: "#e66d52", initial: [5, 5],
pos: [5, 5], action: "carry", target: "B1", fruit: 1, water: 1,
mesh: null, marker: null, ring: null, fruitMesh: null, waterMesh: null
}
];
const workerById = Object.fromEntries(workers.map(w => [w.id, w]));
const state = {
round: 1,
crates: 0,
order: [...DEFAULT_ORDER],
selected: "p1",
running: false,
mode: "clash",
logs: []
};
const targets = {
T1: { type: "tree", name: "Amber Crown", cell: [1, 2], group: null, fruitMeshes: [] },
T2: { type: "tree", name: "Pear Block", cell: [4, 2], group: null, fruitMeshes: [] },
T3: { type: "tree", name: "Ruby Canopy", cell: [2, 4], group: null, fruitMeshes: [] },
T4: { type: "tree", name: "Citadel Tree", cell: [4, 4], group: null, fruitMeshes: [] },
B1: { type: "bay", name: "West Bay", cell: [2, 0], group: null, fruitMeshes: [] },
B2: { type: "bay", name: "East Bay", cell: [4, 0], group: null, fruitMeshes: [] },
W1: { type: "well", name: "Shared Pump", cell: [0, 4], group: null, fruitMeshes: [] }
};
const targetOrder = ["T1", "T2", "T3", "T4", "B1", "B2", "W1"];
const actionNames = {
harvest: "Harvest",
carry: "Carry",
refill: "Refill",
idle: "Rest"
};
const targetNames = {
T1: "Amber Crown",
T2: "Pear Block",
T3: "Ruby Canopy",
T4: "Citadel Tree",
B1: "West Bay",
B2: "East Bay",
W1: "Shared Pump"
};
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const canvas = $("#scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
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.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e7dfce");
scene.fog = new THREE.Fog("#e7dfce", 19, 31);
const camera = new THREE.OrthographicCamera(-8, 8, 5, -5, 0.1, 100);
let yaw = 0.66;
let pitch = 0.76;
const cameraRadius = 13;
scene.add(new THREE.HemisphereLight("#fff8e6", "#8b8c78", 2.1));
const sun = new THREE.DirectionalLight("#fff0cf", 3.1);
sun.position.set(-7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const materials = {
soilA: new THREE.MeshStandardMaterial({ color: "#a9b878", roughness: 1, flatShading: true }),
soilB: new THREE.MeshStandardMaterial({ color: "#b8c587", roughness: 1, flatShading: true }),
soilC: new THREE.MeshStandardMaterial({ color: "#c2ca8d", roughness: 1, flatShading: true }),
soilD: new THREE.MeshStandardMaterial({ color: "#9eae72", roughness: 1, flatShading: true }),
soilE: new THREE.MeshStandardMaterial({ color: "#b3bf80", roughness: 1, flatShading: true }),
trunk: new THREE.MeshStandardMaterial({ color: "#76513a", roughness: 1, flatShading: true }),
leafA: new THREE.MeshStandardMaterial({ color: "#4e8b55", roughness: 1, flatShading: true }),
leafB: new THREE.MeshStandardMaterial({ color: "#65a15a", roughness: 1, flatShading: true }),
leafC: new THREE.MeshStandardMaterial({ color: "#3f774d", roughness: 1, flatShading: true }),
fruit: new THREE.MeshStandardMaterial({ color: "#ef7440", roughness: .78, flatShading: true }),
stone: new THREE.MeshStandardMaterial({ color: "#8e9187", roughness: 1, flatShading: true }),
stoneLight: new THREE.MeshStandardMaterial({ color: "#b8b6a6", roughness: 1, flatShading: true }),
wood: new THREE.MeshStandardMaterial({ color: "#8a5d3c", roughness: 1, flatShading: true }),
woodDark: new THREE.MeshStandardMaterial({ color: "#65442f", roughness: 1, flatShading: true }),
barn: new THREE.MeshStandardMaterial({ color: "#b95643", roughness: 1, flatShading: true }),
roof: new THREE.MeshStandardMaterial({ color: "#713f35", roughness: 1, flatShading: true }),
water: new THREE.MeshStandardMaterial({ color: "#55b5c6", roughness: .55, flatShading: true }),
crate: new THREE.MeshStandardMaterial({ color: "#c88a49", roughness: 1, flatShading: true }),
dark: new THREE.MeshStandardMaterial({ color: "#35443d", roughness: .9, flatShading: true }),
skinA: new THREE.MeshStandardMaterial({ color: "#e9b383", roughness: 1, flatShading: true }),
skinB: new THREE.MeshStandardMaterial({ color: "#9b674d", roughness: 1, flatShading: true }),
success: new THREE.MeshBasicMaterial({ color: "#4fb889" }),
failure: new THREE.MeshBasicMaterial({ color: "#e05b50" })
};
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
function box(parent, size, position, material, shadow = true) {
const mesh = new THREE.Mesh(boxGeometry, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cellPosition(cell) {
return new THREE.Vector3(
(cell[0] - (N - 1) / 2) * TILE,
0,
(cell[1] - (N - 1) / 2) * TILE
);
}
function labelSprite(text, color = "#34453d") {
const c = document.createElement("canvas");
c.width = 256;
c.height = 72;
const ctx = c.getContext("2d");
ctx.fillStyle = "rgba(248,243,229,.94)";
ctx.fillRect(8, 10, 240, 52);
ctx.strokeStyle = "#c3b89f";
ctx.lineWidth = 5;
ctx.strokeRect(8, 10, 240, 52);
ctx.fillStyle = color;
ctx.font = "bold 29px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 128, 37);
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(1.22, .34, 1);
return sprite;
}
function buildBoard() {
const board = new THREE.Group();
scene.add(board);
const foundationMat = new THREE.MeshStandardMaterial({
color: "#806449", roughness: 1, flatShading: true
});
box(board, [N * TILE + .42, .34, N * TILE + .42], [0, -.29, 0], foundationMat);
box(board, [N * TILE + .58, .12, N * TILE + .58], [0, -.49, 0], materials.woodDark);
const tileMaterials = [
materials.soilA, materials.soilB, materials.soilC,
materials.soilD, materials.soilE, materials.soilB
];
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const p = cellPosition([x, z]);
const mat = tileMaterials[(x * 3 + z * 2) % tileMaterials.length];
const tile = box(board, [TILE - .055, .18, TILE - .055], [p.x, -.09, p.z], mat);
tile.rotation.y = ((x + z) % 2) * .006;
}
}
// Voxel corner posts and short rails.
const half = (N * TILE) / 2;
const postPositions = [
[-half, -half], [half, -half], [-half, half], [half, half]
];
for (const [x, z] of postPositions) {
box(board, [.18, .72, .18], [x, .24, z], materials.woodDark);
box(board, [.24, .12, .24], [x, .62, z], materials.wood);
}
// Decorative grass tufts, placed only on walkable-looking open cells.
const occupied = new Set(["1,2", "4,2", "2,4", "4,4", "3,0", "0,4"]);
const tuftMat = new THREE.MeshStandardMaterial({ color: "#7e9e55", flatShading: true });
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
if (occupied.has(`${x},${z}`) || (x + z) % 3 !== 0) continue;
const p = cellPosition([x, z]);
box(board, [.08, .18, .08], [p.x - .31, .08, p.z + .25], tuftMat, false);
box(board, [.08, .13, .08], [p.x - .21, .065, p.z + .29], tuftMat, false);
}
}
}
function buildTree(id) {
const target = targets[id];
const group = new THREE.Group();
const p = cellPosition(target.cell);
group.position.copy(p);
scene.add(group);
target.group = group;
box(group, [.24, 1.05, .24], [0, .52, 0], materials.trunk);
box(group, [.78, .48, .72], [0, 1.16, 0], materials.leafA);
box(group, [.52, .42, .58], [-.35, .97, .02], materials.leafB);
box(group, [.55, .45, .48], [.33, 1.0, -.08], materials.leafC);
box(group, [.43, .35, .45], [.02, 1.48, -.04], materials.leafB);
const fruitPositions = [
[-.28, 1.13, .38],
[.28, 1.22, .35],
[.03, .88, .4]
];
for (const pos of fruitPositions) {
const fruit = box(group, [.16, .16, .16], pos, materials.fruit, false);
target.fruitMeshes.push(fruit);
}
const sign = labelSprite(id);
sign.position.set(0, 1.84, 0);
group.add(sign);
group.traverse(object => {
object.userData.targetId = id;
});
}
function buildBarnAndBays() {
const barn = new THREE.Group();
const bp = cellPosition([3, 0]);
barn.position.copy(bp);
scene.add(barn);
box(barn, [1.0, .72, .86], [0, .36, 0], materials.barn);
box(barn, [1.14, .18, .98], [0, .78, 0], materials.roof);
box(barn, [.63, .68, .93], [0, .78, 0], materials.roof);
box(barn, [.32, .48, .04], [0, .25, .47], materials.woodDark);
box(barn, [.18, .18, .05], [.23, .48, .48], materials.gold || materials.fruit);
for (const id of ["B1", "B2"]) {
const target = targets[id];
const group = new THREE.Group();
const p = cellPosition(target.cell);
group.position.copy(p);
scene.add(group);
target.group = group;
box(group, [.72, .12, .72], [0, .07, 0], materials.woodDark);
box(group, [.55, .35, .55], [0, .29, 0], materials.crate);
box(group, [.58, .07, .09], [0, .31, 0], materials.wood);
box(group, [.09, .07, .58], [0, .31, 0], materials.wood);
const sign = labelSprite(id);
sign.position.set(0, .82, 0);
group.add(sign);
group.traverse(object => {
object.userData.targetId = id;
});
}
}
function buildWell() {
const target = targets.W1;
const group = new THREE.Group();
const p = cellPosition(target.cell);
group.position.copy(p);
scene.add(group);
target.group = group;
box(group, [.88, .18, .88], [0, .09, 0], materials.stone);
box(group, [.18, .48, .82], [-.35, .32, 0], materials.stoneLight);
box(group, [.18, .48, .82], [.35, .32, 0], materials.stoneLight);
box(group, [.82, .48, .18], [0, .32, -.35], materials.stoneLight);
box(group, [.82, .48, .18], [0, .32, .35], materials.stoneLight);
box(group, [.52, .06, .52], [0, .36, 0], materials.water, false);
box(group, [.12, .65, .12], [-.25, .73, 0], materials.wood);
box(group, [.12, .65, .12], [.25, .73, 0], materials.wood);
box(group, [.72, .12, .12], [0, 1.02, 0], materials.woodDark);
const sign = labelSprite("PUMP");
sign.position.set(0, 1.37, 0);
group.add(sign);
group.traverse(object => {
object.userData.targetId = "W1";
});
}
function buildWorker(worker) {
const group = new THREE.Group();
const skin = worker.team === "Poppy" ? materials.skinA : materials.skinB;
const bodyMat = new THREE.MeshStandardMaterial({
color: worker.color, roughness: .9, flatShading: true
});
box(group, [.17, .32, .18], [-.11, .16, 0], materials.dark);
box(group, [.17, .32, .18], [.11, .16, 0], materials.dark);
box(group, [.42, .48, .28], [0, .58, 0], bodyMat);
box(group, [.15, .36, .17], [-.28, .58, 0], skin);
box(group, [.15, .36, .17], [.28, .58, 0], skin);
box(group, [.34, .32, .31], [0, 1.0, 0], skin);
const hatMat = new THREE.MeshStandardMaterial({
color: worker.team === "Poppy" ? "#f0c767" : "#7ec1a8",
roughness: 1, flatShading: true
});
box(group, [.44, .11, .4], [0, 1.2, 0], hatMat);
box(group, [.32, .15, .3], [0, 1.31, 0], hatMat);
// Eyes face +Z, making worker orientation visible.
box(group, [.045, .05, .03], [-.09, 1.03, .166], materials.dark, false);
box(group, [.045, .05, .03], [.09, 1.03, .166], materials.dark, false);
const fruitMesh = new THREE.Group();
box(fruitMesh, [.29, .24, .25], [0, 0, 0], materials.crate);
box(fruitMesh, [.32, .05, .28], [0, .08, 0], materials.woodDark);
fruitMesh.position.set(0, .54, .31);
group.add(fruitMesh);
worker.fruitMesh = fruitMesh;
const waterMesh = new THREE.Group();
box(waterMesh, [.29, .35, .14], [0, 0, 0], materials.water);
box(waterMesh, [.1, .13, .03], [0, .01, .08], materials.stoneLight);
waterMesh.position.set(0, .67, -.22);
group.add(waterMesh);
worker.waterMesh = waterMesh;
const marker = new THREE.Mesh(boxGeometry, materials.success);
marker.scale.set(.22, .22, .22);
marker.position.set(0, 1.72, 0);
marker.visible = false;
group.add(marker);
worker.marker = marker;
const ring = new THREE.Group();
const ringMat = new THREE.MeshBasicMaterial({ color: "#34483e" });
box(ring, [.58, .025, .05], [0, .035, .34], ringMat, false);
box(ring, [.58, .025, .05], [0, .035, -.34], ringMat, false);
box(ring, [.05, .025, .58], [.34, .035, 0], ringMat, false);
box(ring, [.05, .025, .58], [-.34, .035, 0], ringMat, false);
group.add(ring);
worker.ring = ring;
const pos = cellPosition(worker.pos);
group.position.copy(pos);
scene.add(group);
worker.mesh = group;
}
buildBoard();
["T1", "T2", "T3", "T4"].forEach(buildTree);
buildBarnAndBays();
buildWell();
workers.forEach(buildWorker);
// Target outline and route preview.
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({ color: "#355b49" })
);
outline.visible = false;
scene.add(outline);
const routeLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: "#355b49",
dashSize: .13,
gapSize: .09,
transparent: true,
opacity: .8
})
);
routeLine.visible = false;
scene.add(routeLine);
// ---------------------------------------------------------------------
// Direct camera controls
// ---------------------------------------------------------------------
let dragging = false;
let dragMoved = 0;
let pointerStart = { x: 0, y: 0 };
function updateCamera() {
const horizontal = Math.cos(pitch) * cameraRadius;
camera.position.set(
Math.sin(yaw) * horizontal,
Math.sin(pitch) * cameraRadius,
Math.cos(yaw) * horizontal
);
camera.lookAt(0, .15, 0);
camera.updateMatrixWorld();
}
function resize() {
const aspect = innerWidth / innerHeight;
const viewHeight = aspect < 1 ? 13.5 : 9.4;
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
updateCamera();
}
addEventListener("resize", resize);
resize();
updateCamera();
canvas.addEventListener("pointerdown", event => {
dragging = true;
dragMoved = 0;
pointerStart = { x: event.clientX, y: event.clientY };
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (dragging) {
const dx = event.clientX - pointerStart.x;
const dy = event.clientY - pointerStart.y;
dragMoved += Math.abs(dx) + Math.abs(dy);
yaw -= dx * .006;
pitch = THREE.MathUtils.clamp(pitch + dy * .004, .43, 1.25);
pointerStart = { x: event.clientX, y: event.clientY };
updateCamera();
$("#tooltip").style.display = "none";
} else {
updateHover(event);
}
});
canvas.addEventListener("pointerup", event => {
dragging = false;
if (dragMoved < 7) handleBoardClick(event);
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(camera.zoom * Math.exp(-event.deltaY * .001), .62, 1.85);
camera.updateProjectionMatrix();
}, { passive: false });
canvas.addEventListener("dblclick", () => {
yaw = .66;
pitch = .76;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const targetGroups = targetOrder.map(id => targets[id].group);
function pickTarget(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(targetGroups, true);
for (const hit of hits) {
if (hit.object.userData.targetId) return hit.object.userData.targetId;
}
return null;
}
function updateHover(event) {
const id = pickTarget(event);
const tooltip = $("#tooltip");
if (!id) {
tooltip.style.display = "none";
canvas.style.cursor = "grab";
return;
}
const type = targets[id].type;
const hint = type === "tree" ? "click to select this tree"
: type === "bay" ? "click to select this delivery bay"
: "click to select the pump";
tooltip.textContent = `${id} · ${targetNames[id]} — ${hint}`;
tooltip.style.left = `${Math.min(event.clientX + 14, innerWidth - 220)}px`;
tooltip.style.top = `${event.clientY + 14}px`;
tooltip.style.display = "block";
canvas.style.cursor = "pointer";
}
function handleBoardClick(event) {
const id = pickTarget(event);
if (!id) return;
const worker = workerById[state.selected];
const type = targets[id].type;
const compatible =
(worker.action === "harvest" && type === "tree") ||
(worker.action === "carry" && type === "bay") ||
(worker.action === "refill" && type === "well");
if (!compatible) return;
worker.target = id;
renderOrder();
updateAnalysis();
updateVisuals();
addLog("info", `${worker.name}'s target changed`, `${actionNames[worker.action]} → ${targetNames[id]}`);
}
// ---------------------------------------------------------------------
// Grid pathfinding
// ---------------------------------------------------------------------
const blocked = new Set([
"1,2", "4,2", "2,4", "4,4", "3,0", "0,4"
]);
const directions = [
[1, 0], [-1, 0], [0, 1], [0, -1]
];
function isWalkable(cell) {
return cell[0] >= 0 && cell[0] < N &&
cell[1] >= 0 && cell[1] < N &&
!blocked.has(`${cell[0]},${cell[1]}`);
}
function sameCell(a, b) {
return a[0] === b[0] && a[1] === b[1];
}
function findPath(start, goal) {
if (!goal) return null;
if (sameCell(start, goal)) return [[...start]];
const queue = [[...start]];
const cameFrom = new Map();
const visited = new Set([`${start[0]},${start[1]}`]);
while (queue.length) {
const current = queue.shift();
for (const [dx, dz] of directions) {
const next = [current[0] + dx, current[1] + dz];
const key = `${next[0]},${next[1]}`;
if (!isWalkable(next) || visited.has(key)) continue;
visited.add(key);
cameFrom.set(key, current);
if (sameCell(next, goal)) {
const path = [goal];
let cursor = goal;
while (!sameCell(cursor, start)) {
cursor = cameFrom.get(`${cursor[0]},${cursor[1]}`);
path.push(cursor);
}
path.reverse();
return path;
}
queue.push(next);
}
}
return null;
}
function adjacentCells(cell) {
return directions
.map(([dx, dz]) => [cell[0] + dx, cell[1] + dz])
.filter(isWalkable);
}
function destinationFor(worker) {
if (worker.action === "idle") return null;
const target = targets[worker.target];
if (!target) return null;
if (worker.action === "carry") {
return [...target.cell];
}
const candidates = adjacentCells(target.cell);
const paths = candidates
.map(cell => findPath(worker.pos, cell))
.filter(Boolean)
.sort((a, b) => a.length - b.length);
return paths.length ? [...paths[0].at(-1)] : null;
}
// ---------------------------------------------------------------------
// Interface and plan analysis
// ---------------------------------------------------------------------
function targetOptions(action) {
if (action === "harvest") {
return ["T1", "T2", "T3", "T4"].map(id =>
`<option value="${id}">${id} · ${targetNames[id]}</option>`
).join("");
}
if (action === "carry") {
return ["B1", "B2"].map(id =>
`<option value="${id}">${id} · ${targetNames[id]}</option>`
).join("");
}
if (action === "refill") {
return `<option value="W1">W1 · Shared Pump</option>`;
}
return `<option value="">No target</option>`;
}
function defaultTarget(action) {
return { harvest: "T1", carry: "B1", refill: "W1", idle: "" }[action];
}
function renderOrder() {
const list = $("#orderList");
list.innerHTML = "";
state.order.forEach((id, index) => {
const worker = workerById[id];
const card = document.createElement("div");
card.className = `worker-card${state.selected === id ? " selected" : ""}`;
card.style.setProperty("--worker-color", worker.color);
let targetSelect = worker.action === "idle"
? `<select data-field="target" disabled>${targetOptions("idle")}</select>`
: `<select data-field="target">${targetOptions(worker.action)}</select>`;
targetSelect = targetSelect.replace(
`value="${worker.target}"`,
`value="${worker.target}" selected`
);
card.innerHTML = `
<div class="rank">${String(index + 1).padStart(2, "0")}</div>
<div class="avatar">${worker.name[0]}</div>
<div class="worker-main">
<div class="worker-name">
${worker.name}
<small>${worker.team}</small>
</div>
<div class="worker-controls">
<select data-field="action">
${Object.entries(actionNames).map(([value, label]) =>
`<option value="${value}"${worker.action === value ? " selected" : ""}>${label}</option>`
).join("")}
</select>
${targetSelect}
</div>
</div>
<div class="order-buttons">
<button data-move="up"${index === 0 ? " disabled" : ""} title="Raise priority">▲</button>
<button data-move="down"${index === state.order.length - 1 ? " disabled" : ""} title="Lower priority">▼</button>
</div>
<div class="inventory">
<span>FRUIT ${worker.fruit}</span>
<span>WATER ${worker.water}</span>
</div>
`;
card.addEventListener("click", event => {
if (event.target.closest("select, button")) return;
state.selected = id;
renderOrder();
updateVisuals();
});
card.querySelector('[data-field="action"]').addEventListener("change", event => {
worker.action = event.target.value;
worker.target = defaultTarget(worker.action);
state.selected = id;
renderOrder();
updateAnalysis();
updateVisuals();
});
const targetField = card.querySelector('[data-field="target"]');
if (!targetField.disabled) {
targetField.addEventListener("change", event => {
worker.target = event.target.value;
state.selected = id;
updateAnalysis();
updateVisuals();
});
}
card.querySelectorAll("[data-move]").forEach(button => {
button.addEventListener("click", event => {
event.stopPropagation();
const direction = button.dataset.move === "up" ? -1 : 1;
const from = state.order.indexOf(id);
const to = from + direction;
if (to < 0 || to >= state.order.length) return;
[state.order[from], state.order[to]] = [state.order[to], state.order[from]];
renderOrder();
updateAnalysis();
updateVisuals();
});
});
list.appendChild(card);
});
updateQuickActions();
}
function updateQuickActions() {
const worker = workerById[state.selected];
$("#selectedName").textContent = `${worker.name} · ${worker.team} team`;
const targetText = worker.action === "idle"
? "No action selected"
: `${actionNames[worker.action]} at ${targetNames[worker.target]}`;
$("#selectedTarget").textContent = targetText;
document.querySelectorAll("#quickActions button").forEach(button => {
button.classList.toggle("active", button.dataset.action === worker.action);
});
}
function analyzePlan() {
const groups = new Map();
let planned = 0;
for (const id of state.order) {
const worker = workerById[id];
if (worker.action === "idle") continue;
planned++;
const key = `${worker.action}:${worker.target}`;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(worker);
}
let conflicts = 0;
let possible = 0;
const claims = [];
for (const [key, group] of groups) {
conflicts += Math.max(0, group.length - 1);
const winner = group[0];
const eligible =
(winner.action === "harvest" && winner.water > 0) ||
(winner.action === "carry" && winner.fruit > 0) ||
winner.action === "refill";
if (eligible) possible++;
if (group.length > 1) {
claims.push({
group,
action: winner.action,
target: winner.target,
eligible
});
}
}
return { groups, planned, conflicts, possible, claims };
}
function updateAnalysis() {
const analysis = analyzePlan();
$("#plannedMetric").textContent = analysis.planned;
$("#conflictMetric").textContent = analysis.conflicts;
$("#successMetric").textContent = analysis.planned
? `${Math.round(analysis.possible / analysis.planned * 100)}%`
: "—";
$("#analysisMode").textContent = state.mode === "clash" ? "Clash plan" : "Coordinated plan";
const claims = $("#claims");
claims.innerHTML = "";
if (!analysis.claims.length) {
claims.innerHTML = `
<div class="claim good">
<strong>No simultaneous collisions.</strong><br>
Every worker has a distinct resource claim.
</div>
`;
} else {
for (const claim of analysis.claims) {
const names = claim.group.map(w => w.name).join(" + ");
claims.innerHTML += `
<div class="claim">
<strong>${claim.target} · ${names}</strong><br>
${claim.group[0].name} receives priority;
${claim.group.length - 1} action${claim.group.length === 2 ? "" : "s"} will be wasted.
</div>
`;
}
}
$("#clashScenario").classList.toggle("active", state.mode === "clash");
$("#coordinateScenario").classList.toggle("active", state.mode === "coordinated");
}
function updateVisuals() {
for (const worker of workers) {
worker.fruitMesh.visible = worker.fruit > 0;
worker.waterMesh.visible = worker.water > 0;
worker.ring.visible = worker.id === state.selected;
}
const worker = workerById[state.selected];
const target = targets[worker.target];
if (target && worker.action !== "idle") {
const p = cellPosition(target.cell);
outline.visible = true;
outline.position.set(p.x, target.type === "tree" ? 1.03 : .42, p.z);
outline.scale.set(
target.type === "tree" ? 1.05 : .86,
target.type === "tree" ? 2.05 : .72,
target.type === "tree" ? 1.05 : .86
);
} else {
outline.visible = false;
}
const destination = destinationFor(worker);
const path = destination ? findPath(worker.pos, destination) : null;
if (path && path.length > 1) {
const points = path.map(cell => {
const p = cellPosition(cell);
return new THREE.Vector3(p.x, .055, p.z);
});
routeLine.geometry.dispose();
routeLine.geometry = new THREE.BufferGeometry().setFromPoints(points);
routeLine.computeLineDistances();
routeLine.visible = true;
} else {
routeLine.visible = false;
}
}
function applyScenario(mode) {
state.mode = mode;
if (mode === "clash") {
workerById.p1.action = "harvest";
workerById.p1.target = "T1";
workerById.m1.action = "harvest";
workerById.m1.target = "T1";
workerById.m2.action = "refill";
workerById.m2.target = "W1";
workerById.p2.action = "carry";
workerById.p2.target = "B1";
} else {
workerById.p1.action = "harvest";
workerById.p1.target = "T1";
workerById.m1.action = "harvest";
workerById.m1.target = "T2";
workerById.m2.action = "carry";
workerById.m2.target = "B1";
workerById.p2.action = "refill";
workerById.p2.target = "W1";
}
renderOrder();
updateAnalysis();
updateVisuals();
addLog(
"info",
mode === "clash" ? "Clash plan staged" : "Coordinated plan loaded",
mode === "clash"
? "Pip and Mira will claim T1 simultaneously."
: "Every worker now claims a distinct resource."
);
}
// ---------------------------------------------------------------------
// Resolution and animation
// ---------------------------------------------------------------------
const tweens = [];
function tweenWorker(worker, path, duration) {
if (!path || path.length === 0) return;
const points = path.map(cell => {
const p = cellPosition(cell);
return new THREE.Vector3(p.x, 0, p.z);
});
tweens.push({
worker,
points,
start: performance.now(),
duration
});
}
function animate() {
const now = performance.now();
for (let i = tweens.length - 1; i >= 0; i--) {
const tween = tweens[i];
const raw = (now - tween.start) / tween.duration;
const t = THREE.MathUtils.clamp(raw, 0, 1);
const eased = t * t * (3 - 2 * t);
const scaled = eased * (tween.points.length - 1);
const index = Math.min(Math.floor(scaled), tween.points.length - 2);
const local = scaled - index;
const a = tween.points[index];
const b = tween.points[index + 1];
tween.worker.mesh.position.x = THREE.MathUtils.lerp(a.x, b.x, local);
tween.worker.mesh.position.z = THREE.MathUtils.lerp(a.z, b.z, local);
tween.worker.mesh.position.y = Math.sin(local * Math.PI) * .035;
if (index > 0 || local > .01) {
const dx = b.x - a.x;
const dz = b.z - a.z;
if (Math.abs(dx) + Math.abs(dz) > .001) {
tween.worker.mesh.rotation.y = Math.atan2(dx, dz);
}
}
if (raw >= 1) {
const last = tween.points.at(-1);
tween.worker.mesh.position.set(last.x, 0, last.z);
tween.worker.pos = [...tween.points.length ? pathCellFor(tween.points) : []];
tweens.splice(i, 1);
}
}
for (const worker of workers) {
if (worker.marker.visible) {
worker.marker.rotation.y += .025;
worker.marker.position.y = 1.72 + Math.sin(now * .004) * .06;
}
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// Preserve the final grid cell on the tween itself.
function pathCellFor(points) {
const last = points.at(-1);
return [
Math.round(last.x / TILE + (N - 1) / 2),
Math.round(last.z / TILE + (N - 1) / 2)
];
}
function setPhase(phase) {
document.querySelectorAll(".phase").forEach(element => {
const item = element.dataset.phase;
element.classList.toggle("active", item === phase);
element.classList.toggle("done",
(phase === "move" && item === "plan") ||
(phase === "resolve" && (item === "plan" || item === "move"))
);
});
}
function addLog(type, title, detail) {
state.logs.unshift({ type, title, detail });
state.logs = state.logs.slice(0, 9);
renderLog();
}
function renderLog() {
$("#log").innerHTML = state.logs.map(entry => `
<div class="log-entry ${entry.type}">
<strong>${entry.title}</strong>
<span>${entry.detail}</span>
</div>
`).join("");
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function resolveRound() {
if (state.running) return;
state.running = true;
const button = $("#resolveButton");
button.disabled = true;
button.textContent = "Resolving…";
for (const worker of workers) {
worker.marker.visible = false;
}
const round = state.round;
const analysis = analyzePlan();
const plans = [];
for (const id of state.order) {
const worker = workerById[id];
if (worker.action === "idle") continue;
const destination = destinationFor(worker);
const path = destination ? findPath(worker.pos, destination) : null;
plans.push({ worker, destination, path });
}
setPhase("move");
addLog("info", `Round ${round}: simultaneous movement`, `${plans.length} workers entered the grove.`);
// Every worker moves during the same interval. Longer paths finish later,
// but no worker waits for another worker's action.
for (const plan of plans) {
const duration = plan.path
? THREE.MathUtils.clamp(520 + plan.path.length * 110, 650, 1550)
: 300;
tweenWorker(plan.worker, plan.path, duration);
}
await delay(1650);
setPhase("resolve");
const groups = new Map();
for (const plan of plans) {
const key = `${plan.worker.action}:${plan.worker.target}`;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(plan);
}
let successful = 0;
let wasted = 0;
for (const [key, group] of groups) {
const capacity = 1;
let used = 0;
for (const plan of group) {
const worker = plan.worker;
const target = targets[worker.target];
let valid = Boolean(plan.destination);
let reason = "no route";
if (worker.action === "harvest" && worker.water <= 0) {
valid = false;
reason = "no water";
}
if (worker.action === "carry" && worker.fruit <= 0) {
valid = false;
reason = "no fruit";
}
if (used >= capacity) {
valid = false;
reason = "lower priority";
}
if (valid) {
used++;
successful++;
if (worker.action === "harvest") {
worker.water--;
worker.fruit++;
target.fruitMeshes.forEach(mesh => mesh.visible = false);
worker.marker.material = materials.success;
worker.marker.visible = true;
addLog("good", `${worker.name} harvested ${target.name}`, "One ripe slot and one water unit were consumed.");
}
if (worker.action === "carry") {
worker.fruit--;
state.crates++;
worker.marker.material = materials.success;
worker.marker.visible = true;
addLog("good", `${worker.name} delivered a crate`, `${target.name} accepted the carried fruit.`);
}
if (worker.action === "refill") {
worker.water = Math.min(3, worker.water + 2);
worker.marker.material = materials.success;
worker.marker.visible = true;
addLog("good", `${worker.name} refilled at the pump`, "The shared pump granted one deterministic claim.");
}
} else {
wasted++;
worker.marker.material = materials.failure;
worker.marker.visible = true;
addLog(
"bad",
`${worker.name}'s ${actionNames[worker.action].toLowerCase()} was wasted`,
reason === "lower priority"
? `${group[0].worker.name} had higher priority for ${target.name}.`
: `Reason: ${reason}.`
);
}
}
}
await delay(500);
const efficiency = plans.length ? Math.round(successful / plans.length * 100) : 100;
addLog(
"info",
`Round ${round}: ${successful}/${plans.length} actions succeeded`,
`${wasted} wasted move${wasted === 1 ? "" : "s"} · ${efficiency}% efficiency.`
);
updateVisuals();
updateAnalysis();
renderOrder();
// Ripe slots and bay capacity regenerate for the next cycle.
for (const target of Object.values(targets)) {
target.fruitMeshes.forEach(mesh => mesh.visible = true);
}
state.round++;
$("#roundLabel").textContent = String(state.round).padStart(2, "0");
$("#crateLabel").textContent = String(state.crates).padStart(2, "0");
button.disabled = false;
button.textContent = `Resolve round ${state.round}`;
state.running = false;
setPhase("resolve");
}
// ---------------------------------------------------------------------
// Controls, reset, and startup
// ---------------------------------------------------------------------
$("#quickActions").addEventListener("click", event => {
const button = event.target.closest("button[data-action]");
if (!button) return;
const worker = workerById[state.selected];
worker.action = button.dataset.action;
worker.target = defaultTarget(worker.action);
renderOrder();
updateAnalysis();
updateVisuals();
});
$("#clashScenario").addEventListener("click", () => applyScenario("clash"));
$("#coordinateScenario").addEventListener("click", () => applyScenario("coordinated"));
$("#resolveButton").addEventListener("click", resolveRound);
$("#resetButton").addEventListener("click", () => {
state.round = 1;
state.crates = 0;
state.order = [...DEFAULT_ORDER];
state.selected = "p1";
state.logs = [];
for (const worker of workers) {
worker.pos = [...worker.initial];
worker.fruit = worker.id === "m2" || worker.id === "p2" ? 1 : 0;
worker.water = worker.id === "m2" || worker.id === "p2" ? 1 : 2;
worker.marker.visible = false;
const p = cellPosition(worker.pos);
worker.mesh.position.set(p.x, 0, p.z);
worker.mesh.rotation.y = 0;
}
for (const target of Object.values(targets)) {
target.fruitMeshes.forEach(mesh => mesh.visible = true);
}
applyScenario("clash");
addLog("info", "Orchard reset", "All workers, supplies, targets, and priorities were restored.");
updateVisuals();
});
renderOrder();
updateAnalysis();
updateVisuals();
addLog("info", "Deterministic rules loaded", "Top-to-bottom order resolves simultaneous claims.");
addLog("info", "Try the two scenarios", "A staged clash wastes one action; coordinated targets waste none.");
$("#roundLabel").textContent = "01";
$("#crateLabel").textContent = "00";
requestAnimationFrame(animate);
requestAnimationFrame(() => {
$("#loading").classList.add("done");
setTimeout(() => $("#loading").remove(), 350);
});
</script>
</body>
</html>
```