Prompt specification
Build or customize the Three.js 3D scene "Market-stall counting play" 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: Market-stall counting play
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/market-stall-counting-play-x0327
Scene Description Prompt:
Trade voxel fruit between baskets and a toy market counter, moving exactly one counting bead per exchange. Three.js from cdnjs, one HTML file.
Technical checks: Keep fruit and beads lit and distinguishable throughout the exchange. A pear exchanged for one bead movement should preserve the total of nine.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (market-stall-counting-play-x0327):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mercadinho de Contagem</title>
<style>
:root {
color-scheme: light;
--ink: #17324d;
--muted: #5d6f7e;
--paper: rgba(255, 253, 247, 0.94);
--line: rgba(23, 50, 77, 0.13);
--green: #168b77;
--coral: #ef625f;
--gold: #f5bd3d;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #efe8d9;
color: var(--ink);
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button { font: inherit; }
#app, #app canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#app canvas {
cursor: grab;
touch-action: none;
}
#app canvas:active { cursor: grabbing; }
.panel {
background: var(--paper);
border: 1px solid var(--line);
box-shadow: 0 14px 38px rgba(34, 54, 67, 0.14);
backdrop-filter: blur(12px);
}
#heading {
position: fixed;
top: 18px;
left: 18px;
z-index: 5;
max-width: min(470px, calc(100vw - 230px));
padding: 15px 18px;
border-radius: 20px;
pointer-events: none;
}
#heading h1 {
margin: 0;
font-size: clamp(20px, 2.2vw, 31px);
line-height: 1.05;
letter-spacing: -0.035em;
}
#heading p {
margin: 8px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.35;
}
.eyebrow {
display: inline-block;
margin-bottom: 7px;
color: var(--green);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#score {
position: fixed;
top: 18px;
right: 18px;
z-index: 5;
width: 210px;
padding: 14px 16px;
border-radius: 20px;
pointer-events: none;
}
.score-label {
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#total {
display: block;
margin: 1px 0 2px;
color: var(--coral);
font-size: 58px;
font-weight: 900;
line-height: 1;
letter-spacing: -0.06em;
}
#beadStatus {
color: var(--ink);
font-size: 12px;
font-weight: 750;
}
#exchangeState {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
line-height: 1.3;
}
#controls {
position: fixed;
z-index: 7;
left: 50%;
bottom: 18px;
width: min(760px, calc(100vw - 36px));
transform: translateX(-50%);
padding: 13px 15px;
border-radius: 20px;
}
.control-main {
display: flex;
align-items: center;
gap: 12px;
}
.selection {
min-width: 180px;
flex: 1 1 auto;
}
.selection small {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#selectedFruit {
font-size: 15px;
font-weight: 850;
line-height: 1.25;
}
.actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.action {
min-height: 44px;
border: 0;
border-radius: 13px;
padding: 10px 15px;
color: white;
font-weight: 850;
cursor: pointer;
box-shadow: 0 5px 0 rgba(20, 45, 60, 0.16);
transition: transform 120ms ease, filter 120ms ease, opacity 120ms ease;
}
.action:hover:not(:disabled) {
transform: translateY(-2px);
filter: brightness(1.04);
}
.action:active:not(:disabled) {
transform: translateY(2px);
box-shadow: 0 2px 0 rgba(20, 45, 60, 0.16);
}
.action:disabled {
opacity: 0.38;
cursor: not-allowed;
box-shadow: none;
}
#tradeButton { background: var(--green); }
#returnButton { background: var(--coral); }
#resetButton { background: #71869a; }
#history {
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
white-space: pre-line;
}
#cameraHelp {
position: fixed;
right: 18px;
bottom: 164px;
z-index: 4;
padding: 8px 11px;
border-radius: 999px;
color: var(--muted);
background: rgba(255, 253, 247, 0.8);
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 720px) {
#heading {
top: 10px;
left: 10px;
max-width: calc(100vw - 138px);
padding: 11px 13px;
border-radius: 16px;
}
#heading p { display: none; }
#heading h1 { font-size: 19px; }
#score {
top: 10px;
right: 10px;
width: 118px;
padding: 10px 11px;
border-radius: 16px;
}
#total { font-size: 42px; }
#beadStatus { font-size: 10px; }
#exchangeState { display: none; }
#controls {
bottom: 10px;
width: calc(100vw - 20px);
padding: 11px;
border-radius: 16px;
}
.control-main {
align-items: stretch;
flex-direction: column;
gap: 8px;
}
.selection { min-width: 0; }
.actions { justify-content: stretch; }
.action { flex: 1 1 auto; padding: 9px 10px; font-size: 12px; }
#history { font-size: 10px; }
#cameraHelp { display: none; }
}
</style>
</head>
<body>
<div id="app" aria-label="Mercado tridimensional de frutas e contas"></div>
<header id="heading" class="panel">
<span class="eyebrow">Aprenda trocando</span>
<h1>Mercadinho de Contagem</h1>
<p>Escolha uma fruta, passe pela banca e mova exatamente uma conta de contagem.</p>
</header>
<section id="score" class="panel" aria-live="polite">
<span class="score-label">Total na cesta</span>
<output id="total">9</output>
<div id="beadStatus">9 contas na régua · 0 na bandeja</div>
<div id="exchangeState">Pronto para trocar.</div>
</section>
<section id="controls" class="panel" aria-label="Controles da atividade">
<div class="control-main">
<div class="selection">
<small>Fruta selecionada</small>
<div id="selectedFruit">Pera · cesta da esquerda</div>
</div>
<div class="actions">
<button id="tradeButton" class="action" type="button">Trocar Pera</button>
<button id="returnButton" class="action" type="button" disabled>Devolver</button>
<button id="resetButton" class="action" type="button">Reiniciar</button>
</div>
</div>
<div id="history">Clique em uma fruta e depois em “Trocar”. Cada troca move 1 conta.</div>
</section>
<div id="cameraHelp">Arraste para girar · use a roda para aproximar</div>
<div id="live" class="sr-only" aria-live="assertive"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const app = document.getElementById("app");
const totalOutput = document.getElementById("total");
const beadStatus = document.getElementById("beadStatus");
const exchangeState = document.getElementById("exchangeState");
const selectedFruit = document.getElementById("selectedFruit");
const historyOutput = document.getElementById("history");
const liveOutput = document.getElementById("live");
const tradeButton = document.getElementById("tradeButton");
const returnButton = document.getElementById("returnButton");
const resetButton = document.getElementById("resetButton");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xefe8d9);
scene.fog = new THREE.Fog(0xefe8d9, 20, 42);
const camera = new THREE.PerspectiveCamera(46, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const cameraTarget = new THREE.Vector3(0, 1.45, 0);
const cameraState = {
azimuth: 0.22,
elevation: 0.43,
zoom: 1
};
function updateCamera() {
const fitDistance = Math.max(14.2, 13.6 / camera.aspect);
const distance = fitDistance * cameraState.zoom;
const horizontal = Math.cos(cameraState.elevation) * distance;
camera.position.set(
cameraTarget.x + Math.sin(cameraState.azimuth) * horizontal,
cameraTarget.y + Math.sin(cameraState.elevation) * distance,
cameraTarget.z + Math.cos(cameraState.azimuth) * horizontal
);
camera.lookAt(cameraTarget);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
}
window.addEventListener("resize", resize);
// Iluminação explícita: a cena permanece clara em todos os estados.
const hemisphere = new THREE.HemisphereLight(0xfff9e9, 0x7187a0, 2.5);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(-4, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xbddcff, 1.45);
fillLight.position.set(7, 6, -5);
scene.add(fillLight);
const warmLight = new THREE.PointLight(0xffd58a, 1.1, 18, 2);
warmLight.position.set(0, 5, 4);
scene.add(warmLight);
const standard = (color, roughness = 0.72, metalness = 0) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
function addBox(parent, sx, sy, sz, x, y, z, colorOrMaterial, options = {}) {
const material = colorOrMaterial instanceof THREE.Material
? colorOrMaterial
: standard(colorOrMaterial, options.roughness ?? 0.72, options.metalness ?? 0);
const mesh = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), material);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
if (options.rotation) mesh.rotation.set(...options.rotation);
parent.add(mesh);
return mesh;
}
function makeTextPlane(text, width, height, background = "#ffffff", foreground = "#17324d") {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 192;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
if (background) {
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.fillStyle = foreground;
context.font = "900 66px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
return mesh;
}
// Piso e plataforma.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
standard(0xd9e2d0, 0.94)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.28;
ground.receiveShadow = true;
scene.add(ground);
addBox(scene, 14.4, 0.18, 7.1, 0, -0.16, 0, 0xf5e9d2);
addBox(scene, 13.7, 0.035, 6.45, 0, -0.052, 0, 0xeee0c4);
const tileColors = [0xe7d5b5, 0xdce7d3, 0xf3d6bf, 0xd8e6e2];
let tileIndex = 0;
for (let x = -6; x <= 6; x += 2) {
for (let z = -2; z <= 2; z += 2) {
addBox(
scene,
1.72,
0.018,
1.72,
x,
-0.022,
z,
tileColors[tileIndex++ % tileColors.length],
{ castShadow: false }
);
}
}
function createBasket(x, z, label, accentColor) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
const wicker = 0xb9793f;
const darkWicker = 0x8b552e;
addBox(group, 2.28, 0.2, 1.62, 0, 0.15, 0, darkWicker);
addBox(group, 2.08, 0.12, 1.43, 0, 0.29, 0, wicker);
for (const y of [0.48, 0.77, 1.06]) {
addBox(group, 2.26, 0.14, 0.13, 0, y, 0.79, wicker);
addBox(group, 2.26, 0.14, 0.13, 0, y, -0.79, wicker);
addBox(group, 0.13, 0.14, 1.58, -1.08, y, 0, wicker);
addBox(group, 0.13, 0.14, 1.58, 1.08, y, 0, wicker);
}
for (const sx of [-0.92, -0.46, 0, 0.46, 0.92]) {
addBox(group, 0.105, 1.02, 0.105, sx, 0.73, 0.79, darkWicker);
addBox(group, 0.105, 1.02, 0.105, sx, 0.73, -0.79, darkWicker);
}
for (const sz of [-0.52, 0, 0.52]) {
addBox(group, 0.105, 1.02, 0.105, -1.08, 0.73, sz, darkWicker);
addBox(group, 0.105, 1.02, 0.105, 1.08, 0.73, sz, darkWicker);
}
addBox(group, 2.33, 0.12, 0.18, 0, 1.17, 0.8, accentColor);
addBox(group, 2.33, 0.12, 0.18, 0, 1.17, -0.8, accentColor);
addBox(group, 0.18, 0.12, 1.62, -1.09, 1.17, 0, accentColor);
addBox(group, 0.18, 0.12, 1.62, 1.09, 1.17, 0, accentColor);
const plaque = makeTextPlane(label, 1.25, 0.32, accentColor, "#ffffff");
plaque.position.set(0, 0.76, 0.875);
group.add(plaque);
return group;
}
const LEFT_X = -4.15;
const RIGHT_X = 4.15;
const BASKET_Z = 0.55;
createBasket(LEFT_X, BASKET_Z, "CESTA 1", 0x168b77);
createBasket(RIGHT_X, BASKET_Z, "CESTA 2", 0xef625f);
const slotOffsets = [
[-0.55, 0.39],
[0, 0.39],
[0.55, 0.39],
[-0.55, 0],
[0, 0],
[0.55, 0],
[-0.55, -0.39],
[0, -0.39],
[0.55, -0.39]
];
const leftSlots = slotOffsets.map(([ox, oz]) =>
new THREE.Vector3(LEFT_X + ox, 1.03 + Math.abs(oz) * 0.04, BASKET_Z + oz)
);
const rightSlots = slotOffsets.map(([ox, oz]) =>
new THREE.Vector3(RIGHT_X + ox, 1.03 + Math.abs(oz) * 0.04, BASKET_Z + oz)
);
// Banca central de brinquedo.
const counter = new THREE.Group();
scene.add(counter);
addBox(counter, 4.72, 1.34, 1.7, 0, 0.91, -0.85, 0x168b77);
addBox(counter, 5.05, 0.22, 2.04, 0, 1.67, -0.85, 0xf5dfb5);
addBox(counter, 0.42, 0.34, 0.42, -1.72, 0.19, -0.2, 0x6c4931);
addBox(counter, 0.42, 0.34, 0.42, 1.72, 0.19, -0.2, 0x6c4931);
for (const x of [-1.55, -0.78, 0, 0.78, 1.55]) {
addBox(counter, 0.58, 0.78, 0.055, x, 0.91, 0.018, 0x11705f);
}
addBox(counter, 0.14, 2.0, 0.14, -2.43, 2.7, -1.57, 0x744c32);
addBox(counter, 0.14, 2.0, 0.14, 2.43, 2.7, -1.57, 0x744c32);
addBox(counter, 0.14, 2.0, 0.14, -2.43, 2.7, 0.02, 0x744c32);
addBox(counter, 0.14, 2.0, 0.14, 2.43, 2.7, 0.02, 0x744c32);
const canopyColors = [0xf7f0dc, 0xef625f];
for (let i = 0; i < 9; i++) {
addBox(
counter,
0.59,
0.18,
2.28,
-2.36 + i * 0.59,
3.66,
-0.88,
canopyColors[i % 2]
);
addBox(
counter,
0.59,
0.42,
0.14,
-2.36 + i * 0.59,
3.43,
0.19,
canopyColors[i % 2]
);
}
const exchangeSign = makeTextPlane("1 FRUTA = 1 CONTA", 4.25, 0.55, "#f7f0dc", "#17324d");
exchangeSign.position.set(0, 3.19, 0.275);
counter.add(exchangeSign);
const actionGroups = [];
function createCounterButton(x, text, color, action) {
const group = new THREE.Group();
group.position.set(x, 0.92, 0.085);
group.userData.action = action;
counter.add(group);
addBox(group, 1.34, 0.58, 0.14, 0, 0, 0, color);
const label = makeTextPlane(text, 1.21, 0.38, color, "#ffffff");
label.position.z = 0.076;
group.add(label);
actionGroups.push(group);
}
createCounterButton(-0.87, "TROCAR", 0x168b77, "trade");
createCounterButton(0.87, "DEVOLVER", 0xef625f, "return");
// Régua de contas: oito contas fixas e uma conta coral que se move.
addBox(counter, 5.68, 0.78, 0.18, 0, 2.31, -1.48, 0x244b61);
addBox(counter, 5.82, 0.12, 0.25, 0, 2.75, -1.48, 0xf5dfb5);
const beadSlots = [];
const beadMeshes = [];
for (let i = 0; i < 9; i++) {
const x = -2.22 + i * 0.5;
const slot = new THREE.Vector3(x, 2.31, -1.24);
beadSlots.push(slot);
addBox(counter, 0.34, 0.34, 0.07, x, 2.31, -1.355, 0x102d3d);
const beadMaterial = standard(i === 8 ? 0xff625f : 0xf5c84a, 0.46, 0.06);
const bead = addBox(counter, 0.29, 0.29, 0.27, x, 2.31, -1.22, beadMaterial);
addBox(bead, 0.075, 0.075, 0.025, -0.065, 0.07, 0.145, 0xfff4c9, {
castShadow: false
});
beadMeshes.push(bead);
}
const trayPosition = new THREE.Vector3(2.22, 2.0, -0.14);
addBox(counter, 0.72, 0.09, 0.62, 2.22, 1.79, -0.14, 0xef625f);
addBox(counter, 0.08, 0.34, 0.62, 1.89, 1.94, -0.14, 0xf58b79);
addBox(counter, 0.08, 0.34, 0.62, 2.55, 1.94, -0.14, 0xf58b79);
addBox(counter, 0.72, 0.25, 0.08, 2.22, 1.91, 0.13, 0xf58b79);
addBox(counter, 0.72, 0.25, 0.08, 2.22, 1.91, -0.41, 0xf58b79);
// Frutas voxel.
const fruitRecords = [];
const fruitById = new Map();
const raycastObjects = [];
function createFruit(type) {
const group = new THREE.Group();
if (type === "pear") {
const pear = standard(0xcddd4a, 0.62);
const lightPear = standard(0xe3eb72, 0.62);
addBox(group, 0.34, 0.31, 0.34, 0, 0.16, 0, pear);
addBox(group, 0.45, 0.34, 0.43, 0, 0.45, 0, pear);
addBox(group, 0.34, 0.34, 0.34, 0, 0.74, 0, lightPear);
addBox(group, 0.27, 0.27, 0.28, 0.13, 0.49, 0, lightPear);
addBox(group, 0.1, 0.24, 0.1, 0, 0.99, 0, 0x70452b);
addBox(group, 0.24, 0.075, 0.13, 0.13, 1.04, 0, 0x438a3b, {
rotation: [0, 0.2, -0.35]
});
} else if (type === "apple") {
const apple = standard(0xe84c4c, 0.58);
const appleLight = standard(0xf36b5d, 0.58);
addBox(group, 0.52, 0.43, 0.5, 0, 0.36, 0, apple);
addBox(group, 0.32, 0.36, 0.34, -0.26, 0.35, 0, appleLight);
addBox(group, 0.32, 0.36, 0.34, 0.26, 0.35, 0, appleLight);
addBox(group, 0.34, 0.32, 0.34, 0, 0.66, 0, apple);
addBox(group, 0.09, 0.22, 0.09, 0, 0.86, 0, 0x70452b);
addBox(group, 0.25, 0.07, 0.14, 0.14, 0.88, 0, 0x438a3b, {
rotation: [0, 0.15, -0.3]
});
} else {
const orange = standard(0xf39a32, 0.6);
const orangeLight = standard(0xffb548, 0.6);
addBox(group, 0.57, 0.57, 0.57, 0, 0.32, 0, orange);
addBox(group, 0.4, 0.16, 0.4, 0, 0.65, 0, orangeLight);
addBox(group, 0.1, 0.1, 0.1, 0, 0.77, 0, 0x78502d);
}
const marker = new THREE.Group();
marker.visible = false;
const markerColor = standard(0x244b9b, 0.45);
addBox(marker, 0.78, 0.055, 0.07, 0, 0.03, -0.39, markerColor, { castShadow: false });
addBox(marker, 0.78, 0.055, 0.07, 0, 0.03, 0.39, markerColor, { castShadow: false });
addBox(marker, 0.07, 0.055, 0.78, -0.39, 0.03, 0, markerColor, { castShadow: false });
addBox(marker, 0.07, 0.055, 0.78, 0.39, 0.03, 0, markerColor, { castShadow: false });
group.add(marker);
group.traverse(object => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
return { group, marker };
}
const fruitTypes = [
"pear", "apple", "orange",
"pear", "apple", "orange",
"pear", "apple", "orange"
];
const fruitNames = {
pear: "Pera",
apple: "Maçã",
orange: "Laranja"
};
const leftOccupied = new Set();
const rightOccupied = new Set();
fruitTypes.forEach((type, index) => {
const { group, marker } = createFruit(type);
const id = `fruit-${index}`;
const record = {
id,
type,
name: fruitNames[type],
group,
marker,
side: "left",
slot: index,
homeSlot: index
};
group.position.copy(leftSlots[index]);
group.userData.fruitId = id;
scene.add(group);
leftOccupied.add(index);
fruitRecords.push(record);
fruitById.set(id, record);
raycastObjects.push(group);
});
const state = {
total: 9,
beadsInRow: 9,
selectedId: "fruit-0",
busy: false,
history: ["Clique em uma fruta e depois em “Trocar”. Cada troca move 1 conta."]
};
function selectedRecord() {
return fruitById.get(state.selectedId) || null;
}
function updateHUD() {
totalOutput.textContent = String(state.total);
beadStatus.textContent =
`${state.beadsInRow} ${state.beadsInRow === 1 ? "conta" : "contas"} na régua · ` +
`${9 - state.beadsInRow} na bandeja`;
const record = selectedRecord();
if (record && record.side !== "moving") {
selectedFruit.textContent =
`${record.name} · ${record.side === "left" ? "cesta da esquerda" : "cesta da direita"}`;
} else {
selectedFruit.textContent = "Nenhuma fruta selecionada";
}
tradeButton.disabled = state.busy || !record || record.side !== "left";
returnButton.disabled = state.busy || !record || record.side !== "right";
resetButton.disabled = state.busy;
tradeButton.textContent = record && record.side === "left"
? `Trocar ${record.name}`
: "Trocar";
historyOutput.textContent = state.history.slice(0, 3).join("\n");
}
function selectFruit(record) {
if (!record || state.busy || record.side === "moving") return;
for (const fruit of fruitRecords) fruit.marker.visible = false;
record.marker.visible = true;
state.selectedId = record.id;
updateHUD();
}
// Pequeno gerenciador de animações, sem bibliotecas externas.
const tweens = [];
function tween(duration, update, complete) {
tweens.push({
start: performance.now(),
duration,
update,
complete
});
}
function easeInOutCubic(value) {
return value < 0.5
? 4 * value * value * value
: 1 - Math.pow(-2 * value + 2, 3) / 2;
}
function updateTweens(now) {
for (let i = tweens.length - 1; i >= 0; i--) {
const item = tweens[i];
const progress = Math.min(1, (now - item.start) / item.duration);
item.update(progress);
if (progress >= 1) {
tweens.splice(i, 1);
if (item.complete) item.complete();
}
}
}
function moveActiveBead(destination, duration = 850) {
// Somente a conta coral é movida. As outras oito permanecem imóveis.
const bead = beadMeshes[8];
const origin = bead.position.clone();
const startRotation = bead.rotation.y;
tween(duration, progress => {
const eased = easeInOutCubic(progress);
bead.position.lerpVectors(origin, destination, eased);
bead.position.y += Math.sin(progress * Math.PI) * 0.28;
bead.rotation.y = startRotation + progress * Math.PI * 2;
}, () => {
bead.position.copy(destination);
bead.rotation.y = 0;
});
}
function animateFruit(record, destination, onComplete) {
const start = record.group.position.clone();
const via = new THREE.Vector3(0, 3.12, 0.72);
const curve = new THREE.CatmullRomCurve3([start, via, destination]);
const startRotation = record.group.rotation.y;
tween(1150, progress => {
const eased = easeInOutCubic(progress);
record.group.position.copy(curve.getPoint(eased));
record.group.rotation.y = startRotation + progress * Math.PI * 2;
const scale = 1 + Math.sin(progress * Math.PI) * 0.08;
record.group.scale.setScalar(scale);
}, () => {
record.group.position.copy(destination);
record.group.rotation.set(0, 0, 0);
record.group.scale.setScalar(1);
onComplete();
});
}
function firstFruitOn(side) {
return fruitRecords.find(record => record.side === side) || null;
}
function tradeSelected() {
const record = selectedRecord();
if (state.busy || !record || record.side !== "left") return;
let targetSlot = -1;
for (let i = 0; i < rightSlots.length; i++) {
if (!rightOccupied.has(i)) {
targetSlot = i;
break;
}
}
if (targetSlot < 0) return;
const oldTotal = state.total;
const fruitName = record.name;
state.busy = true;
record.side = "moving";
leftOccupied.delete(record.slot);
state.total = Math.max(0, state.total - 1);
state.beadsInRow = Math.max(0, state.beadsInRow - 1);
exchangeState.textContent = "Trocando: 1 fruta, 1 conta.";
liveOutput.textContent =
`${fruitName}: total ${oldTotal} para ${state.total}. Uma conta se moveu.`;
state.history.unshift(
`${fruitName}: ${oldTotal} → ${state.total} · exatamente 1 conta foi para a bandeja.`
);
updateHUD();
moveActiveBead(trayPosition);
animateFruit(record, rightSlots[targetSlot], () => {
record.side = "right";
record.slot = targetSlot;
rightOccupied.add(targetSlot);
state.busy = false;
exchangeState.textContent = "Troca concluída. Escolha outra fruta.";
updateHUD();
});
}
function returnSelected() {
const record = selectedRecord();
if (state.busy || !record || record.side !== "right") return;
let targetSlot = -1;
for (let i = 0; i < leftSlots.length; i++) {
if (!leftOccupied.has(i)) {
targetSlot = i;
break;
}
}
if (targetSlot < 0) return;
const oldTotal = state.total;
const fruitName = record.name;
state.busy = true;
record.side = "moving";
rightOccupied.delete(record.slot);
state.total = Math.min(9, state.total + 1);
state.beadsInRow = Math.min(9, state.beadsInRow + 1);
exchangeState.textContent = "Devolvendo: 1 fruta, 1 conta.";
liveOutput.textContent =
`${fruitName}: total ${oldTotal} para ${state.total}. Uma conta voltou à régua.`;
state.history.unshift(
`${fruitName}: ${oldTotal} → ${state.total} · exatamente 1 conta voltou à régua.`
);
updateHUD();
moveActiveBead(beadSlots[state.beadsInRow - 1]);
animateFruit(record, leftSlots[targetSlot], () => {
record.side = "left";
record.slot = targetSlot;
leftOccupied.add(targetSlot);
state.busy = false;
exchangeState.textContent = "Devolução concluída.";
updateHUD();
});
}
function resetActivity() {
if (state.busy) return;
state.total = 9;
state.beadsInRow = 9;
leftOccupied.clear();
rightOccupied.clear();
for (const record of fruitRecords) {
record.side = "left";
record.slot = record.homeSlot;
record.group.position.copy(leftSlots[record.homeSlot]);
record.group.rotation.set(0, 0, 0);
record.group.scale.setScalar(1);
record.marker.visible = false;
leftOccupied.add(record.homeSlot);
}
for (let i = 0; i < beadMeshes.length; i++) {
beadMeshes[i].position.copy(beadSlots[i]);
beadMeshes[i].rotation.set(0, 0, 0);
}
state.selectedId = "fruit-0";
fruitById.get("fruit-0").marker.visible = true;
state.history = ["Atividade reiniciada: 9 frutas e 9 contas na régua."];
exchangeState.textContent = "Pronto para trocar.";
liveOutput.textContent = "Atividade reiniciada com nove frutas.";
updateHUD();
}
tradeButton.addEventListener("click", tradeSelected);
returnButton.addEventListener("click", returnSelected);
resetButton.addEventListener("click", resetActivity);
// Raycasting e câmera orbital implementados diretamente.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = null;
function pickAt(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(raycastObjects.concat(actionGroups), true);
if (!intersections.length) return null;
let object = intersections[0].object;
while (object) {
if (object.userData.fruitId) {
return { type: "fruit", record: fruitById.get(object.userData.fruitId) };
}
if (object.userData.action) {
return { type: "action", action: object.userData.action };
}
object = object.parent;
}
return null;
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
pointerDown = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown || pointerDown.id !== event.pointerId) return;
const dx = event.clientX - pointerDown.lastX;
const dy = event.clientY - pointerDown.lastY;
if (Math.hypot(event.clientX - pointerDown.x, event.clientY - pointerDown.y) > 6) {
pointerDown.moved = true;
}
if (pointerDown.moved) {
cameraState.azimuth = THREE.MathUtils.clamp(
cameraState.azimuth - dx * 0.005,
-0.75,
0.75
);
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.004,
0.22,
0.72
);
updateCamera();
}
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerDown || pointerDown.id !== event.pointerId) return;
const wasClick = !pointerDown.moved;
pointerDown = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!wasClick) return;
const picked = pickAt(event.clientX, event.clientY);
if (!picked || state.busy) return;
if (picked.type === "fruit") {
selectFruit(picked.record);
} else if (picked.action === "trade") {
const record = selectedRecord();
if (!record || record.side !== "left") {
const fallback = firstFruitOn("left");
if (!fallback) return;
selectFruit(fallback);
}
tradeSelected();
} else if (picked.action === "return") {
const record = selectedRecord();
if (!record || record.side !== "right") {
const fallback = firstFruitOn("right");
if (!fallback) return;
selectFruit(fallback);
}
returnSelected();
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(event.deltaY * 0.001),
0.68,
1.38
);
updateCamera();
}, { passive: false });
selectFruit(fruitById.get("fruit-0"));
resize();
function animate(now) {
updateTweens(now);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```