Prompt specification
Build or customize the Three.js 3D scene "Farm Rotation Strategy Board" 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: Farm Rotation Strategy Board
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/farm-rotation-strategy-board-x3571
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: farm rotation strategy board. Create a small original farming game with three crop types and explicit simplified rotation effects. Label rates fictional and make each season's inputs and outputs inspectable.
Working Three.js Starter (farm-rotation-strategy-board-x3571):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Little Rotation — Voxel Farm Strategy</title>
<style>
:root {
--bg: #172329;
--panel: #202f34;
--panel-2: #293b40;
--panel-3: #33494e;
--line: #426067;
--text: #f1f4e8;
--muted: #aec1bd;
--accent: #e9c46a;
--green: #79c977;
--grain: #f1c75b;
--root: #ed8d50;
--bad: #ef6b6b;
--cyan: #77d7d0;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
height: 100vh;
overflow: hidden;
}
button { font: inherit; }
#app {
height: 100%;
display: grid;
grid-template-rows: auto minmax(0, 1fr);
}
header {
min-height: 74px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 12px 20px;
background: #1d2b30;
border-bottom: 1px solid #3b5055;
box-shadow: 0 4px 18px #0002;
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: max-content;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
transform: rotate(-4deg);
}
.brand-mark i {
display: block;
background: var(--green);
border-radius: 2px;
}
.brand-mark i:nth-child(2) { background: var(--grain); }
.brand-mark i:nth-child(3) { background: var(--root); }
.brand-mark i:nth-child(4) { background: #6b4c35; }
.brand h1 {
margin: 0;
font-size: 19px;
line-height: 1.05;
letter-spacing: .01em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.top-stats {
display: flex;
justify-content: flex-end;
align-items: stretch;
gap: 8px;
flex-wrap: wrap;
}
.stat {
min-width: 86px;
padding: 8px 11px;
background: #26383d;
border: 1px solid #40575c;
border-radius: 9px;
}
.stat small {
display: block;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: .09em;
}
.stat strong {
display: block;
margin-top: 2px;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.season-stat {
border-color: #b08e4f;
background: #3b382b;
}
.season-dots {
display: flex;
gap: 4px;
margin-top: 6px;
}
.season-dots i {
width: 15px;
height: 4px;
border-radius: 4px;
background: #607075;
}
.season-dots i.done { background: var(--accent); }
.season-dots i.current { background: #fff0b1; }
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 410px;
}
#scene-wrap {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #b9d4cb;
}
#scene-wrap canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene-wrap canvas:active { cursor: grabbing; }
.scene-title {
position: absolute;
left: 16px;
top: 15px;
z-index: 2;
padding: 10px 13px;
border-radius: 10px;
color: #213238;
background: #f6f0dccc;
border: 1px solid #ffffff88;
box-shadow: 0 6px 20px #263a3520;
backdrop-filter: blur(5px);
pointer-events: none;
}
.scene-title strong {
display: block;
font-size: 14px;
}
.scene-title span {
display: block;
margin-top: 2px;
font-size: 11px;
color: #536763;
}
.view-tools {
position: absolute;
right: 14px;
top: 15px;
z-index: 4;
display: flex;
gap: 6px;
}
.view-tools button {
width: 36px;
height: 34px;
border: 1px solid #ffffff88;
border-radius: 8px;
color: #26383a;
background: #f7f1decc;
cursor: pointer;
box-shadow: 0 4px 12px #23322f20;
}
.view-tools button:hover { background: #fff7df; }
.scene-help {
position: absolute;
left: 16px;
bottom: 14px;
z-index: 2;
padding: 8px 10px;
border-radius: 8px;
background: #203338d9;
border: 1px solid #7e9a9755;
color: #dce9e4;
font-size: 11px;
pointer-events: none;
}
#plot-labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 3;
}
.plot-label {
position: absolute;
transform: translate(-50%, -50%);
min-width: 66px;
padding: 4px 7px;
border: 1px solid #d7e4dd99;
border-radius: 6px;
background: #203338df;
color: #edf4e9;
box-shadow: 0 3px 10px #15222655;
text-align: center;
font-size: 10px;
font-weight: 700;
line-height: 1.25;
pointer-events: auto;
cursor: pointer;
user-select: none;
}
.plot-label.selected {
border-color: var(--cyan);
box-shadow: 0 0 0 2px #77d7d055, 0 3px 10px #15222655;
}
.plot-label .plan {
display: block;
color: var(--cyan);
font-size: 9px;
}
#plot-tooltip {
position: absolute;
z-index: 8;
display: none;
max-width: 230px;
padding: 9px 11px;
border-radius: 8px;
background: #17282ef2;
border: 1px solid #789591;
color: #edf4e9;
box-shadow: 0 8px 24px #0004;
font-size: 11px;
line-height: 1.45;
pointer-events: none;
}
#toast {
position: absolute;
left: 50%;
top: 76px;
z-index: 12;
transform: translate(-50%, -8px);
max-width: 90%;
padding: 9px 13px;
border-radius: 8px;
background: #213238ee;
border: 1px solid #8fa8a2;
color: #f5f2df;
box-shadow: 0 7px 22px #0004;
font-size: 12px;
opacity: 0;
transition: opacity .18s, transform .18s;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
aside {
min-height: 0;
overflow-y: auto;
background: var(--panel);
border-left: 1px solid #40565b;
scrollbar-color: #587278 #202f34;
}
.section {
padding: 15px 16px;
border-bottom: 1px solid #40565b;
}
.section h2 {
margin: 0 0 10px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: .12em;
color: #d9e4de;
}
.objective-card {
background: #2b3d3f;
border: 1px solid #587068;
border-radius: 10px;
padding: 11px;
}
.objective-card p {
margin: 0 0 9px;
color: #c9d7d1;
font-size: 12px;
line-height: 1.45;
}
.objective-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.objective-item {
display: flex;
align-items: center;
gap: 7px;
padding: 6px 7px;
border-radius: 6px;
background: #223337;
color: #aebfba;
font-size: 11px;
}
.objective-item::before {
content: "○";
color: #81948f;
font-weight: 900;
}
.objective-item.done {
color: #e7f3e4;
}
.objective-item.done::before {
content: "●";
color: var(--green);
}
.budgets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 10px;
}
.budget {
padding: 8px;
border: 1px solid #496267;
border-radius: 7px;
background: #1c2c31;
text-align: center;
}
.budget small {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: .08em;
}
.budget strong {
display: block;
margin-top: 2px;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.budget.over {
border-color: var(--bad);
color: #ffb1b1;
}
.crop-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.crop-card {
position: relative;
min-width: 0;
padding: 10px 7px 9px;
border: 1px solid #4a6267;
border-radius: 9px;
background: #293b40;
color: var(--text);
text-align: left;
cursor: pointer;
transition: transform .12s, border-color .12s, background .12s;
}
.crop-card:hover {
transform: translateY(-2px);
background: #31464a;
}
.crop-card.selected {
border-color: var(--crop);
background: #35494c;
box-shadow: inset 0 0 0 1px var(--crop), 0 5px 14px #0002;
}
.crop-card .crop-icon {
width: 23px;
height: 23px;
margin-bottom: 7px;
border-radius: 4px;
background: var(--crop);
box-shadow: 7px 7px 0 color-mix(in srgb, var(--crop), #000 35%);
transform: rotate(-8deg);
}
.crop-card strong {
display: block;
font-size: 12px;
}
.crop-card .rate {
display: block;
margin-top: 5px;
color: #c0d0ca;
font-size: 9px;
line-height: 1.4;
}
.crop-card .out {
display: block;
margin-top: 5px;
color: var(--crop);
font-size: 10px;
font-weight: 800;
}
.quick-actions {
display: flex;
gap: 6px;
flex-wrap: wrap;
margin: 10px 0;
}
.small-button,
.primary-button,
.secondary-button {
border-radius: 7px;
cursor: pointer;
transition: filter .12s, transform .12s;
}
.small-button:hover,
.primary-button:hover,
.secondary-button:hover { filter: brightness(1.08); }
.small-button {
padding: 6px 9px;
border: 1px solid #506a6f;
background: #25383d;
color: #dce8e2;
font-size: 10px;
}
.primary-button {
width: 100%;
padding: 11px 12px;
border: 1px solid #f1d78e;
background: var(--accent);
color: #2b3028;
font-weight: 900;
box-shadow: 0 4px 0 #8d743e;
}
.primary-button:disabled {
cursor: not-allowed;
opacity: .43;
filter: grayscale(.45);
box-shadow: none;
}
#plan-status {
margin: 7px 0 0;
text-align: center;
color: var(--muted);
font-size: 10px;
}
.table-wrap {
overflow-x: auto;
border: 1px solid #40585d;
border-radius: 8px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th, td {
padding: 7px 6px;
border-bottom: 1px solid #405358;
text-align: right;
white-space: nowrap;
}
th {
background: #192a2f;
color: #b9cbc4;
font-size: 9px;
text-transform: uppercase;
letter-spacing: .04em;
}
th:first-child, td:first-child { text-align: left; }
tr:last-child td { border-bottom: 0; }
tbody tr:hover { background: #ffffff06; }
.crop-dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 5px;
border-radius: 2px;
background: var(--dot);
}
.total-row td {
background: #192a2f;
font-weight: 900;
}
#plot-detail {
min-height: 105px;
padding: 11px;
border: 1px solid #496166;
border-radius: 8px;
background: #192b30;
color: #c8d6d1;
font-size: 11px;
line-height: 1.55;
}
#plot-detail strong { color: #f2f4e9; }
.detail-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
margin-top: 7px;
}
.detail-grid span {
padding: 5px 6px;
border-radius: 5px;
background: #25383c;
}
details summary {
cursor: pointer;
color: #e2ebe5;
font-size: 12px;
font-weight: 800;
}
.rules {
margin-top: 10px;
color: #bfcec9;
font-size: 11px;
line-height: 1.55;
}
.rules ul {
margin: 8px 0;
padding-left: 18px;
}
.rule-table {
margin-top: 9px;
font-size: 9px;
}
.rule-table th, .rule-table td {
padding: 6px 5px;
}
.tag {
display: inline-block;
padding: 2px 5px;
margin: 1px;
border-radius: 4px;
background: #354a4f;
color: #dfe9e4;
font-size: 9px;
}
#end-overlay {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
padding: 20px;
background: #14252d99;
backdrop-filter: blur(4px);
}
#end-overlay.hidden { display: none; }
.end-card {
width: min(420px, 100%);
padding: 22px;
border: 1px solid #90aaa3;
border-radius: 14px;
background: #203238;
box-shadow: 0 18px 55px #0005;
text-align: center;
}
.end-card .result-icon {
width: 52px;
height: 52px;
margin: 0 auto 12px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--green);
color: #173128;
font-size: 28px;
transform: rotate(-6deg);
}
.end-card.fail .result-icon { background: var(--bad); }
.end-card h2 { margin: 0; font-size: 23px; }
.end-card p { color: #c7d5d0; font-size: 12px; line-height: 1.55; }
.end-metrics {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px;
margin: 14px 0;
}
.end-metrics div {
padding: 9px;
border-radius: 7px;
background: #2a4045;
color: #c4d2cd;
font-size: 10px;
}
.end-metrics strong {
display: block;
color: #f1f2e4;
font-size: 16px;
}
.end-actions {
display: flex;
gap: 8px;
margin-top: 14px;
}
.secondary-button {
flex: 1;
padding: 10px;
border: 1px solid #6a8588;
background: #30474c;
color: #eef4eb;
}
@media (max-width: 980px) {
body {
height: auto;
overflow: auto;
}
#app { min-height: 100vh; }
header {
align-items: flex-start;
flex-wrap: wrap;
}
main {
grid-template-columns: 1fr;
}
#scene-wrap {
height: 62vh;
min-height: 430px;
}
aside {
overflow: visible;
border-left: 0;
border-top: 1px solid #40565b;
}
}
@media (max-width: 560px) {
header { padding: 10px 12px; }
.brand p { display: none; }
.top-stats { width: 100%; justify-content: flex-start; }
.stat { flex: 1; min-width: 66px; padding: 6px 8px; }
.stat strong { font-size: 14px; }
.scene-title { left: 10px; top: 10px; }
.scene-title span { display: none; }
.view-tools { right: 10px; top: 10px; }
.scene-help { left: 10px; bottom: 10px; }
.objective-list { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<div>
<h1>Little Rotation</h1>
<p>A four-season voxel farm strategy board</p>
</div>
</div>
<div class="top-stats">
<div class="stat season-stat">
<small>Season</small>
<strong id="season-value">1 / 4</strong>
<div class="season-dots" id="season-dots">
<i></i><i></i><i></i><i></i>
</div>
</div>
<div class="stat">
<small>Farm value</small>
<strong id="coin-value">0</strong>
</div>
<div class="stat">
<small>Avg soil</small>
<strong id="soil-value">2.0</strong>
</div>
<div class="stat">
<small>Max pest</small>
<strong id="pest-value">0</strong>
</div>
<div class="stat">
<small>Crops sold</small>
<strong id="diversity-value">0 / 3</strong>
</div>
</div>
</header>
<main>
<section id="scene-wrap" aria-label="Interactive voxel farm board">
<div class="scene-title">
<strong id="scene-season-title">Season 1 planning</strong>
<span>Drag to orbit · wheel to zoom · right-drag to pan</span>
</div>
<div class="view-tools">
<button id="reset-view" title="Reset camera" aria-label="Reset camera">⌂</button>
</div>
<div id="plot-labels"></div>
<div id="plot-tooltip"></div>
<div id="toast" role="status" aria-live="polite"></div>
<div class="scene-help">
Select a crop, then click a plot. Shift-click a plot to inspect without planting.
</div>
<div id="end-overlay" class="hidden">
<div class="end-card" id="end-card">
<div class="result-icon" id="result-icon">✓</div>
<h2 id="result-title">Harvest complete</h2>
<p id="result-copy"></p>
<div class="end-metrics" id="end-metrics"></div>
<div class="end-actions">
<button class="secondary-button" id="review-board">Review board</button>
<button class="primary-button" id="new-game">New farm</button>
</div>
</div>
</div>
</section>
<aside>
<section class="section">
<h2>Four-season contract</h2>
<div class="objective-card">
<p>
Finish four harvests with a diversified rotation. All rates and market
values are fictional game rules, not agronomic advice.
</p>
<div class="objective-list">
<div class="objective-item" id="goal-coins">Earn 220 value</div>
<div class="objective-item" id="goal-diversity">Harvest all 3 crops</div>
<div class="objective-item" id="goal-soil">Finish avg soil ≥ 2</div>
<div class="objective-item" id="goal-pests">Finish pests ≤ 3</div>
</div>
</div>
<div class="budgets">
<div class="budget" id="budget-seeds">
<small>Seeds</small><strong id="seed-use">0 / 13</strong>
</div>
<div class="budget" id="budget-labor">
<small>Labor</small><strong id="labor-use">0 / 15</strong>
</div>
<div class="budget" id="budget-water">
<small>Water</small><strong id="water-use">0 / 13</strong>
</div>
</div>
</section>
<section class="section">
<h2>Choose this season's crop</h2>
<div class="crop-grid">
<button class="crop-card selected" data-crop="clover" style="--crop:#79c977">
<span class="crop-icon"></span>
<strong>Clover</strong>
<span class="rate">1 seed · 1 labor<br>1 water</span>
<span class="out">Base output 3</span>
</button>
<button class="crop-card" data-crop="grain" style="--crop:#f1c75b">
<span class="crop-icon"></span>
<strong>Grain</strong>
<span class="rate">2 seed · 2 labor<br>2 water</span>
<span class="out">Base output 5</span>
</button>
<button class="crop-card" data-crop="root" style="--crop:#ed8d50">
<span class="crop-icon"></span>
<strong>Root</strong>
<span class="rate">1 seed · 2 labor<br>1 water</span>
<span class="out">Base output 4</span>
</button>
</div>
<div class="quick-actions">
<button class="small-button" data-fill="clover">Fill clover</button>
<button class="small-button" data-fill="grain">Fill grain</button>
<button class="small-button" data-fill="root">Fill roots</button>
<button class="small-button" id="clear-plan">Clear</button>
</div>
<button class="primary-button" id="end-season">Harvest season 1</button>
<p id="plan-status">Plan all nine plots to continue.</p>
</section>
<section class="section">
<h2>Season ledger</h2>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Crop</th>
<th>Plots</th>
<th>Seed</th>
<th>Labor</th>
<th>Water</th>
<th>Output</th>
<th>Value</th>
</tr>
</thead>
<tbody id="ledger-body"></tbody>
</table>
</div>
</section>
<section class="section">
<h2>Selected plot</h2>
<div id="plot-detail">Select a plot to inspect its projected rotation.</div>
</section>
<section class="section">
<details open>
<summary>Simplified rotation rules</summary>
<div class="rules">
<ul>
<li>Soil <b>N</b> and pest pressure <b>P</b> are clamped to 0–6.</li>
<li>Changing the previous crop gives <b>+1 soil</b>.</li>
<li>Repeating the same crop gives <b>−2 soil, +2 pests, −1 output</b>.</li>
<li>Final output gets <b>+1</b> at soil ≥ 4, <b>−1</b> at pests ≥ 3,
and another <b>−1</b> at pests ≥ 5. Output cannot fall below zero.</li>
</ul>
<div class="table-wrap">
<table class="rule-table">
<thead>
<tr><th>Crop</th><th>Base soil</th><th>Base pests</th><th>Base output</th><th>Value</th></tr>
</thead>
<tbody>
<tr><td><span class="crop-dot" style="--dot:#79c977"></span>Clover</td><td>+2</td><td>−1</td><td>3</td><td>2</td></tr>
<tr><td><span class="crop-dot" style="--dot:#f1c75b"></span>Grain</td><td>−1</td><td>+1</td><td>5</td><td>3</td></tr>
<tr><td><span class="crop-dot" style="--dot:#ed8d50"></span>Root</td><td>0</td><td>+1</td><td>4</td><td>2</td></tr>
</tbody>
</table>
</div>
</div>
</details>
</section>
<section class="section">
<details open>
<summary>Harvest history</summary>
<div class="table-wrap" style="margin-top:9px">
<table>
<thead>
<tr>
<th>S</th>
<th>Seed/Labor/Water</th>
<th>Clover/Grain/Root</th>
<th>Value</th>
<th>Avg N</th>
<th>Max P</th>
</tr>
</thead>
<tbody id="history-body">
<tr><td colspan="6">No harvests yet.</td></tr>
</tbody>
</table>
</div>
</details>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
Game rules
--------------------------------------------------------------------------- */
const CROPS = {
clover: {
name: "Clover",
code: "C",
color: "#79c977",
seed: 1,
labor: 1,
water: 1,
output: 3,
value: 2,
soil: 2,
pest: -1
},
grain: {
name: "Grain",
code: "G",
color: "#f1c75b",
seed: 2,
labor: 2,
water: 2,
output: 5,
value: 3,
soil: -1,
pest: 1
},
root: {
name: "Root",
code: "R",
color: "#ed8d50",
seed: 1,
labor: 2,
water: 1,
output: 4,
value: 2,
soil: 0,
pest: 1
}
};
const SEASONS = 4;
const BUDGET = { seeds: 13, labor: 15, water: 13 };
const GOAL_COINS = 220;
const clamp = (n, min, max) => Math.max(min, Math.min(max, n));
let plots = [];
let selectedCrop = "clover";
let selectedPlot = 0;
let season = 1;
let coins = 0;
let inventory = { clover: 0, grain: 0, root: 0 };
let history = [];
let gameEnded = false;
function plotName(index) {
return String.fromCharCode(65 + Math.floor(index / 3)) + (index % 3 + 1);
}
function resetGame() {
plots = Array.from({ length: 9 }, (_, index) => ({
index,
current: "clover",
planned: null,
soil: 2,
pest: 0,
rotation: index
}));
selectedCrop = "clover";
selectedPlot = 0;
season = 1;
coins = 0;
inventory = { clover: 0, grain: 0, root: 0 };
history = [];
gameEnded = false;
document.getElementById("end-overlay").classList.add("hidden");
updateAllVisuals();
updateUI();
toast("A new four-season contract is ready.");
}
function projectPlot(plot, cropKey) {
const crop = CROPS[cropKey];
const same = plot.current === cropKey;
const rotationSoil = same ? -2 : 1;
const rotationPest = same ? 2 : 0;
const rotationOutput = same ? -1 : 0;
const soil = clamp(plot.soil + crop.soil + rotationSoil, 0, 6);
const pest = clamp(plot.pest + crop.pest + rotationPest, 0, 6);
let output = crop.output + rotationOutput;
if (soil >= 4) output += 1;
if (pest >= 3) output -= 1;
if (pest >= 5) output -= 1;
output = Math.max(0, output);
return {
crop: cropKey,
same,
soil,
pest,
output,
value: output * crop.value,
seed: crop.seed,
labor: crop.labor,
water: crop.water,
rotationSoil,
rotationPest,
rotationOutput
};
}
function projectSeason() {
const result = {
seeds: 0,
labor: 0,
water: 0,
value: 0,
outputs: { clover: 0, grain: 0, root: 0 },
counts: { clover: 0, grain: 0, root: 0 },
perPlot: Array(9).fill(null),
avgSoil: 0,
maxPest: 0,
planned: 0
};
for (const plot of plots) {
if (!plot.planned) continue;
result.planned++;
const p = projectPlot(plot, plot.planned);
result.perPlot[plot.index] = p;
result.seeds += p.seed;
result.labor += p.labor;
result.water += p.water;
result.outputs[p.crop] += p.output;
result.counts[p.crop]++;
result.value += p.value;
}
const projected = plots.map((plot, index) => result.perPlot[index]);
const valid = projected.filter(Boolean);
result.avgSoil = valid.length
? valid.reduce((sum, p) => sum + p.soil, 0) / valid.length
: 0;
result.maxPest = valid.length ? Math.max(...valid.map(p => p.pest)) : 0;
return result;
}
function commitSeason() {
const projection = projectSeason();
if (projection.planned !== 9) {
toast("Plant all nine plots before harvesting.");
return;
}
if (
projection.seeds > BUDGET.seeds ||
projection.labor > BUDGET.labor ||
projection.water > BUDGET.water
) {
toast("This plan exceeds the season's input budget.");
return;
}
for (const plot of plots) {
const p = projection.perPlot[plot.index];
plot.current = plot.planned;
plot.planned = null;
plot.soil = p.soil;
plot.pest = p.pest;
}
for (const key of Object.keys(inventory)) {
inventory[key] += projection.outputs[key];
}
coins += projection.value;
history.push({
season,
seeds: projection.seeds,
labor: projection.labor,
water: projection.water,
outputs: { ...projection.outputs },
value: projection.value,
avgSoil: projection.avgSoil,
maxPest: projection.maxPest
});
season++;
updateAllVisuals();
updateUI();
if (season > SEASONS) {
gameEnded = true;
showResult();
} else {
toast(`Season ${season - 1} harvested for ${projection.value} value.`);
}
}
function objectiveState() {
const diversity = Object.values(inventory).filter(v => v > 0).length;
const avgSoil = plots.reduce((sum, p) => sum + p.soil, 0) / plots.length;
const maxPest = Math.max(...plots.map(p => p.pest));
return {
diversity,
avgSoil,
maxPest,
coins: coins >= GOAL_COINS,
diversityDone: diversity === 3,
soilDone: avgSoil >= 2,
pestDone: maxPest <= 3
};
}
function showResult() {
const state = objectiveState();
const won = state.coins && state.diversityDone && state.soilDone && state.pestDone;
const overlay = document.getElementById("end-overlay");
const card = document.getElementById("end-card");
overlay.classList.remove("hidden");
card.classList.toggle("fail", !won);
document.getElementById("result-icon").textContent = won ? "✓" : "!";
document.getElementById("result-title").textContent = won
? "Rotation certified!"
: "The contract is not quite met";
document.getElementById("result-copy").textContent = won
? "Your four seasons balanced input limits, soil health, pest pressure, and crop diversity."
: "Review the ledger and harvest history. A different crop sequence may improve the final farm state.";
document.getElementById("end-metrics").innerHTML = `
<div>Final value<strong>${coins}</strong></div>
<div>Crop types sold<strong>${state.diversity} / 3</strong></div>
<div>Average soil<strong>${state.avgSoil.toFixed(1)}</strong></div>
<div>Maximum pests<strong>${state.maxPest}</strong></div>
`;
}
/* --------------------------------------------------------------------------
UI
--------------------------------------------------------------------------- */
const cropButtons = [...document.querySelectorAll(".crop-card")];
function setSelectedCrop(cropKey) {
selectedCrop = cropKey;
for (const button of cropButtons) {
button.classList.toggle("selected", button.dataset.crop === cropKey);
}
updateUI();
}
function updateUI() {
const projection = projectSeason();
const state = objectiveState();
document.getElementById("season-value").textContent =
gameEnded ? "4 / 4" : `${season} / 4`;
document.getElementById("scene-season-title").textContent =
gameEnded ? "Four seasons complete" : `Season ${season} planning`;
document.getElementById("coin-value").textContent = coins;
document.getElementById("soil-value").textContent = state.avgSoil.toFixed(1);
document.getElementById("pest-value").textContent = state.maxPest;
document.getElementById("diversity-value").textContent = `${state.diversity} / 3`;
const dots = [...document.querySelectorAll("#season-dots i")];
dots.forEach((dot, index) => {
dot.classList.toggle("done", index < history.length);
dot.classList.toggle("current", !gameEnded && index === season - 1);
});
document.getElementById("seed-use").textContent = `${projection.seeds} / ${BUDGET.seeds}`;
document.getElementById("labor-use").textContent = `${projection.labor} / ${BUDGET.labor}`;
document.getElementById("water-use").textContent = `${projection.water} / ${BUDGET.water}`;
document.getElementById("budget-seeds").classList.toggle("over", projection.seeds > BUDGET.seeds);
document.getElementById("budget-labor").classList.toggle("over", projection.labor > BUDGET.labor);
document.getElementById("budget-water").classList.toggle("over", projection.water > BUDGET.water);
document.getElementById("goal-coins").classList.toggle("done", state.coins);
document.getElementById("goal-diversity").classList.toggle("done", state.diversityDone);
document.getElementById("goal-soil").classList.toggle("done", state.soilDone);
document.getElementById("goal-pests").classList.toggle("done", state.pestDone);
const ledger = document.getElementById("ledger-body");
ledger.innerHTML = Object.entries(CROPS).map(([key, crop]) => {
const count = projection.counts[key];
const output = projection.outputs[key];
const value = output * crop.value;
return `
<tr>
<td><span class="crop-dot" style="--dot:${crop.color}"></span>${crop.name}</td>
<td>${count}</td>
<td>${count * crop.seed}</td>
<td>${count * crop.labor}</td>
<td>${count * crop.water}</td>
<td>${output}</td>
<td>${value}</td>
</tr>
`;
}).join("") + `
<tr class="total-row">
<td>Total</td>
<td>${projection.planned}</td>
<td>${projection.seeds}</td>
<td>${projection.labor}</td>
<td>${projection.water}</td>
<td>${Object.values(projection.outputs).reduce((a, b) => a + b, 0)}</td>
<td>${projection.value}</td>
</tr>
`;
const endButton = document.getElementById("end-season");
const overBudget =
projection.seeds > BUDGET.seeds ||
projection.labor > BUDGET.labor ||
projection.water > BUDGET.water;
endButton.disabled = gameEnded || projection.planned !== 9 || overBudget;
endButton.textContent = gameEnded ? "Harvest complete" : `Harvest season ${season}`;
const status = document.getElementById("plan-status");
if (gameEnded) {
status.textContent = "Review the board or start a new contract.";
} else if (projection.planned !== 9) {
status.textContent = `${9 - projection.planned} plot${9 - projection.planned === 1 ? "" : "s"} still unplanted.`;
} else if (overBudget) {
status.textContent = "Over budget: change the highlighted input totals.";
} else {
status.textContent = `Ready: ${projection.planned} plots, projected ${projection.value} value.`;
}
updateHistory();
updatePlotDetail();
updatePlotLabels();
}
function updateHistory() {
const body = document.getElementById("history-body");
if (!history.length) {
body.innerHTML = '<tr><td colspan="6">No harvests yet.</td></tr>';
return;
}
body.innerHTML = history.map(h => `
<tr>
<td>${h.season}</td>
<td>${h.seeds}/${h.labor}/${h.water}</td>
<td>${h.outputs.clover}/${h.outputs.grain}/${h.outputs.root}</td>
<td>${h.value}</td>
<td>${h.avgSoil.toFixed(1)}</td>
<td>${h.maxPest}</td>
</tr>
`).join("");
}
function updatePlotDetail() {
const detail = document.getElementById("plot-detail");
const plot = plots[selectedPlot];
const current = CROPS[plot.current];
const plannedKey = plot.planned;
if (!plannedKey) {
detail.innerHTML = `
<strong>Plot ${plotName(plot.index)}</strong><br>
Previous crop: <span style="color:${current.color}">${current.name}</span><br>
Current soil: ${plot.soil} · pests: ${plot.pest}<br>
<span style="color:#91aaa4">Choose a crop card, then click this plot to plant it.</span>
`;
return;
}
const p = projectPlot(plot, plannedKey);
const crop = CROPS[plannedKey];
const rotationText = p.same
? "Repeat penalty: −2 soil, +2 pests, −1 output"
: "Rotation bonus: +1 soil";
detail.innerHTML = `
<strong>Plot ${plotName(plot.index)}</strong> · ${crop.name}<br>
${current.name} → ${crop.name}: ${rotationText}<br>
Inputs: ${p.seed} seed · ${p.labor} labor · ${p.water} water<br>
<div class="detail-grid">
<span>Projected output<br><strong>${p.output} ${crop.name.toLowerCase()}</strong></span>
<span>Projected value<br><strong>${p.value}</strong></span>
<span>Soil after harvest<br><strong>${p.soil}</strong></span>
<span>Pests after harvest<br><strong>${p.pest}</strong></span>
</div>
`;
}
let toastTimer;
function toast(message) {
const element = document.getElementById("toast");
element.textContent = message;
element.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => element.classList.remove("show"), 2200);
}
/* --------------------------------------------------------------------------
Three.js scene
--------------------------------------------------------------------------- */
const sceneWrap = document.getElementById("scene-wrap");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d4cb);
scene.fog = new THREE.Fog(0xb9d4cb, 12, 24);
const camera = new THREE.OrthographicCamera(-5, 5, 4, -4, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneWrap.prepend(renderer.domElement);
const ambient = new THREE.HemisphereLight(0xe8f6ed, 0x69513d, 2.25);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff0c8, 3.1);
sun.position.set(-5, 9, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -7;
sun.shadow.camera.right = 7;
sun.shadow.camera.top = 7;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 22;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0xb6dce0, 1.1);
rimLight.position.set(7, 5, -6);
scene.add(rimLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({ color, roughness: 0.86, metalness: 0, ...options });
const materials = {
dirt: material(0x76533b),
dirtDark: material(0x5f422f),
grass: material(0x7ca35f),
grassLight: material(0x91b76e),
path: material(0xc3a979),
wood: material(0x7d5536),
woodLight: material(0xa67447),
barn: material(0xa8493d),
barnDark: material(0x74352f),
roof: material(0x374a4c),
silo: material(0xaebbb4),
siloDark: material(0x778883),
fence: material(0xe1c68f),
leaf: material(0x4f9d50),
leafLight: material(0x72bd62),
leafDark: material(0x35773e),
flower: material(0xeaa5bc),
grain: material(0xe3b949),
grainLight: material(0xf5d774),
root: material(0xd76f37),
rootLight: material(0xf19a55),
pest: material(0xd84987, { emissive: 0x4b092d, emissiveIntensity: 0.35 }),
marker: material(0x77d7d0, { emissive: 0x1b7775, emissiveIntensity: 0.45 }),
markerDark: material(0x397d7b),
soilLow: material(0x9a704e),
soilMid: material(0x765039),
soilHigh: material(0x4e392b)
};
function box(parent, mat, x, y, z, sx, sy, sz, shadow = true) {
const mesh = new THREE.Mesh(unitBox, mat);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const farm = new THREE.Group();
scene.add(farm);
box(farm, materials.dirtDark, 0, -0.52, 0, 5.7, 0.72, 5.7);
box(farm, materials.dirt, 0, -0.20, 0, 5.65, 0.18, 5.65);
box(farm, materials.grass, 0, -0.07, 0, 5.58, 0.14, 5.58);
box(farm, materials.grassLight, 0, -0.02, 0, 5.38, 0.07, 5.38);
const plotVisuals = [];
const hitTargets = [];
const spacing = 1.45;
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
const index = row * 3 + col;
const x = (col - 1) * spacing;
const z = (row - 1) * spacing;
const group = new THREE.Group();
group.position.set(x, 0, z);
farm.add(group);
const tileMaterial = materials.soilMid.clone();
const tile = box(group, tileMaterial, 0, 0.10, 0, 1.13, 0.20, 1.13);
const edgeMaterial = materials.dirtDark;
box(group, edgeMaterial, 0, 0.015, -0.54, 1.17, 0.06, 0.08);
box(group, edgeMaterial, 0, 0.015, 0.54, 1.17, 0.06, 0.08);
box(group, edgeMaterial, -0.54, 0.015, 0, 0.08, 0.06, 1.17);
box(group, edgeMaterial, 0.54, 0.015, 0, 0.08, 0.06, 1.17);
const cropGroup = new THREE.Group();
cropGroup.position.y = 0.20;
group.add(cropGroup);
const pestGroup = new THREE.Group();
pestGroup.position.y = 0.20;
group.add(pestGroup);
const signGroup = new THREE.Group();
group.add(signGroup);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const hit = new THREE.Mesh(unitBox, hitMaterial);
hit.position.y = 0.45;
hit.scale.set(1.16, 0.9, 1.16);
hit.userData.plotIndex = index;
group.add(hit);
hitTargets.push(hit);
plotVisuals.push({
group,
tile,
tileMaterial,
cropGroup,
pestGroup,
signGroup,
worldPosition: new THREE.Vector3(x, 0.78, z)
});
}
}
// Small voxel barn.
const barn = new THREE.Group();
barn.position.set(2.04, 0, -1.97);
farm.add(barn);
box(barn, materials.barn, 0, 0.38, 0, 0.76, 0.76, 0.72);
box(barn, materials.barnDark, 0, 0.04, 0, 0.88, 0.08, 0.84);
box(barn, materials.roof, 0, 0.83, 0, 0.96, 0.16, 0.86);
box(barn, materials.roof, 0, 0.97, 0, 0.68, 0.16, 0.78);
box(barn, materials.wood, 0, 0.30, 0.37, 0.32, 0.55, 0.06);
box(barn, materials.fence, 0.10, 0.30, 0.41, 0.03, 0.03, 0.03);
box(barn, materials.fence, -0.10, 0.30, 0.41, 0.03, 0.03, 0.03);
// Stacked-box silo.
const silo = new THREE.Group();
silo.position.set(-2.03, 0, -1.97);
farm.add(silo);
box(silo, materials.siloDark, 0, 0.09, 0, 0.63, 0.18, 0.63);
box(silo, materials.silo, 0, 0.37, 0, 0.50, 0.48, 0.50);
box(silo, materials.silo, 0, 0.70, 0, 0.39, 0.18, 0.39);
box(silo, materials.siloDark, 0, 0.84, 0, 0.50, 0.12, 0.50);
// Voxel trees.
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
farm.add(tree);
box(tree, materials.wood, 0, 0.28, 0, 0.16, 0.56, 0.16);
box(tree, materials.leafDark, 0, 0.67, 0, 0.63, 0.40, 0.63);
box(tree, materials.leaf, 0, 0.91, 0, 0.47, 0.35, 0.47);
box(tree, materials.leafLight, 0.12, 1.10, -0.04, 0.28, 0.25, 0.28);
}
addTree(-2.15, 2.04, 0.85);
addTree(2.16, 2.08, 0.72);
// Fence along two sides.
for (let i = -2; i <= 2; i++) {
const x = i * 1.08;
box(farm, materials.fence, x, 0.23, -2.55, 0.09, 0.46, 0.09);
if (i < 2) {
box(farm, materials.fence, x + 0.54, 0.31, -2.55, 1.08, 0.08, 0.07);
box(farm, materials.fence, x + 0.54, 0.15, -2.55, 1.08, 0.07, 0.06);
}
}
for (let i = -2; i <= 2; i++) {
const z = i * 1.08;
box(farm, materials.fence, -2.55, 0.23, z, 0.09, 0.46, 0.09);
if (i < 2) {
box(farm, materials.fence, -2.55, 0.31, z + 0.54, 0.07, 0.08, 1.08);
box(farm, materials.fence, -2.55, 0.15, z + 0.54, 0.06, 0.07, 1.08);
}
}
// Selection outline.
const selectionGroup = new THREE.Group();
scene.add(selectionGroup);
const selectionMat = new THREE.MeshBasicMaterial({
color: 0x77d7d0,
transparent: true,
opacity: 0.9,
depthWrite: false
});
box(selectionGroup, selectionMat, 0, 0.235, -0.60, 1.25, 0.025, 0.055, false);
box(selectionGroup, selectionMat, 0, 0.235, 0.60, 1.25, 0.025, 0.055, false);
box(selectionGroup, selectionMat, -0.60, 0.235, 0, 0.055, 0.025, 1.25, false);
box(selectionGroup, selectionMat, 0.60, 0.235, 0, 0.055, 0.025, 1.25, false);
function clearGroup(group) {
while (group.children.length) group.remove(group.children[group.children.length - 1]);
}
function buildCrop(group, cropKey, index) {
const phase = index * 1.73;
if (cropKey === "clover") {
for (let i = 0; i < 5; i++) {
const angle = phase + i * 1.25;
const x = Math.cos(angle) * (0.17 + (i % 2) * 0.07);
const z = Math.sin(angle) * (0.17 + (i % 2) * 0.07);
const height = 0.20 + (i % 3) * 0.055;
box(group, materials.leafDark, x, height / 2, z, 0.055, height, 0.055);
box(group, i % 2 ? materials.leaf : materials.leafLight,
x, height * 0.78, z, 0.20, 0.08, 0.12);
box(group, materials.flower,
x, height + 0.035, z, 0.115, 0.075, 0.115);
}
}
if (cropKey === "grain") {
for (let i = 0; i < 6; i++) {
const x = ((i % 3) - 1) * 0.17 + Math.sin(phase) * 0.025;
const z = (Math.floor(i / 3) - 0.5) * 0.24 + Math.cos(phase) * 0.025;
const height = 0.43 + (i % 2) * 0.08;
box(group, materials.grain, x, height / 2, z, 0.045, height, 0.045);
box(group, materials.grainLight, x, height + 0.07, z, 0.12, 0.14, 0.10);
box(group, materials.grainLight, x + 0.04, height + 0.01, z, 0.09, 0.10, 0.09);
}
}
if (cropKey === "root") {
box(group, materials.root, 0, 0.08, 0, 0.23, 0.16, 0.23);
box(group, materials.rootLight, 0.05, 0.12, -0.03, 0.14, 0.13, 0.13);
for (let i = 0; i < 4; i++) {
const angle = phase + i * 1.55;
const x = Math.cos(angle) * 0.12;
const z = Math.sin(angle) * 0.12;
const h = 0.28 + (i % 2) * 0.08;
box(group, materials.leafDark, x, h / 2, z, 0.055, h, 0.055);
box(group, i % 2 ? materials.leaf : materials.leafLight,
x + 0.07, h * 0.78, z, 0.18, 0.075, 0.11);
box(group, materials.leafLight,
x, h * 0.92, z + 0.06, 0.10, 0.08, 0.18);
}
}
}
function updatePlotVisual(index) {
const plot = plots[index];
const visual = plotVisuals[index];
const shownCrop = plot.planned || plot.current;
clearGroup(visual.cropGroup);
buildCrop(visual.cropGroup, shownCrop, index);
clearGroup(visual.pestGroup);
if (plot.pest >= 3) {
const count = Math.min(4, plot.pest - 1);
for (let i = 0; i < count; i++) {
const fly = box(visual.pestGroup, materials.pest,
Math.sin(index + i * 2.1) * 0.33,
0.48 + (i % 2) * 0.15,
Math.cos(index * 0.7 + i * 1.7) * 0.33,
0.065, 0.065, 0.065, false);
fly.userData.flyOffset = i * 1.7;
}
}
clearGroup(visual.signGroup);
if (plot.planned && plot.planned !== plot.current) {
box(visual.signGroup, materials.marker, 0.43, 0.34, -0.43, 0.09, 0.28, 0.09);
box(visual.signGroup, materials.markerDark, 0.43, 0.49, -0.43, 0.25, 0.15, 0.06);
}
const low = new THREE.Color(0x9a704e);
const mid = new THREE.Color(0x765039);
const high = new THREE.Color(0x4e392b);
const color = plot.soil <= 3
? low.clone().lerp(mid, plot.soil / 3)
: mid.clone().lerp(high, (plot.soil - 3) / 3);
visual.tileMaterial.color.copy(color);
}
function updateAllVisuals() {
for (let i = 0; i < plots.length; i++) updatePlotVisual(i);
updateSelection();
}
function updateSelection() {
const visual = plotVisuals[selectedPlot];
selectionGroup.position.copy(visual.group.position);
}
/* --------------------------------------------------------------------------
DOM labels
--------------------------------------------------------------------------- */
const labelElements = [];
for (let i = 0; i < 9; i++) {
const label = document.createElement("button");
label.className = "plot-label";
label.type = "button";
label.addEventListener("click", event => {
event.stopPropagation();
selectedPlot = i;
if (!event.shiftKey && !gameEnded) assignPlot(i, selectedCrop);
else {
updateSelection();
updateUI();
}
});
document.getElementById("plot-labels").appendChild(label);
labelElements.push(label);
}
function updatePlotLabels() {
for (let i = 0; i < plots.length; i++) {
const plot = plots[i];
const label = labelElements[i];
const current = CROPS[plot.current];
const planned = plot.planned ? CROPS[plot.planned] : null;
label.innerHTML = `
${plotName(i)} · ${current.code}
<span class="plan">${planned ? `${current.code} → ${planned.code} · N${plot.soil}/P${plot.pest}` : `N${plot.soil} / P${plot.pest}`}</span>
`;
label.classList.toggle("selected", selectedPlot === i);
label.style.borderColor = planned ? planned.color : "#d7e4dd99";
}
}
const projectedPoint = new THREE.Vector3();
function positionLabels() {
const width = sceneWrap.clientWidth;
const height = sceneWrap.clientHeight;
for (let i = 0; i < labelElements.length; i++) {
projectedPoint.copy(plotVisuals[i].worldPosition).project(camera);
const x = (projectedPoint.x * 0.5 + 0.5) * width;
const y = (-projectedPoint.y * 0.5 + 0.5) * height;
const visible = projectedPoint.z > -1 && projectedPoint.z < 1;
labelElements[i].style.display = visible ? "block" : "none";
labelElements[i].style.left = `${x}px`;
labelElements[i].style.top = `${y}px`;
}
}
/* --------------------------------------------------------------------------
Interaction and custom camera controls
--------------------------------------------------------------------------- */
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const tooltip = document.getElementById("plot-tooltip");
function pickPlot(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;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(hitTargets, false);
return hits.length ? hits[0].object.userData.plotIndex : null;
}
function assignPlot(index, cropKey) {
if (gameEnded) return;
plots[index].planned = cropKey;
selectedPlot = index;
updatePlotVisual(index);
updateSelection();
updateUI();
}
let dragging = false;
let dragged = false;
let dragButton = 0;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragged = false;
dragButton = event.button;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (dragging) {
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 1) dragged = true;
if (dragButton === 2 || event.shiftKey) {
const scale = 0.006 / camera.zoom;
const right = new THREE.Vector3(Math.cos(orbit.theta), 0, -Math.sin(orbit.theta));
const forward = new THREE.Vector3(-Math.sin(orbit.theta), 0, -Math.cos(orbit.theta));
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
} else {
orbit.theta -= dx * 0.007;
orbit.phi = clamp(orbit.phi - dy * 0.006, 0.30, 1.35);
}
updateCamera();
tooltip.style.display = "none";
return;
}
const index = pickPlot(event);
if (index === null) {
tooltip.style.display = "none";
return;
}
const plot = plots[index];
const crop = CROPS[plot.planned || plot.current];
const rect = sceneWrap.getBoundingClientRect();
tooltip.innerHTML = `
<strong>Plot ${plotName(index)} · ${crop.name}</strong><br>
Soil ${plot.soil} · Pests ${plot.pest}<br>
${plot.planned ? `Planned: ${crop.name}` : `Current: ${crop.name}`}<br>
<span style="color:#a9c2bc">Click to plant the selected crop.</span>
`;
tooltip.style.display = "block";
tooltip.style.left = `${clamp(event.clientX - rect.left + 13, 8, rect.width - 238)}px`;
tooltip.style.top = `${clamp(event.clientY - rect.top + 13, 8, rect.height - 92)}px`;
});
renderer.domElement.addEventListener("pointerup", event => {
if (dragging && !dragged && event.button === 0) {
const index = pickPlot(event);
if (index !== null) {
selectedPlot = index;
if (!event.shiftKey && !gameEnded) assignPlot(index, selectedCrop);
else {
updateSelection();
updateUI();
}
}
}
dragging = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
dragging = false;
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = clamp(camera.zoom * Math.exp(-event.deltaY * 0.001), 0.65, 2.7);
camera.updateProjectionMatrix();
updateCamera();
}, { passive: false });
const orbit = {
theta: 0.72,
phi: 0.88,
radius: 10,
target: new THREE.Vector3(0, 0.15, 0)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.theta = 0.72;
orbit.phi = 0.88;
orbit.radius = 10;
orbit.target.set(0, 0.15, 0);
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
}
function resize() {
const width = sceneWrap.clientWidth;
const height = sceneWrap.clientHeight;
const aspect = width / Math.max(1, height);
const viewSize = 6.9;
camera.left = -viewSize * aspect / 2;
camera.right = viewSize * aspect / 2;
camera.top = viewSize / 2;
camera.bottom = -viewSize / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
new ResizeObserver(resize).observe(sceneWrap);
/* --------------------------------------------------------------------------
Buttons
--------------------------------------------------------------------------- */
for (const button of cropButtons) {
button.addEventListener("click", () => setSelectedCrop(button.dataset.crop));
}
for (const button of document.querySelectorAll("[data-fill]")) {
button.addEventListener("click", () => {
if (gameEnded) return;
const cropKey = button.dataset.fill;
for (const plot of plots) plot.planned = cropKey;
updateAllVisuals();
updateUI();
});
}
document.getElementById("clear-plan").addEventListener("click", () => {
if (gameEnded) return;
for (const plot of plots) plot.planned = null;
updateAllVisuals();
updateUI();
});
document.getElementById("end-season").addEventListener("click", commitSeason);
document.getElementById("reset-view").addEventListener("click", resetCamera);
document.getElementById("new-game").addEventListener("click", resetGame);
document.getElementById("review-board").addEventListener("click", () => {
document.getElementById("end-overlay").classList.add("hidden");
});
document.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "1") setSelectedCrop("clover");
if (event.key === "2") setSelectedCrop("grain");
if (event.key === "3") setSelectedCrop("root");
});
/* --------------------------------------------------------------------------
Render loop
--------------------------------------------------------------------------- */
const clock = new THREE.Clock();
function animate() {
const time = clock.getElapsedTime();
for (const visual of plotVisuals) {
for (const child of visual.pestGroup.children) {
const offset = child.userData.flyOffset || 0;
child.position.x += Math.sin(time * 2.5 + offset) * 0.0018;
child.position.y += Math.cos(time * 3.1 + offset) * 0.0012;
}
}
selectionMat.opacity = 0.72 + Math.sin(time * 4) * 0.18;
positionLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resetGame();
resize();
updateCamera();
animate();
</script>
</body>
</html>
```