Prompt specification
Build or customize the Three.js 3D scene "Outdoor Chess Movement Exhibit" 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: Outdoor Chess Movement Exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/outdoor-chess-movement-exhibit-x3607
Scene Description Prompt:
Build an original park chess teaching board with selectable pieces and legal-move previews. Limit the ruleset explicitly if king safety or special moves are omitted. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Technical checks: Show c3 and a3 as legal knight destinations from b1. When e2–e3 is played, place the white pawn on e3 and leave the material balance unchanged because no piece was captured.
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 (outdoor-chess-movement-exhibit-x3607):
```html
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#19392f">
<link rel="icon" href="data:,">
<title>Chess no Parque — Tabuleiro didático</title>
<style>
:root {
color-scheme: dark;
--ink: #f5f2df;
--muted: #b9c9bd;
--panel: rgba(18, 45, 37, 0.9);
--panel-strong: rgba(13, 36, 30, 0.96);
--line: rgba(235, 240, 219, 0.15);
--green: #9bd36e;
--green-dark: #456e47;
--cream: #eee4bd;
--gold: #f2c765;
--orange: #ff9d61;
--danger: #ff7b75;
--shadow: 0 18px 55px rgba(6, 23, 17, 0.34);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #accdb9;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button {
font: inherit;
}
#app, #scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#scene {
display: block;
touch-action: none;
outline: none;
}
.loading {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: #183b31;
transition: opacity .35s ease, visibility .35s ease;
}
.loading.hidden {
opacity: 0;
visibility: hidden;
}
.loading-card {
display: flex;
align-items: center;
gap: 14px;
padding: 18px 22px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255,255,255,.06);
box-shadow: var(--shadow);
font-weight: 700;
letter-spacing: .03em;
}
.loading-squares {
display: grid;
grid-template-columns: repeat(2, 12px);
grid-template-rows: repeat(2, 12px);
gap: 3px;
transform: rotate(8deg);
}
.loading-squares i {
display: block;
background: var(--cream);
}
.loading-squares i:nth-child(2),
.loading-squares i:nth-child(3) {
background: var(--green);
}
.brand {
position: fixed;
z-index: 5;
top: 24px;
left: 26px;
width: min(480px, calc(100vw - 420px));
pointer-events: none;
text-shadow: 0 2px 12px rgba(9, 34, 26, .35);
}
.brand-top {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 8px;
}
.brand-mark {
width: 43px;
height: 43px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
padding: 6px;
border: 1px solid rgba(255,255,255,.38);
border-radius: 12px;
background: rgba(18, 49, 39, .62);
box-shadow: var(--shadow);
transform: rotate(-3deg);
}
.brand-mark i {
display: block;
border-radius: 2px;
background: var(--cream);
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(3) {
background: var(--green);
}
.eyebrow {
margin: 0 0 4px;
color: var(--green);
font-size: 11px;
font-weight: 850;
letter-spacing: .15em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(29px, 4vw, 52px);
line-height: .98;
letter-spacing: -.045em;
}
.brand p {
max-width: 430px;
margin: 10px 0 0;
color: rgba(255,255,255,.83);
font-size: 14px;
line-height: 1.45;
}
.lesson-card {
position: fixed;
z-index: 6;
left: 26px;
bottom: 24px;
width: min(430px, calc(100vw - 420px));
padding: 17px 18px 16px;
border: 1px solid rgba(255,255,255,.22);
border-radius: 20px;
background: rgba(19, 49, 39, .82);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.lesson-card h2 {
margin: 3px 0 7px;
font-size: 20px;
letter-spacing: -.025em;
}
.lesson-card p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.challenge-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 13px;
}
.challenge-row button {
flex: 0 0 auto;
border: 0;
border-radius: 11px;
padding: 10px 13px;
color: #17372c;
background: var(--gold);
font-size: 12px;
font-weight: 850;
cursor: pointer;
transition: transform .15s ease, filter .15s ease;
}
.challenge-row button:hover {
transform: translateY(-1px);
filter: brightness(1.06);
}
#challengeStatus {
min-height: 32px;
display: flex;
align-items: center;
color: #dbe6d6;
font-size: 12px;
line-height: 1.3;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
bottom: 18px;
width: 360px;
overflow: auto;
padding: 19px;
border: 1px solid var(--line);
border-radius: 24px;
background: linear-gradient(155deg, rgba(24, 57, 47, .94), rgba(11, 32, 27, .96));
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(255,255,255,.22) transparent;
}
.panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding-bottom: 15px;
border-bottom: 1px solid var(--line);
}
.panel-head h2 {
margin: 2px 0 0;
font-size: 22px;
letter-spacing: -.035em;
}
.turn-pill {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 7px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255,255,255,.06);
color: #e9efdd;
font-size: 11px;
font-weight: 800;
}
.turn-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--cream);
box-shadow: 0 0 0 3px rgba(238,228,189,.12);
}
.turn-dot.black { background: #283f3a; }
.section {
padding: 16px 0;
border-bottom: 1px solid var(--line);
}
.section:last-child { border-bottom: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 11px;
}
.section-title h3 {
margin: 0;
color: #dce8d9;
font-size: 11px;
font-weight: 850;
letter-spacing: .13em;
text-transform: uppercase;
}
.small-note {
color: #91aa9c;
font-size: 10px;
}
.selection-box {
min-height: 73px;
display: flex;
align-items: center;
gap: 13px;
padding: 12px;
border: 1px solid rgba(255,255,255,.12);
border-radius: 16px;
background: rgba(255,255,255,.045);
}
.piece-glyph {
width: 47px;
height: 47px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 13px;
color: #17382e;
background: var(--cream);
font-family: Georgia, serif;
font-size: 31px;
box-shadow: inset 0 -4px 0 rgba(36,61,48,.13);
}
.piece-glyph.black {
color: #e8edda;
background: #294139;
}
.selection-copy {
min-width: 0;
}
#selectionName {
margin: 0 0 3px;
font-size: 17px;
font-weight: 850;
}
#selectionMeta {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.35;
}
.destinations {
display: flex;
flex-wrap: wrap;
gap: 7px;
min-height: 29px;
margin-top: 11px;
}
.square-chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 6px 9px;
border: 1px solid rgba(155,211,110,.34);
border-radius: 9px;
color: #dff5c7;
background: rgba(155,211,110,.1);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
font-weight: 800;
}
.square-chip.capture {
border-color: rgba(255,157,97,.48);
color: #ffd2b5;
background: rgba(255,157,97,.12);
}
.square-chip.capture::after {
content: "captura";
font-family: inherit;
font-size: 9px;
opacity: .78;
}
.empty-copy {
color: #8ca497;
font-size: 12px;
line-height: 1.4;
}
.scores {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 12px;
}
.score-side strong {
display: block;
margin-top: 2px;
font-size: 27px;
line-height: 1;
}
.score-side span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .09em;
text-transform: uppercase;
}
.score-side.right { text-align: right; }
.versus {
color: #799286;
font-size: 10px;
font-weight: 900;
letter-spacing: .1em;
}
#materialVerdict {
margin: 13px 0 9px;
padding: 9px 11px;
border-radius: 11px;
color: #dfeadd;
background: rgba(255,255,255,.055);
font-size: 12px;
font-weight: 750;
text-align: center;
}
.material-bar {
display: flex;
height: 7px;
overflow: hidden;
border-radius: 99px;
background: #283c35;
}
#materialBarW {
width: 50%;
background: var(--cream);
transition: width .35s ease;
}
#materialBarB {
width: 50%;
background: #5d8470;
transition: width .35s ease;
}
.capture-row {
display: grid;
grid-template-columns: 83px 1fr;
align-items: center;
gap: 9px;
margin-top: 8px;
color: var(--muted);
font-size: 11px;
}
.capture-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
min-height: 24px;
}
.capture-item {
min-width: 25px;
height: 25px;
display: inline-grid;
place-items: center;
padding: 0 6px;
border-radius: 7px;
color: #1a382e;
background: var(--cream);
font-family: Georgia, serif;
font-size: 16px;
}
.capture-item.dark {
color: #e5ead8;
background: #314c42;
}
.history {
max-height: 128px;
overflow: auto;
display: grid;
gap: 6px;
}
.history-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 10px;
border-radius: 9px;
color: #d5e0d5;
background: rgba(255,255,255,.045);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.history-row span:last-child {
color: #91a99c;
font-family: inherit;
font-size: 10px;
}
.rules {
margin: 0;
color: #a9bbb0;
font-size: 11px;
line-height: 1.52;
}
.rules strong { color: #dce8d9; }
.diagnostic {
margin-top: 12px;
padding: 10px 11px;
border: 1px solid rgba(155,211,110,.2);
border-radius: 11px;
color: #cfe6c2;
background: rgba(155,211,110,.07);
font-size: 10px;
line-height: 1.45;
}
.diagnostic.bad {
border-color: rgba(255,123,117,.35);
color: #ffc1bd;
background: rgba(255,123,117,.08);
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.actions button {
min-height: 39px;
border: 1px solid var(--line);
border-radius: 11px;
color: #e6eee1;
background: rgba(255,255,255,.065);
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: background .15s ease, transform .15s ease;
}
.actions button:hover {
background: rgba(255,255,255,.12);
transform: translateY(-1px);
}
.actions button.primary {
border-color: transparent;
color: #17372c;
background: var(--green);
}
.camera-hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
padding: 8px 12px;
border: 1px solid rgba(255,255,255,.18);
border-radius: 999px;
color: rgba(255,255,255,.82);
background: rgba(19,49,39,.56);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 900px) {
.brand {
top: 16px;
left: 16px;
width: calc(100vw - 32px);
}
.brand p { display: none; }
.brand h1 { font-size: 32px; }
.lesson-card {
display: none;
}
.panel {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
max-height: 43vh;
padding: 15px;
border-radius: 20px;
}
.camera-hint { display: none; }
}
@media (max-height: 650px) and (min-width: 901px) {
.lesson-card { display: none; }
.panel { padding: 15px; }
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene" aria-label="Tabuleiro de xadrez tridimensional em um parque" tabindex="0"></canvas>
<div class="loading" id="loading">
<div class="loading-card">
<span class="loading-squares" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
Preparando o parque…
</div>
</div>
<header class="brand">
<div class="brand-top">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<div>
<p class="eyebrow">Parque dos tabuleiros</p>
<h1>Chess no Parque</h1>
</div>
</div>
<p>Selecione uma peça, preveja as casas e descubra como cada lance transforma a partida.</p>
</header>
<section class="lesson-card" aria-labelledby="objectiveTitle">
<p class="eyebrow">Objetivo de aprendizagem</p>
<h2 id="objectiveTitle">Mover não é capturar.</h2>
<p>Observe que um lance sem captura muda a posição, mas mantém a força de material das duas cores.</p>
<div class="challenge-row">
<button id="challengeBtn" type="button">Desafio: e2 → e3</button>
<span id="challengeStatus" aria-live="polite">Selecione o peão de e2 para começar.</span>
</div>
</section>
<aside class="panel" aria-label="Inspetor de jogadas">
<div class="panel-head">
<div>
<p class="eyebrow">Inspetor de jogadas</p>
<h2>Peça selecionada</h2>
</div>
<div class="turn-pill">
<span class="turn-dot" id="turnDot"></span>
<span id="turnText">Turno branco</span>
</div>
</div>
<section class="section">
<div class="selection-box">
<div class="piece-glyph" id="selectionGlyph">♞</div>
<div class="selection-copy">
<p id="selectionName">Cavalo branco</p>
<p id="selectionMeta">Casa b1 · 2 destinos livres</p>
</div>
</div>
<div class="destinations" id="destinations" aria-live="polite"></div>
</section>
<section class="section">
<div class="section-title">
<h3>Material restante</h3>
<span class="small-note">peão 1 · cavalo/bispo 3 · torre 5 · rainha 9</span>
</div>
<div class="scores">
<div class="score-side">
<span>Brancas</span>
<strong id="whiteScore">39</strong>
</div>
<div class="versus">VS</div>
<div class="score-side right">
<span>Pretas</span>
<strong id="blackScore">39</strong>
</div>
</div>
<div id="materialVerdict">Material igual</div>
<div class="material-bar" aria-hidden="true">
<div id="materialBarW"></div>
<div id="materialBarB"></div>
</div>
<div class="capture-row">
<span>Capturados pelas brancas</span>
<div class="capture-list" id="capturedWhite"></div>
</div>
<div class="capture-row">
<span>Capturados pelas pretas</span>
<div class="capture-list" id="capturedBlack"></div>
</div>
</section>
<section class="section">
<div class="section-title">
<h3>Lances</h3>
<span class="small-note">modo livre: ambas as cores</span>
</div>
<div class="history" id="history">
<div class="empty-copy">Nenhum lance realizado.</div>
</div>
</section>
<section class="section">
<div class="section-title"><h3>Limites das regras</h3></div>
<p class="rules">
<strong>Ativos:</strong> movimentos das peças, bloqueios, capturas e promoção simplificada para rainha.
<strong>Omitidos:</strong> xeque, cheque-mate, roque, en passant e IA. A segurança do rei não é validada e o rei não pode ser capturado.
</p>
<div class="diagnostic" id="diagnostic" aria-live="polite">Executando auto-teste da cena…</div>
</section>
<div class="actions">
<button type="button" id="newGameBtn">Nova partida</button>
<button type="button" id="undoBtn">Desfazer</button>
<button type="button" id="cameraBtn">Câmera padrão</button>
<button type="button" id="testBtn">Testar estados</button>
<button type="button" class="primary" id="captureBtn">Capturar PNG</button>
<button type="button" id="clearBtn">Limpar seleção</button>
</div>
</aside>
<div class="camera-hint">Arraste para orbitar · roda para aproximar · clique para jogar</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
const $ = id => document.getElementById(id);
const canvas = $('scene');
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
preserveDrawingBuffer: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb7d5c2);
scene.fog = new THREE.Fog(0xb7d5c2, 18, 43);
const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.1, 80);
const cameraTarget = new THREE.Vector3(0.15, 0.45, 0.15);
const cameraState = { yaw: 0.48, pitch: 0.72, distance: 14.8 };
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraState.yaw) * cp * cameraState.distance,
cameraTarget.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraTarget.z + Math.cos(cameraState.yaw) * cp * cameraState.distance
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xeaf8df, 0x48614e, 2.05));
const sun = new THREE.DirectionalLight(0xfff1c4, 3.25);
sun.position.set(-7, 14, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xa9d9ff, 0.55);
rim.position.set(9, 5, -10);
scene.add(rim);
const materials = {
ground: new THREE.MeshStandardMaterial({ color: 0x789866, roughness: 0.95 }),
grassLight: new THREE.MeshStandardMaterial({ color: 0x88a96e, roughness: 1 }),
grassDark: new THREE.MeshStandardMaterial({ color: 0x718f5f, roughness: 1 }),
path: new THREE.MeshStandardMaterial({ color: 0xc7b889, roughness: 0.94 }),
pathEdge: new THREE.MeshStandardMaterial({ color: 0x9e916c, roughness: 1 }),
boardBase: new THREE.MeshStandardMaterial({ color: 0x365346, roughness: 0.78 }),
boardRim: new THREE.MeshStandardMaterial({ color: 0x203e35, roughness: 0.82 }),
tileLight: new THREE.MeshStandardMaterial({ color: 0xe7dbad, roughness: 0.72 }),
tileDark: new THREE.MeshStandardMaterial({ color: 0x617f5c, roughness: 0.78 }),
trunk: new THREE.MeshStandardMaterial({ color: 0x76523a, roughness: 1 }),
leafA: new THREE.MeshStandardMaterial({ color: 0x3f754e, roughness: 0.95 }),
leafB: new THREE.MeshStandardMaterial({ color: 0x568b56, roughness: 0.95 }),
leafC: new THREE.MeshStandardMaterial({ color: 0x6f9a5c, roughness: 0.95 }),
wood: new THREE.MeshStandardMaterial({ color: 0x9a6944, roughness: 0.9 }),
woodDark: new THREE.MeshStandardMaterial({ color: 0x5d4937, roughness: 0.92 }),
metal: new THREE.MeshStandardMaterial({ color: 0x334b43, roughness: 0.55, metalness: 0.35 }),
pond: new THREE.MeshStandardMaterial({ color: 0x5eaeb0, roughness: 0.24, metalness: 0.08 }),
pondLight: new THREE.MeshStandardMaterial({ color: 0x8bd0c2, roughness: 0.32 }),
white: new THREE.MeshStandardMaterial({ color: 0xf1ead2, roughness: 0.52 }),
whiteTrim: new THREE.MeshStandardMaterial({ color: 0xd5cba9, roughness: 0.6 }),
black: new THREE.MeshStandardMaterial({ color: 0x263d38, roughness: 0.48 }),
blackTrim: new THREE.MeshStandardMaterial({ color: 0x172a27, roughness: 0.55 }),
gold: new THREE.MeshStandardMaterial({ color: 0xd9b75a, roughness: 0.42, metalness: 0.25 }),
cloud: new THREE.MeshStandardMaterial({ color: 0xe8efe3, roughness: 1 })
};
function box(parent, w, h, d, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
let randomSeed = 73421;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function makeTextSprite(text, foreground = '#203c31', background = null) {
const c = document.createElement('canvas');
c.width = 256;
c.height = 128;
const ctx = c.getContext('2d');
if (background) {
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
}
ctx.fillStyle = foreground;
ctx.font = '800 55px ui-monospace, SFMono-Regular, Menlo, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, 128, 66);
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.54, 0.27, 1);
return sprite;
}
function buildPark() {
const ground = new THREE.Group();
scene.add(ground);
box(ground, 31, 0.6, 25, materials.ground, 0, -0.45, 0);
for (let i = 0; i < 75; i++) {
const x = -14 + random() * 28;
const z = -11 + random() * 22;
if (Math.abs(x + 1.45) < 6.1 && Math.abs(z) < 6.1) continue;
const tile = box(
ground,
0.55 + random() * 0.8,
0.025,
0.55 + random() * 0.8,
random() > 0.5 ? materials.grassLight : materials.grassDark,
x,
-0.135,
z
);
tile.castShadow = false;
}
box(ground, 15.6, 0.07, 1.75, materials.path, -1.4, -0.09, 5.7);
box(ground, 1.65, 0.07, 15.2, materials.path, -9.1, -0.08, 0.1);
box(ground, 12.2, 0.05, 1.1, materials.path, 4.3, -0.08, -5.2);
box(ground, 12.5, 0.07, 0.14, materials.pathEdge, 4.3, -0.035, -4.62);
box(ground, 12.5, 0.07, 0.14, materials.pathEdge, 4.3, -0.035, -5.78);
function tree(x, z, scale = 1) {
const g = new THREE.Group();
g.position.set(x, -0.12, z);
g.scale.setScalar(scale);
ground.add(g);
box(g, 0.48, 2.25, 0.48, materials.trunk, 0, 1.1, 0);
box(g, 2.4, 1.1, 2.15, materials.leafA, 0, 2.45, 0);
box(g, 1.6, 1.2, 1.7, materials.leafB, -0.6, 3.15, 0.15);
box(g, 1.55, 1.05, 1.55, materials.leafC, 0.65, 3.05, -0.25);
box(g, 1.0, 0.95, 1.15, materials.leafB, 0.1, 3.72, 0.1);
}
tree(-8.1, -5.8, 1.05);
tree(-11.3, 1.8, 0.82);
tree(5.0, -8.2, 1.1);
tree(10.0, 3.8, 0.95);
tree(7.7, 8.0, 0.75);
tree(-5.2, 8.0, 0.72);
function bench(x, z, rotation = 0) {
const g = new THREE.Group();
g.position.set(x, -0.1, z);
g.rotation.y = rotation;
ground.add(g);
box(g, 2.05, 0.16, 0.62, materials.wood, 0, 0.63, 0);
box(g, 2.05, 0.52, 0.13, materials.woodDark, 0, 1.05, -0.26);
box(g, 0.16, 0.72, 0.5, materials.metal, -0.72, 0.27, 0);
box(g, 0.16, 0.72, 0.5, materials.metal, 0.72, 0.27, 0);
}
bench(-7.2, 4.8, 0);
bench(4.9, 5.9, Math.PI / 2);
function lamp(x, z) {
const g = new THREE.Group();
g.position.set(x, -0.12, z);
ground.add(g);
box(g, 0.13, 3.1, 0.13, materials.metal, 0, 1.55, 0);
box(g, 0.55, 0.12, 0.55, materials.metal, 0, 3.08, 0);
box(g, 0.34, 0.34, 0.34, materials.gold, 0, 3.28, 0);
}
lamp(-10.0, 4.1);
lamp(2.9, 7.1);
const pond = new THREE.Group();
pond.position.set(7.3, -0.16, -4.85);
ground.add(pond);
box(pond, 4.6, 0.12, 3.25, materials.pond, 0, 0, 0);
box(pond, 1.0, 0.14, 0.7, materials.pond, -2.05, 0.02, 0.75);
box(pond, 0.7, 0.14, 0.8, materials.pond, 2.0, 0.02, -0.7);
for (let i = 0; i < 6; i++) {
const ripple = box(
pond,
0.65 + random() * 0.7,
0.018,
0.08,
materials.pondLight,
-1.7 + random() * 3.4,
0.09,
-1.0 + random() * 2.0
);
ripple.castShadow = false;
}
const sign = makeTextSprite('PARQUE', '#203c31', '#eee4bd');
sign.position.set(-9.9, 1.65, 2.2);
sign.scale.set(2.15, 1.08, 1);
ground.add(sign);
box(ground, 0.13, 2.1, 0.13, materials.woodDark, -9.9, 0.75, 2.23);
const cloudGroup = new THREE.Group();
cloudGroup.position.set(0, 8.7, -10);
scene.add(cloudGroup);
box(cloudGroup, 2.3, 0.55, 0.8, materials.cloud, 0, 0, 0);
box(cloudGroup, 1.2, 0.85, 0.9, materials.cloud, -0.7, 0.2, 0);
box(cloudGroup, 1.1, 0.75, 0.85, materials.cloud, 0.8, 0.12, 0);
}
buildPark();
const CELL = 1.04;
const BOARD_X = -1.45;
const BOARD_Z = 0.15;
const BOARD_TOP = 0.27;
const FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
function squareFrom(file, rank) {
return FILES[file] + String(rank + 1);
}
function parseSquare(square) {
return {
file: FILES.indexOf(square[0]),
rank: Number(square[1]) - 1
};
}
function worldForSquare(square) {
const { file, rank } = parseSquare(square);
return new THREE.Vector3(
BOARD_X + (file - 3.5) * CELL,
BOARD_TOP,
BOARD_Z + (3.5 - rank) * CELL
);
}
const boardGroup = new THREE.Group();
scene.add(boardGroup);
box(boardGroup, 8.95, 0.32, 8.95, materials.boardBase, BOARD_X, 0.01, BOARD_Z);
box(boardGroup, 9.18, 0.12, 9.18, materials.boardRim, BOARD_X, -0.11, BOARD_Z);
const tileMeshes = [];
for (let rank = 0; rank < 8; rank++) {
for (let file = 0; file < 8; file++) {
const square = squareFrom(file, rank);
const p = worldForSquare(square);
const tile = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.965, 0.12, CELL * 0.965),
(file + rank) % 2 === 0 ? materials.tileLight : materials.tileDark
);
tile.position.set(p.x, 0.205, p.z);
tile.receiveShadow = true;
tile.userData.square = square;
tile.userData.interactiveType = 'square';
boardGroup.add(tile);
tileMeshes.push(tile);
}
}
for (let file = 0; file < 8; file++) {
const label = makeTextSprite(FILES[file], '#f4edcf', '#29483d');
const p = worldForSquare(squareFrom(file, 0));
label.position.set(p.x, 0.25, BOARD_Z + 4.55);
label.scale.set(0.48, 0.24, 1);
boardGroup.add(label);
}
for (let rank = 0; rank < 8; rank++) {
const label = makeTextSprite(String(rank + 1), '#f4edcf', '#29483d');
const p = worldForSquare(squareFrom(0, rank));
label.position.set(BOARD_X - 4.55, 0.25, p.z);
label.scale.set(0.48, 0.24, 1);
boardGroup.add(label);
}
function createPieceMesh(piece) {
const root = new THREE.Group();
const isWhite = piece.color === 'w';
const body = isWhite ? materials.white : materials.black;
const trim = isWhite ? materials.whiteTrim : materials.blackTrim;
root.userData.pieceId = piece.id;
root.userData.square = piece.square;
root.userData.interactiveType = 'piece';
root.rotation.y = isWhite ? 0 : Math.PI;
if (piece.type === 'p') {
box(root, 0.58, 0.12, 0.58, trim, 0, 0.06, 0);
box(root, 0.34, 0.31, 0.34, body, 0, 0.275, 0);
box(root, 0.31, 0.29, 0.31, body, 0, 0.565, 0);
} else if (piece.type === 'n') {
box(root, 0.61, 0.12, 0.61, trim, 0, 0.06, 0);
box(root, 0.34, 0.43, 0.38, body, 0, 0.335, -0.03);
box(root, 0.32, 0.28, 0.36, body, 0, 0.66, 0.05);
box(root, 0.47, 0.29, 0.35, body, 0, 0.83, 0.08);
box(root, 0.28, 0.17, 0.25, body, 0, 0.72, 0.28);
box(root, 0.12, 0.2, 0.14, trim, -0.12, 1.05, 0.05);
box(root, 0.12, 0.2, 0.14, trim, 0.12, 1.05, 0.05);
} else if (piece.type === 'b') {
box(root, 0.61, 0.12, 0.61, trim, 0, 0.06, 0);
box(root, 0.39, 0.47, 0.39, body, 0, 0.355, 0);
box(root, 0.48, 0.14, 0.48, trim, 0, 0.66, 0);
box(root, 0.35, 0.36, 0.35, body, 0, 0.89, 0);
box(root, 0.055, 0.19, 0.03, trim, 0, 0.91, 0.19);
} else if (piece.type === 'r') {
box(root, 0.65, 0.12, 0.65, trim, 0, 0.06, 0);
box(root, 0.47, 0.54, 0.47, body, 0, 0.39, 0);
box(root, 0.62, 0.14, 0.62, trim, 0, 0.73, 0);
box(root, 0.15, 0.22, 0.15, body, -0.23, 0.88, -0.23);
box(root, 0.15, 0.22, 0.15, body, 0.23, 0.88, -0.23);
box(root, 0.15, 0.22, 0.15, body, -0.23, 0.88, 0.23);
box(root, 0.15, 0.22, 0.15, body, 0.23, 0.88, 0.23);
} else if (piece.type === 'q') {
box(root, 0.66, 0.12, 0.66, trim, 0, 0.06, 0);
box(root, 0.38, 0.58, 0.38, body, 0, 0.41, 0);
box(root, 0.56, 0.13, 0.56, trim, 0, 0.76, 0);
box(root, 0.13, 0.3, 0.13, body, -0.21, 0.95, -0.21);
box(root, 0.13, 0.3, 0.13, body, 0.21, 0.95, -0.21);
box(root, 0.13, 0.3, 0.13, body, -0.21, 0.95, 0.21);
box(root, 0.13, 0.3, 0.13, body, 0.21, 0.95, 0.21);
box(root, 0.18, 0.32, 0.18, body, 0, 0.98, 0);
} else if (piece.type === 'k') {
box(root, 0.67, 0.12, 0.67, trim, 0, 0.06, 0);
box(root, 0.4, 0.65, 0.4, body, 0, 0.445, 0);
box(root, 0.57, 0.13, 0.57, trim, 0, 0.83, 0);
box(root, 0.38, 0.27, 0.38, body, 0, 1.02, 0);
box(root, 0.12, 0.35, 0.12, materials.gold, 0, 1.3, 0);
box(root, 0.29, 0.1, 0.1, materials.gold, 0, 1.31, 0);
}
root.position.copy(worldForSquare(piece.square));
scene.add(root);
return root;
}
const VALUES = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
const TYPE_NAMES = {
p: 'Peão', n: 'Cavalo', b: 'Bispo', r: 'Torre', q: 'Rainha', k: 'Rei'
};
const GLYPHS = {
w: { p: '♙', n: '♘', b: '♗', r: '♖', q: '♕', k: '♔' },
b: { p: '♟', n: '♞', b: '♝', r: '♜', q: '♛', k: '♚' }
};
function createInitialState() {
const pieces = [];
const back = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'];
for (const color of ['w', 'b']) {
const rank = color === 'w' ? 0 : 7;
for (let file = 0; file < 8; file++) {
const type = back[file];
pieces.push({
id: `${color}-${type}-${squareFrom(file, rank)}`,
type,
color,
square: squareFrom(file, rank)
});
}
const pawnRank = color === 'w' ? 1 : 6;
for (let file = 0; file < 8; file++) {
const square = squareFrom(file, pawnRank);
pieces.push({
id: `${color}-p-${square}`,
type: 'p',
color,
square
});
}
}
return {
pieces,
turn: 'w',
capturedBy: { w: [], b: [] },
history: []
};
}
let state = createInitialState();
const pieceMeshes = new Map();
const undoStack = [];
const markerGroup = new THREE.Group();
const selectionGroup = new THREE.Group();
const lastMoveGroup = new THREE.Group();
scene.add(markerGroup, selectionGroup, lastMoveGroup);
let selectedId = null;
let markerMaterials = [];
let challenge = { active: false, done: false };
const animations = [];
function rebuildPieces() {
for (const mesh of pieceMeshes.values()) scene.remove(mesh);
pieceMeshes.clear();
for (const piece of state.pieces) {
pieceMeshes.set(piece.id, createPieceMesh(piece));
}
}
rebuildPieces();
function pieceAt(square) {
return state.pieces.find(piece => piece.square === square) || null;
}
function pieceById(id) {
return state.pieces.find(piece => piece.id === id) || null;
}
function isInside(file, rank) {
return file >= 0 && file < 8 && rank >= 0 && rank < 8;
}
function legalDestinations(piece) {
if (!piece) return [];
const { file, rank } = parseSquare(piece.square);
const destinations = [];
function canLand(square) {
const target = pieceAt(square);
if (!target) return true;
if (target.color === piece.color) return false;
if (target.type === 'k') return false;
return true;
}
function add(file2, rank2) {
if (!isInside(file2, rank2)) return;
const square = squareFrom(file2, rank2);
if (canLand(square)) destinations.push(square);
}
if (piece.type === 'p') {
const direction = piece.color === 'w' ? 1 : -1;
const startRank = piece.color === 'w' ? 1 : 6;
if (!pieceAt(squareFrom(file, rank + direction))) {
add(file, rank + direction);
if (rank === startRank && !pieceAt(squareFrom(file, rank + direction * 2))) {
add(file, rank + direction * 2);
}
}
for (const df of [-1, 1]) {
const cf = file + df;
const cr = rank + direction;
if (!isInside(cf, cr)) continue;
const target = pieceAt(squareFrom(cf, cr));
if (target && target.color !== piece.color && target.type !== 'k') {
destinations.push(squareFrom(cf, cr));
}
}
} else if (piece.type === 'n') {
const offsets = [[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]];
for (const [df, dr] of offsets) add(file + df, rank + dr);
} else if (piece.type === 'k') {
for (let df = -1; df <= 1; df++) {
for (let dr = -1; dr <= 1; dr++) {
if (df || dr) add(file + df, rank + dr);
}
}
} else {
const diagonal = piece.type === 'b' || piece.type === 'q';
const straight = piece.type === 'r' || piece.type === 'q';
const directions = [];
if (straight) directions.push([1,0],[-1,0],[0,1],[0,-1]);
if (diagonal) directions.push([1,1],[1,-1],[-1,1],[-1,-1]);
for (const [df, dr] of directions) {
let cf = file + df;
let cr = rank + dr;
while (isInside(cf, cr)) {
const square = squareFrom(cf, cr);
const target = pieceAt(square);
if (target) {
if (target.color !== piece.color && target.type !== 'k') destinations.push(square);
break;
}
destinations.push(square);
cf += df;
cr += dr;
}
}
}
return [...new Set(destinations)];
}
function materialScores() {
let white = 0;
let black = 0;
for (const piece of state.pieces) {
if (piece.color === 'w') white += VALUES[piece.type];
else black += VALUES[piece.type];
}
return { white, black, diff: white - black };
}
function clearDynamicGroup(group) {
for (const child of [...group.children]) {
group.remove(child);
child.traverse(node => {
if (node.geometry) node.geometry.dispose();
if (node.isSprite && node.material?.map) {
node.material.map.dispose();
node.material.dispose();
}
});
}
}
function updateSelectionVisuals() {
clearDynamicGroup(selectionGroup);
clearDynamicGroup(lastMoveGroup);
const selected = pieceById(selectedId);
if (selected) {
const p = worldForSquare(selected.square);
const color = 0xf3c75f;
const half = CELL * 0.46;
const thickness = 0.075;
const height = 0.04;
const parts = [
[p.x, p.z - half, CELL * 0.8, thickness],
[p.x, p.z + half, CELL * 0.8, thickness],
[p.x - half, p.z, thickness, CELL * 0.8],
[p.x + half, p.z, thickness, CELL * 0.8]
];
for (const [x, z, w, d] of parts) {
const m = new THREE.Mesh(
new THREE.BoxGeometry(w, height, d),
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.94 })
);
m.position.set(x, BOARD_TOP + 0.11, z);
selectionGroup.add(m);
}
}
const last = state.history[state.history.length - 1];
if (last) {
for (const square of [last.from, last.to]) {
const p = worldForSquare(square);
const tile = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.91, 0.025, CELL * 0.91),
new THREE.MeshBasicMaterial({ color: 0xf0b75e, transparent: true, opacity: 0.18 })
);
tile.position.set(p.x, BOARD_TOP + 0.075, p.z);
lastMoveGroup.add(tile);
}
}
}
function updateMarkers() {
clearDynamicGroup(markerGroup);
markerMaterials = [];
const selected = pieceById(selectedId);
if (!selected) return;
for (const square of legalDestinations(selected)) {
const target = pieceAt(square);
const isCapture = !!target && target.color !== selected.color;
const group = new THREE.Group();
group.userData.square = square;
group.userData.interactiveType = 'square';
const color = isCapture ? 0xff8b57 : 0x9ee36b;
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: isCapture ? 0.42 : 0.3,
depthWrite: false
});
markerMaterials.push({ material, capture: isCapture });
const p = worldForSquare(square);
const tile = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.72, 0.035, CELL * 0.72),
material
);
tile.position.set(p.x, BOARD_TOP + 0.09, p.z);
group.add(tile);
const dot = new THREE.Mesh(
new THREE.BoxGeometry(isCapture ? 0.33 : 0.19, 0.04, isCapture ? 0.33 : 0.19),
material
);
dot.position.set(p.x, BOARD_TOP + 0.13, p.z);
group.add(dot);
const label = makeTextSprite(square, isCapture ? '#ffd1b3' : '#e4f8ce');
label.position.set(p.x, BOARD_TOP + 0.42, p.z);
label.scale.set(0.45, 0.225, 1);
group.add(label);
markerGroup.add(group);
}
}
function animateMeshTo(mesh, destination, animate = true) {
const target = worldForSquare(destination);
if (!animate) {
mesh.position.copy(target);
return;
}
animations.push({
mesh,
from: mesh.position.clone(),
to: target,
start: performance.now(),
duration: 210
});
}
function commitMove(piece, destination, options = {}) {
const {
animate = true,
record = true,
announce = true
} = options;
const captured = pieceAt(destination);
const from = piece.square;
if (record) {
undoStack.push(JSON.stringify(state));
}
if (captured) {
state.pieces = state.pieces.filter(item => item.id !== captured.id);
const capturedMesh = pieceMeshes.get(captured.id);
if (capturedMesh) {
scene.remove(capturedMesh);
pieceMeshes.delete(captured.id);
}
state.capturedBy[piece.color].push({
type: captured.type,
color: captured.color
});
}
piece.square = destination;
let promotion = false;
const finalRank = piece.color === 'w' ? 7 : 0;
if (piece.type === 'p' && parseSquare(destination).rank === finalRank) {
piece.type = 'q';
piece.promoted = true;
promotion = true;
}
state.turn = state.turn === 'w' ? 'b' : 'w';
if (record) {
state.history.push({
from,
to: destination,
color: piece.color,
pieceType: piece.type,
captured: captured?.type || null,
promotion
});
}
if (promotion) {
const oldMesh = pieceMeshes.get(piece.id);
if (oldMesh) scene.remove(oldMesh);
const newMesh = createPieceMesh(piece);
pieceMeshes.set(piece.id, newMesh);
animateMeshTo(newMesh, destination, animate);
} else {
const mesh = pieceMeshes.get(piece.id);
if (mesh) {
mesh.userData.square = destination;
animateMeshTo(mesh, destination, animate);
}
}
selectedId = null;
if (announce) {
const captureText = captured ? ` — captura de ${TYPE_NAMES[captured.type].toLowerCase()}` : '';
const promotionText = promotion ? ' — promoção para rainha' : '';
$('challengeStatus').textContent = `${piece.color === 'w' ? 'Brancas' : 'Pretas'}: ${from} → ${destination}${captureText}${promotionText}.`;
}
evaluateChallenge(from, destination);
return true;
}
function evaluateChallenge(from, to) {
if (!challenge.active || challenge.done) return;
if (from === 'e2' && to === 'e3') {
challenge.done = true;
const scores = materialScores();
$('challengeStatus').textContent = scores.diff === 0 && state.capturedBy.w.length === 0 && state.capturedBy.b.length === 0
? 'Correto: o peão está em e3, e2 ficou vazia e o material continua igual.'
: 'O peão chegou a e3, mas confira a atualização de material e captura.';
}
}
function selectPiece(id) {
const piece = pieceById(id);
if (!piece) return;
selectedId = id;
updateAll();
}
function clearSelection() {
selectedId = null;
updateAll();
}
function updateUI() {
const selected = pieceById(selectedId);
if (selected) {
const destinations = legalDestinations(selected);
$('selectionGlyph').textContent = GLYPHS[selected.color][selected.type];
$('selectionGlyph').classList.toggle('black', selected.color === 'b');
$('selectionName').textContent = `${TYPE_NAMES[selected.type]} ${selected.color === 'w' ? 'branco' : 'preto'}`;
$('selectionMeta').textContent = `Casa ${selected.square} · ${destinations.length} ${destinations.length === 1 ? 'destino' : 'destinos'}`;
$('destinations').innerHTML = destinations.length
? destinations.map(square => {
const target = pieceAt(square);
const capture = target && target.color !== selected.color;
return `<span class="square-chip ${capture ? 'capture' : ''}">${square}</span>`;
}).join('')
: '<span class="empty-copy">Esta peça não tem destinos disponíveis.</span>';
} else {
$('selectionGlyph').textContent = '♟';
$('selectionGlyph').classList.remove('black');
$('selectionName').textContent = 'Nenhuma peça selecionada';
$('selectionMeta').textContent = 'Clique em uma peça no tabuleiro';
$('destinations').innerHTML = '<span class="empty-copy">Os destinos legais aparecerão aqui.</span>';
}
const scores = materialScores();
$('whiteScore').textContent = scores.white;
$('blackScore').textContent = scores.black;
if (scores.diff > 0) {
$('materialVerdict').textContent = `Vantagem branca de ${scores.diff} ${scores.diff === 1 ? 'ponto' : 'pontos'}`;
} else if (scores.diff < 0) {
$('materialVerdict').textContent = `Vantagem preta de ${Math.abs(scores.diff)} ${Math.abs(scores.diff) === 1 ? 'ponto' : 'pontos'}`;
} else {
$('materialVerdict').textContent = 'Material igual';
}
const total = Math.max(1, scores.white + scores.black);
$('materialBarW').style.width = `${scores.white / total * 100}%`;
$('materialBarB').style.width = `${scores.black / total * 100}%`;
function captureHTML(items) {
if (!items.length) return '<span class="empty-copy">—</span>';
return items.map(item =>
`<span class="capture-item ${item.color === 'b' ? 'dark' : ''}" title="${TYPE_NAMES[item.type]}">${GLYPHS[item.color][item.type]}</span>`
).join('');
}
$('capturedWhite').innerHTML = captureHTML(state.capturedBy.w);
$('capturedBlack').innerHTML = captureHTML(state.capturedBy.b);
$('turnText').textContent = state.turn === 'w' ? 'Turno branco' : 'Turno preto';
$('turnDot').classList.toggle('black', state.turn === 'b');
if (!state.history.length) {
$('history').innerHTML = '<div class="empty-copy">Nenhum lance realizado.</div>';
} else {
$('history').innerHTML = state.history.slice(-8).reverse().map((move, index) => {
const number = state.history.length - index;
const capture = move.captured ? ` · capturou ${TYPE_NAMES[move.captured].toLowerCase()}` : '';
const promotion = move.promotion ? ' · promoção' : '';
return `<div class="history-row"><span>${move.color === 'w' ? 'B' : 'P'} ${move.from} → ${move.to}</span><span>${number}${capture}${promotion}</span></div>`;
}).join('');
}
}
function updateAll() {
updateSelectionVisuals();
updateMarkers();
updateUI();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function interactiveData(object) {
let current = object;
while (current && current !== scene) {
if (current.userData?.pieceId) {
return {
type: 'piece',
pieceId: current.userData.pieceId,
square: current.userData.square
};
}
if (current.userData?.square) {
return {
type: 'square',
square: current.userData.square
};
}
current = current.parent;
}
return null;
}
function handlePick(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 roots = [
...pieceMeshes.values(),
...tileMeshes,
...markerGroup.children
];
const hits = raycaster.intersectObjects(roots, true);
let hitData = null;
for (const hit of hits) {
hitData = interactiveData(hit.object);
if (hitData) break;
}
if (!hitData) return;
const selected = pieceById(selectedId);
if (selected && hitData.square && hitData.square !== selected.square) {
const destinations = legalDestinations(selected);
if (destinations.includes(hitData.square)) {
commitMove(selected, hitData.square);
updateAll();
return;
}
}
if (hitData.type === 'piece') {
selectPiece(hitData.pieceId);
} else {
const occupant = pieceAt(hitData.square);
if (occupant) selectPiece(occupant.id);
else clearSelection();
}
}
let pointerDown = null;
canvas.addEventListener('pointerdown', event => {
pointerDown = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
pointerId: event.pointerId
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener('pointermove', event => {
if (!pointerDown || event.pointerId !== pointerDown.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;
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.0045, 0.38, 1.18);
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
updateCamera();
});
canvas.addEventListener('pointerup', event => {
if (!pointerDown || event.pointerId !== pointerDown.pointerId) return;
const wasClick = !pointerDown.moved;
pointerDown = null;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
if (wasClick) handlePick(event);
});
canvas.addEventListener('pointercancel', () => { pointerDown = null; });
canvas.addEventListener('contextmenu', event => event.preventDefault());
canvas.addEventListener('wheel', event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.009,
9.5,
21
);
updateCamera();
}, { passive: false });
function resetCamera() {
cameraState.yaw = 0.48;
cameraState.pitch = 0.72;
cameraState.distance = 14.8;
cameraTarget.set(0.15, 0.45, 0.15);
updateCamera();
}
function newGame() {
state = createInitialState();
undoStack.length = 0;
selectedId = 'w-knight-b1';
challenge = { active: false, done: false };
$('challengeStatus').textContent = 'Selecione o peão de e2 para começar.';
updateAll();
}
function undoMove() {
if (!undoStack.length) return;
state = JSON.parse(undoStack.pop());
selectedId = null;
updateAll();
$('challengeStatus').textContent = 'Último lance desfeito.';
}
function startChallenge() {
challenge = { active: true, done: false };
const pawn = pieceById('w-p-e2');
if (!pawn) return;
selectedId = pawn.id;
$('challengeStatus').textContent = 'Agora clique na casa e3 destacada.';
updateAll();
}
function runDiagnostics(showMessage = true) {
const savedState = JSON.stringify(state);
const savedSelection = selectedId;
let checks = 0;
const failures = [];
function check(condition, message) {
checks++;
if (!condition) failures.push(message);
}
try {
const knight = pieceById('w-n-b1');
const knightDestinations = knight ? legalDestinations(knight) : [];
const knightMesh = pieceById('w-n-b1') ? pieceMeshes.get('w-n-b1') : null;
const b1World = worldForSquare('b1');
check(!!knight, 'Cavalo de b1 não encontrado');
check(knightDestinations.includes('a3'), 'Cavalo de b1 deveria alcançar a3');
check(knightDestinations.includes('c3'), 'Cavalo de b1 deveria alcançar c3');
check(!knightDestinations.includes('d2'), 'Cavalo de b1 não pode atravessar o peão de d2');
check(knightDestinations.length === 2, 'Cavalo de b1 deveria ter exatamente dois destinos');
check(!!knightMesh && Math.abs(knightMesh.position.x - b1World.x) < 0.001 && Math.abs(knightMesh.position.z - b1World.z) < 0.001,
'Geometria do cavalo de b1 está deslocada');
const pawn = pieceById('w-p-e2');
check(!!pawn, 'Peão de e2 não encontrado');
check(!!pawn && legalDestinations(pawn).includes('e3'), 'Peão de e2 deveria alcançar e3');
const before = materialScores();
if (pawn) {
commitMove(pawn, 'e3', { animate: false, record: false, announce: false });
}
const movedPawn = pieceById('w-p-e2');
const movedMesh = movedPawn ? pieceMeshes.get(movedPawn.id) : null;
const e3World = worldForSquare('e3');
const after = materialScores();
check(!pieceAt('e2'), 'A casa lógica e2 ainda aparece ocupada após o lance');
check(!!movedPawn && movedPawn.square === 'e3', 'O estado lógico não moveu o peão para e3');
check(!!movedMesh && Math.abs(movedMesh.position.x - e3World.x) < 0.001 && Math.abs(movedMesh.position.z - e3World.z) < 0.001,
'A geometria do peão não ocupou o centro de e3');
check(after.diff === before.diff && after.diff === 0, 'Um lance sem captura alterou a vantagem de material');
check(state.capturedBy.w.length === 0 && state.capturedBy.b.length === 0, 'Um lance sem captura registrou captura');
state = JSON.parse(savedState);
rebuildPieces();
selectedId = savedSelection || 'w-knight-b1';
updateAll();
if (failures.length) throw new Error(failures.join('; '));
$('diagnostic').classList.remove('bad');
$('diagnostic').textContent = `Auto-teste: ${checks}/${checks} verificações OK. b1 → a3/c3; e2–e3 ocupou e3; material Δ0; captura 0.`;
} catch (error) {
state = JSON.parse(savedState);
rebuildPieces();
selectedId = savedSelection || 'w-knight-b1';
updateAll();
$('diagnostic').classList.add('bad');
$('diagnostic').textContent = `Falha no auto-teste: ${error.message}`;
}
}
$('newGameBtn').addEventListener('click', newGame);
$('undoBtn').addEventListener('click', undoMove);
$('cameraBtn').addEventListener('click', resetCamera);
$('clearBtn').addEventListener('click', clearSelection);
$('testBtn').addEventListener('click', () => runDiagnostics(true));
$('challengeBtn').addEventListener('click', startChallenge);
$('captureBtn').addEventListener('click', () => {
try {
renderer.render(scene, camera);
const link = document.createElement('a');
link.download = 'chess-no-parque.png';
link.href = renderer.domElement.toDataURL('image/png');
link.click();
} catch (error) {
$('diagnostic').classList.add('bad');
$('diagnostic').textContent = `Não foi possível capturar a cena: ${error.message}`;
}
});
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
});
window.addEventListener('keydown', event => {
if (event.key === 'Escape') clearSelection();
});
selectedId = 'w-knight-b1';
updateAll();
function animate(now) {
requestAnimationFrame(animate);
for (let i = animations.length - 1; i >= 0; i--) {
const animation = animations[i];
const t = THREE.MathUtils.clamp((now - animation.start) / animation.duration, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
animation.mesh.position.lerpVectors(animation.from, animation.to, eased);
if (t >= 1) {
animation.mesh.position.copy(animation.to);
animations.splice(i, 1);
}
}
const pulse = 0.5 + 0.5 * Math.sin(now * 0.004);
for (const entry of markerMaterials) {
entry.material.opacity = (entry.capture ? 0.32 : 0.22) + pulse * 0.13;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
setTimeout(() => {
runDiagnostics();
$('loading').classList.add('hidden');
}, 120);
</script>
</body>
</html>
```