Com certeza! Criar um Tetris totalmente 3D em um único arquivo HTML é um desafio fantástico que combina lógica de jogo, matemática 3D e renderização em tempo real.
Aqui está uma implementação completa e funcional. O jogo acontece em um poço 3D, as peças (agora "policubos") podem ser movidas nos eixos X e Z, e rotacionadas nos 3 eixos (X, Y e Z). A "limpeza de linha" se torna uma "limpeza de camada".
Funcionalidades:
- Grade 3D: O jogo se passa em um espaço 3D (10x20x10).
- Peças 3D (Tetracubos): As 7 peças clássicas do Tetris, construídas com cubos.
- Movimentação 3D:
- Setas: Movem a peça no plano XZ (chão).
- PageUp/PageDown: Movem a peça para cima e para baixo (não é parte do Tetris clássico, mas útil para o 3D).
- SHIFT: Acelera a queda (Soft Drop).
- ESPAÇO: Queda instantânea (Hard Drop).
- Rotação 3D:
- Q/W: Rotação no eixo X.
- A/S: Rotação no eixo Y.
- Z/X: Rotação no eixo Z.
- Câmera 3D: Use o mouse para girar a câmera e ver o jogo de qualquer ângulo. Use o scroll para dar zoom.
- Limpeza de Camada: Quando um plano XZ inteiro é preenchido, essa camada é limpa e as camadas de cima descem.
- Tudo em 1 Arquivo: HTML, CSS e JavaScript (usando a biblioteca Three.js via CDN) estão contidos em um único arquivo.
Como Usar:
- Copie todo o código abaixo.
- Cole em um novo arquivo de texto.
- Salve o arquivo com a extensão
.html (por exemplo, tetris3d.html).
- Abra esse arquivo em um navegador moderno (Chrome, Firefox, Edge, etc.).
Código Completo
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris 3D</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: 'Arial', sans-serif;
background-color: #111;
color: #eee;
}
#info {
position: absolute;
top: 10px;
left: 10px;
padding: 10px;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 8px;
border: 1px solid #444;
max-width: 300px;
}
h1 {
margin: 0 0 10px 0;
font-size: 1.5em;
}
p {
margin: 5px 0;
}
kbd {
background-color: #333;
border: 1px solid #555;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 40px;
background-color: rgba(200, 0, 0, 0.85);
border: 2px solid #fff;
border-radius: 10px;
text-align: center;
display: none; /* Inicia escondido */
font-size: 2em;
color: white;
text-shadow: 2px 2px 4px #000;
}
#game-over button {
margin-top: 20px;
padding: 10px 20px;
font-size: 0.8em;
cursor: pointer;
border: none;
border-radius: 5px;
background-color: #fff;
color: #c00;
}
</style>
</head>
<body>
<div id="info">
<h1>Tetris 3D</h1>
<p><strong>Pontos:</strong> <span id="score">0</span></p>
<p><strong>Nível:</strong> <span id="level">1</span></p>
<hr>
<p><strong>Controles:</strong></p>
<p><kbd>Mouse</kbd> - Girar Câmera</p>
<p><kbd>Setas</kbd> - Mover no Chão</p>
<p><kbd>Q</kbd><kbd>W</kbd> <kbd>A</kbd><kbd>S</kbd> <kbd>Z</kbd><kbd>X</kbd> - Rotacionar</p>
<p><kbd>Shift</kbd> - Acelerar Queda</p>
<p><kbd>Espaço</kbd> - Queda Instantânea</p>
</div>
<div id="game-over">
FIM DE JOGO
<button onclick="window.location.reload()">Jogar Novamente</button>
</div>
<!-- Importa a biblioteca Three.js e os controles de órbita -->
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.157.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.157.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// --- CONFIGURAÇÕES GLOBAIS ---
const GRID_WIDTH = 10;
const GRID_HEIGHT = 20;
const GRID_DEPTH = 10;
const CUBE_SIZE = 1;
// --- VARIÁVEIS DE JOGO ---
let scene, camera, renderer, controls;
let gameGrid; // Matriz 3D para lógica do jogo
let currentPiece;
let score = 0;
let level = 1;
let dropInterval = 1000; // Milissegundos
let lastDropTime = 0;
let isGameOver = false;
let staticCubesGroup; // Grupo para cubos já posicionados
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const gameOverElement = document.getElementById('game-over');
// --- DEFINIÇÃO DAS PEÇAS (TETRACUBOS) ---
// Coordenadas relativas ao pivô da peça
const PIECES = [
{ // I
color: 0x00ffff,
shape: [[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0]]
},
{ // O
color: 0xffff00,
shape: [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]
},
{ // T
color: 0x800080,
shape: [[0, 0, 0], [1, 0, 0], [-1, 0, 0], [0, 1, 0]]
},
{ // L
color: 0xffa500,
shape: [[0, 0, 0], [0, 1, 0], [0, 2, 0], [1, 0, 0]]
},
{ // J
color: 0x0000ff,
shape: [[0, 0, 0], [0, 1, 0], [0, 2, 0], [-1, 0, 0]]
},
{ // S
color: 0x00ff00,
shape: [[0, 0, 0], [1, 0, 0], [0, 1, 0], [-1, 1, 0]]
},
{ // Z
color: 0xff0000,
shape: [[0, 0, 0], [-1, 0, 0], [0, 1, 0], [1, 1, 0]]
}
];
// --- FUNÇÃO DE INICIALIZAÇÃO ---
function init() {
// Cena
scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a1a2a);
// Câmera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(GRID_WIDTH * 1.2, GRID_HEIGHT * 1.2, GRID_DEPTH * 1.2);
// Renderizador
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Controles da Câmera
controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(GRID_WIDTH / 2, GRID_HEIGHT / 2, GRID_DEPTH / 2);
controls.update();
// Luzes
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(15, 30, 20);
directionalLight.castShadow = true;
scene.add(directionalLight);
// Helpers Visuais (grade e caixa do poço)
const gridHelper = new THREE.GridHelper(GRID_WIDTH, GRID_WIDTH);
gridHelper.position.set(GRID_WIDTH / 2 - CUBE_SIZE / 2, -CUBE_SIZE / 2, GRID_DEPTH / 2 - CUBE_SIZE / 2);
scene.add(gridHelper);
const boxGeometry = new THREE.BoxGeometry(GRID_WIDTH, GRID_HEIGHT, GRID_DEPTH);
const edges = new THREE.EdgesGeometry(boxGeometry);
const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0x888888 }));
line.position.set(GRID_WIDTH / 2 - CUBE_SIZE / 2, GRID_HEIGHT / 2 - CUBE_SIZE / 2, GRID_DEPTH / 2 - CUBE_SIZE / 2);
scene.add(line);
// Grupo para os cubos estáticos
staticCubesGroup = new THREE.Group();
scene.add(staticCubesGroup);
// Lógica do jogo
initializeGrid();
spawnNewPiece();
// Event Listeners
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('keydown', onKeyDown);
// Inicia o loop do jogo
animate();
}
function initializeGrid() {
gameGrid = Array(GRID_DEPTH).fill(0).map(() =>
Array(GRID_HEIGHT).fill(0).map(() =>
Array(GRID_WIDTH).fill(0)
)
);
}
// --- LÓGICA DO JOGO ---
function spawnNewPiece() {
const pieceData = PIECES[Math.floor(Math.random() * PIECES.length)];
// Remove a peça anterior da cena
if (currentPiece && currentPiece.mesh) {
scene.remove(currentPiece.mesh);
}
currentPiece = {
x: Math.floor(GRID_WIDTH / 2) -1,
y: GRID_HEIGHT - 3, // Iniciar mais alto
z: Math.floor(GRID_DEPTH / 2) -1,
color: pieceData.color,
shape: JSON.parse(JSON.stringify(pieceData.shape)), // Cópia profunda
mesh: createPieceMesh(pieceData)
};
scene.add(currentPiece.mesh);
updatePiecePosition();
if (checkCollision(currentPiece.x, currentPiece.y, currentPiece.z, currentPiece.shape)) {
gameOver();
}
}
function createPieceMesh(pieceData) {
const group = new THREE.Group();
const material = new THREE.MeshLambertMaterial({ color: pieceData.color });
const geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const edgeGeometry = new THREE.EdgesGeometry(geometry);
const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x000000, linewidth: 2 });
pieceData.shape.forEach(pos => {
const cube = new THREE.Mesh(geometry, material);
cube.position.set(pos[0], pos[1], pos[2]);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
cube.add(edges);
group.add(cube);
});
return group;
}
function updatePiecePosition() {
if (currentPiece && currentPiece.mesh) {
currentPiece.mesh.position.set(
currentPiece.x,
currentPiece.y,
currentPiece.z
);
}
}
function checkCollision(x, y, z, shape) {
for (let i = 0; i < shape.length; i++) {
const block = shape[i];
const newX = x + block[0];
const newY = y + block[1];
const newZ = z + block[2];
// Checar limites do poço
if (newX < 0 || newX >= GRID_WIDTH || newZ < 0 || newZ >= GRID_DEPTH || newY < 0) {
return true;
}
// Checar colisão com outros blocos (com segurança para 'newY' alto)
if (newY < GRID_HEIGHT && gameGrid[newZ][newY][newX] !== 0) {
return true;
}
}
return false;
}
function lockPiece() {
const material = new THREE.MeshLambertMaterial({ color: currentPiece.color });
const geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const edgeGeometry = new THREE.EdgesGeometry(geometry);
const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x000000, linewidth: 2 });
currentPiece.shape.forEach(pos => {
const x = currentPiece.x + pos[0];
const y = currentPiece.y + pos[1];
const z = currentPiece.z + pos[2];
if (y < GRID_HEIGHT) {
gameGrid[z][y][x] = currentPiece.color;
const cube = new THREE.Mesh(geometry, material);
cube.position.set(x, y, z);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
cube.add(edges);
staticCubesGroup.add(cube);
}
});
scene.remove(currentPiece.mesh);
checkAndClearLayers();
spawnNewPiece();
}
function checkAndClearLayers() {
let layersCleared = 0;
for (let y = 0; y < GRID_HEIGHT; y++) {
let isLayerFull = true;
for (let z = 0; z < GRID_DEPTH; z++) {
for (let x = 0; x < GRID_WIDTH; x++) {
if (gameGrid[z][y][x] === 0) {
isLayerFull = false;
break;
}
}
if (!isLayerFull) break;
}
if (isLayerFull) {
layersCleared++;
// Remove a camada da matriz lógica
for (let yShift = y; yShift < GRID_HEIGHT - 1; yShift++) {
for (let z = 0; z < GRID_DEPTH; z++) {
for (let x = 0; x < GRID_WIDTH; x++) {
gameGrid[z][yShift][x] = gameGrid[z][yShift + 1][x];
}
}
}
// Limpa a camada superior
for (let z = 0; z < GRID_DEPTH; z++) {
for (let x = 0; x < GRID_WIDTH; x++) {
gameGrid[z][GRID_HEIGHT - 1][x] = 0;
}
}
y--; // Re-checar a mesma camada, pois ela agora contém o conteúdo da de cima
}
}
if (layersCleared > 0) {
updateScore(layersCleared);
redrawStaticCubes();
}
}
function redrawStaticCubes() {
// Limpa o grupo visual
while(staticCubesGroup.children.length > 0){
staticCubesGroup.remove(staticCubesGroup.children[0]);
}
// Redesenha baseado no gameGrid
const geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const edgeGeometry = new THREE.EdgesGeometry(geometry);
const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x000000, linewidth: 2 });
for (let z = 0; z < GRID_DEPTH; z++) {
for (let y = 0; y < GRID_HEIGHT; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
if (gameGrid[z][y][x] !== 0) {
const color = gameGrid[z][y][x];
const material = new THREE.MeshLambertMaterial({ color: color });
const cube = new THREE.Mesh(geometry, material);
cube.position.set(x, y, z);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
cube.add(edges);
staticCubesGroup.add(cube);
}
}
}
}
}
function updateScore(layersCleared) {
const points = [0, 100, 300, 500, 800]; // Pontos por 0, 1, 2, 3, 4 camadas
score += points[layersCleared] * level;
scoreElement.innerText = score;
// Aumentar o nível e a velocidade
if (score > level * 1000) {
level++;
levelElement.innerText = level;
dropInterval = Math.max(100, dropInterval * 0.9);
}
}
function gameOver() {
isGameOver = true;
gameOverElement.style.display = 'block';
console.log("FIM DE JOGO");
}
// --- CONTROLES E MOVIMENTAÇÃO ---
function onKeyDown(event) {
if (isGameOver) return;
let moved = false;
let tempShape;
switch (event.key) {
// Movimento
case 'ArrowLeft':
if (!checkCollision(currentPiece.x - 1, currentPiece.y, currentPiece.z, currentPiece.shape)) {
currentPiece.x--;
moved = true;
}
break;
case 'ArrowRight':
if (!checkCollision(currentPiece.x + 1, currentPiece.y, currentPiece.z, currentPiece.shape)) {
currentPiece.x++;
moved = true;
}
break;
case 'ArrowDown': // Move para "trás" no eixo Z
if (!checkCollision(currentPiece.x, currentPiece.y, currentPiece.z + 1, currentPiece.shape)) {
currentPiece.z++;
moved = true;
}
break;
case 'ArrowUp': // Move para "frente" no eixo Z
if (!checkCollision(currentPiece.x, currentPiece.y, currentPiece.z - 1, currentPiece.shape)) {
currentPiece.z--;
moved = true;
}
break;
// Rotações
case 'w': tempShape = rotateShape(currentPiece.shape, 'x', 1); break;
case 'q': tempShape = rotateShape(currentPiece.shape, 'x', -1); break;
case 's': tempShape = rotateShape(currentPiece.shape, 'y', 1); break;
case 'a': tempShape = rotateShape(currentPiece.shape, 'y', -1); break;
case 'x': tempShape = rotateShape(currentPiece.shape, 'z', 1); break;
case 'z': tempShape = rotateShape(currentPiece.shape, 'z', -1); break;
// Queda
case 'Shift':
if (!checkCollision(currentPiece.x, currentPiece.y - 1, currentPiece.z, currentPiece.shape)) {
currentPiece.y--;
lastDropTime = performance.now(); // Resetar timer da gravidade
moved = true;
}
break;
case ' ': // Hard Drop
while (!checkCollision(currentPiece.x, currentPiece.y - 1, currentPiece.z, currentPiece.shape)) {
currentPiece.y--;
}
lockPiece();
moved = true;
break;
}
if (tempShape) {
if (!checkCollision(currentPiece.x, currentPiece.y, currentPiece.z, tempShape)) {
currentPiece.shape = tempShape;
// Atualizar a malha visual
scene.remove(currentPiece.mesh);
const pieceData = { color: currentPiece.color, shape: currentPiece.shape };
currentPiece.mesh = createPieceMesh(pieceData);
scene.add(currentPiece.mesh);
moved = true;
}
}
if (moved) {
updatePiecePosition();
}
}
function rotateShape(shape, axis, direction) {
const newShape = [];
const angle = direction * Math.PI / 2; // 90 graus
for (const p of shape) {
let [x, y, z] = p;
let newX, newY, newZ;
if (axis === 'x') {
newY = Math.round(y * Math.cos(angle) - z * Math.sin(angle));
newZ = Math.round(y * Math.sin(angle) + z * Math.cos(angle));
newX = x;
} else if (axis === 'y') {
newX = Math.round(x * Math.cos(angle) + z * Math.sin(angle));
newZ = Math.round(-x * Math.sin(angle) + z * Math.cos(angle));
newY = y;
} else { // axis === 'z'
newX = Math.round(x * Math.cos(angle) - y * Math.sin(angle));
newY = Math.round(x * Math.sin(angle) + y * Math.cos(angle));
newZ = z;
}
newShape.push([newX, newY, newZ]);
}
return newShape;
}
// --- LOOP DE ANIMAÇÃO E RENDERIZAÇÃO ---
function animate(time) {
if (isGameOver) return;
requestAnimationFrame(animate);
// Lógica de queda automática (gravidade)
if (time - lastDropTime > dropInterval) {
if (!checkCollision(currentPiece.x, currentPiece.y - 1, currentPiece.z, currentPiece.shape)) {
currentPiece.y--;
updatePiecePosition();
} else {
lockPiece();
}
lastDropTime = time;
}
controls.update();
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Iniciar o jogo
init();
</script>
</body>
</html>