Files

403 lines
10 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tic-Tac-Toe 3D</title>
<style>
html, body {
margin: 0;
height: 100%;
overflow: hidden;
background: #0b1020;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
#app { position: fixed; inset: 0; }
#app canvas { display: block; width: 100%; height: 100%; }
#hud {
position: fixed;
top: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 18px 22px;
pointer-events: none;
color: #e8ecf5;
}
#status {
margin: 0;
font-size: 22px;
font-weight: 600;
letter-spacing: 0.02em;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.55);
}
#status.winner { color: #7ef0b2; }
#status.draw { color: #ffd166; }
#restart {
pointer-events: auto;
font: inherit;
font-size: 15px;
font-weight: 600;
color: #e8ecf5;
background: rgba(120, 150, 220, 0.18);
border: 1px solid rgba(160, 190, 255, 0.35);
border-radius: 10px;
padding: 10px 16px;
cursor: pointer;
}
#restart:hover { background: rgba(120, 150, 220, 0.32); }
#hint {
position: fixed;
left: 22px;
bottom: 18px;
margin: 0;
font-size: 13px;
color: rgba(232, 236, 245, 0.55);
pointer-events: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div id="hud">
<p id="status">X's turn</p>
<button id="restart" type="button">Restart</button>
</div>
<p id="hint">Click a square to place a mark. X moves first.</p>
<script type="module">
import * as THREE from './three.module.min.js';
const LINES = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
];
const CELL = 1.5;
const STEP = 1.7;
const COLORS = {
x: 0xff6b6b,
o: 0x53c8ff,
tile: 0x1b2440,
tileHover: 0x27365d,
};
const IDLE_EMISSIVE = new THREE.Color(0x000000);
const HOVER_EMISSIVE = new THREE.Color(COLORS.tileHover).multiplyScalar(0.35);
const WIN_EMISSIVE = new THREE.Color(0x1c3a2a);
const statusEl = document.getElementById('status');
const restartBtn = document.getElementById('restart');
const appEl = document.getElementById('app');
let scene;
let renderer, camera, raycaster;
let tiles = [];
let marks = new Array(9).fill(null);
let winBeam = null;
let winCells = [];
const board = new Array(9).fill(null);
const pointer = new THREE.Vector2();
const boardPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0.12);
const hitPoint = new THREE.Vector3();
const animations = [];
let current = 'X';
let gameOver = false;
let hoverIndex = -1;
function cellPosition(index) {
const row = Math.floor(index / 3);
const col = index % 3;
return new THREE.Vector3((col - 1) * STEP, 0, (row - 1) * STEP);
}
function buildScene() {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1020);
camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
camera.position.set(0, 7.4, 7.6);
camera.lookAt(0, 0, 0);
scene.add(new THREE.AmbientLight(0xffffff, 0.55));
const key = new THREE.DirectionalLight(0xffffff, 1.1);
key.position.set(4, 8, 6);
scene.add(key);
const rim = new THREE.DirectionalLight(0x88aaff, 0.4);
rim.position.set(-5, 3, -4);
scene.add(rim);
const plate = new THREE.Mesh(
new THREE.BoxGeometry(STEP * 3 + 0.5, 0.3, STEP * 3 + 0.5),
new THREE.MeshStandardMaterial({ color: 0x121a30, roughness: 0.85, metalness: 0.1 }),
);
plate.position.y = -0.45;
scene.add(plate);
for (let index = 0; index < 9; index += 1) {
const material = new THREE.MeshStandardMaterial({
color: COLORS.tile,
roughness: 0.6,
metalness: 0.15,
emissive: 0x000000,
});
const tile = new THREE.Mesh(new THREE.BoxGeometry(CELL, 0.24, CELL), material);
const position = cellPosition(index);
tile.position.set(position.x, -0.12, position.z);
tile.userData.index = index;
tile.userData.baseY = tile.position.y;
tiles.push(tile);
scene.add(tile);
}
return scene;
}
function createMark(player, index) {
const group = new THREE.Group();
if (player === 'X') {
const material = new THREE.MeshStandardMaterial({
color: COLORS.x,
roughness: 0.42,
metalness: 0.25,
emissive: 0x3a0d0d,
});
const bar = new THREE.BoxGeometry(1.0, 0.2, 0.2);
const first = new THREE.Mesh(bar, material);
first.rotation.y = Math.PI / 4;
const second = new THREE.Mesh(bar, material);
second.rotation.y = -Math.PI / 4;
group.add(first, second);
} else {
const material = new THREE.MeshStandardMaterial({
color: COLORS.o,
roughness: 0.42,
metalness: 0.25,
emissive: 0x06283a,
});
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.42, 0.11, 18, 44), material);
ring.rotation.x = -Math.PI / 2;
group.add(ring);
}
const position = cellPosition(index);
group.position.set(position.x, 0.34, position.z);
group.scale.setScalar(0.01);
animations.push({ object: group, start: performance.now(), duration: 260 });
return group;
}
function showWinBeam(line, player) {
const from = cellPosition(line[0]);
const to = cellPosition(line[2]);
const start = new THREE.Vector3(from.x, 0.34, from.z);
const end = new THREE.Vector3(to.x, 0.34, to.z);
const length = start.distanceTo(end);
const beam = new THREE.Mesh(
new THREE.CylinderGeometry(0.06, 0.06, length, 16),
new THREE.MeshStandardMaterial({
color: player === 'X' ? COLORS.x : COLORS.o,
emissive: player === 'X' ? 0x8c2020 : 0x146a99,
roughness: 0.3,
metalness: 0.4,
}),
);
beam.position.copy(start).add(end).multiplyScalar(0.5);
beam.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
end.clone().sub(start).normalize(),
);
winBeam = beam;
return beam;
}
function evaluate(state) {
for (const line of LINES) {
const a = state[line[0]];
if (a && a === state[line[1]] && a === state[line[2]]) {
return { winner: a, line: line };
}
}
if (state.every((value) => value !== null)) {
return { winner: null, line: null, draw: true };
}
return null;
}
function renderStatus() {
statusEl.classList.remove('winner', 'draw');
if (gameOver) {
const outcome = evaluate(board);
if (outcome && outcome.winner) {
statusEl.textContent = outcome.winner + ' wins';
statusEl.classList.add('winner');
} else {
statusEl.textContent = 'Draw';
statusEl.classList.add('draw');
}
} else {
statusEl.textContent = current + "'s turn";
}
}
function clearBoard() {
for (let index = 0; index < 9; index += 1) {
const mark = marks[index];
if (mark) {
if (mark.parent) {
mark.parent.remove(mark);
}
marks[index] = null;
}
}
if (winBeam) {
if (winBeam.parent) {
winBeam.parent.remove(winBeam);
}
winBeam = null;
}
animations.length = 0;
for (const tile of tiles) {
tile.material.emissive.copy(IDLE_EMISSIVE);
tile.position.y = tile.userData.baseY;
}
winCells = [];
board.fill(null);
current = 'X';
gameOver = false;
hoverIndex = -1;
renderStatus();
}
function placeMark(index) {
board[index] = current;
const mark = createMark(current, index);
marks[index] = mark;
scene.add(mark);
const outcome = evaluate(board);
if (outcome && outcome.winner) {
gameOver = true;
scene.add(showWinBeam(outcome.line, outcome.winner));
winCells = outcome.line.slice();
} else if (outcome && outcome.draw) {
gameOver = true;
} else {
current = current === 'X' ? 'O' : 'X';
}
renderStatus();
}
function indexFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
return -1;
}
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(boardPlane, hitPoint) === null) {
return -1;
}
const col = Math.round(hitPoint.x / STEP);
const row = Math.round(hitPoint.z / STEP);
if (col < -1 || col > 1 || row < -1 || row > 1) {
return -1;
}
return (row + 1) * 3 + (col + 1);
}
function onPointerDown(event) {
if (gameOver) {
return;
}
const index = indexFromEvent(event);
if (index < 0 || board[index] !== null) {
return;
}
hoverIndex = -1;
placeMark(index);
}
function onPointerMove(event) {
if (gameOver) {
hoverIndex = -1;
return;
}
const index = indexFromEvent(event);
hoverIndex = index >= 0 && board[index] === null ? index : -1;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function boot() {
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(0x0b1020, 1);
appEl.appendChild(renderer.domElement);
scene = buildScene();
raycaster = new THREE.Raycaster();
resize();
window.addEventListener('resize', resize);
renderer.domElement.addEventListener('click', onPointerDown);
renderer.domElement.addEventListener('pointermove', onPointerMove);
restartBtn.addEventListener('click', clearBoard);
renderStatus();
const clock = new THREE.Clock();
renderer.setAnimationLoop(function animate() {
const now = performance.now();
for (let i = animations.length - 1; i >= 0; i -= 1) {
const animation = animations[i];
const t = Math.min((now - animation.start) / animation.duration, 1);
const eased = 1 - Math.pow(1 - t, 3);
animation.object.scale.setScalar(0.01 + 0.99 * eased);
if (t >= 1) {
animation.object.scale.setScalar(1);
animations.splice(i, 1);
}
}
for (let index = 0; index < 9; index += 1) {
const tile = tiles[index];
const targetY = index === hoverIndex ? tile.userData.baseY + 0.12 : tile.userData.baseY;
tile.position.y += (targetY - tile.position.y) * 0.2;
const targetEmissive = winCells.indexOf(index) >= 0 ? WIN_EMISSIVE : index === hoverIndex ? HOVER_EMISSIVE : IDLE_EMISSIVE;
tile.material.emissive.lerp(targetEmissive, 0.18);
}
if (winBeam) {
const pulse = 1 + Math.sin(clock.getElapsedTime() * 4) * 0.12;
winBeam.scale.set(pulse, 1, pulse);
}
renderer.render(scene, camera);
});
}
try {
boot();
} catch (error) {
statusEl.textContent = 'WebGL is not available in this browser.';
console.error(error);
}
</script>
</body>
</html>