construa, em um unico html, um jogo 2d estilo terraria. monte o melhor jogo que vc…
- User
construa, em um unico html, um jogo 2d estilo terraria. monte o melhor jogo que vc conseguir
Assistant
Mini Terra: Uma Aventura em HTML
Claro! Desafio aceito. Construí um jogo 2D estilo sandbox inspirado em Terraria, totalmente contido em um único arquivo HTML. Ele inclui:
- Mundo Gerado Proceduralmente: Cada vez que você recarrega a página, um novo mundo com colinas, cavernas e minérios é criado.
- Ciclo Dia/Noite: O céu muda de cor, criando uma atmosfera dinâmica.
- Física Básica: O jogador tem gravidade e pode pular.
- Mineração e Construção: Use o clique esquerdo para quebrar blocos e o clique direito para colocar blocos.
- Inventário Simples: Os blocos que você quebra são adicionados ao seu inventário. Use a roda do mouse ou as teclas 1 e 2 para selecionar qual bloco colocar.
- Câmera Dinâmica: A câmera segue o jogador enquanto ele explora o mundo.
Para jogar:
- Copie todo o código abaixo.
- Cole-o em um editor de texto (como Bloco de Notas, VS Code, etc.).
- Salve o arquivo com a extensão
.html(por exemplo,jogo_terraria.html). - Abra o arquivo salvo em qualquer navegador de internet moderno (Chrome, Firefox, Edge).
O Jogo (Código Fonte Completo)
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mini Terra - Aventura em HTML</title> <style> body { margin: 0; padding: 0; background-color: #111; color: #eee; font-family: 'Courier New', Courier, monospace; display: flex; justify-content: center; align-items: center; height: 100vh; overflow: hidden; } #game-container { position: relative; border: 2px solid #555; box-shadow: 0 0 20px rgba(0, 255, 255, 0.3); } canvas { display: block; background-color: #87CEEB; /* Sky Blue */ } #ui-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; /* Permite cliques através da UI */ display: flex; flex-direction: column; justify-content: space-between; padding: 10px; box-sizing: border-box; } .info-box, .inventory-box { background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; border: 1px solid rgba(255, 255, 255, 0.2); } .info-box { max-width: 350px; } .inventory-box { align-self: center; display: flex; gap: 10px; } .inventory-slot { width: 50px; height: 50px; border: 2px solid #888; background-color: rgba(0,0,0,0.4); display: flex; justify-content: center; align-items: center; font-size: 10px; position: relative; } .inventory-slot.selected { border-color: #FFF; box-shadow: 0 0 10px #0FF; } .slot-block { width: 30px; height: 30px; } .slot-count { position: absolute; bottom: 2px; right: 4px; font-size: 14px; font-weight: bold; text-shadow: 1px 1px 2px black; } </style> </head> <body> <div id="game-container"> <canvas id="gameCanvas"></canvas> <div id="ui-container"> <div class="info-box"> <strong>Controles:</strong><br> - <strong>A / D</strong> ou <strong>← / →</strong>: Mover<br> - <strong>W / ↑</strong> ou <strong>Espaço</strong>: Pular<br> - <strong>Clique Esquerdo:</strong> Quebrar Bloco<br> - <strong>Clique Direito:</strong> Colocar Bloco<br> - <strong>Roda do Mouse / 1 / 2:</strong> Mudar item </div> <div id="inventory" class="inventory-box"> <!-- Slots de inventário serão gerados aqui --> </div> </div> </div> <script> // --- SETUP INICIAL --- const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const inventoryUI = document.getElementById('inventory'); // --- CONSTANTES DO JOGO --- const BLOCK_SIZE = 32; const WORLD_WIDTH = 500; // em blocos const WORLD_HEIGHT = 200; // em blocos const GRAVITY = 0.8; const PLAYER_SPEED = 5; const JUMP_FORCE = 15; // --- DEFINIÇÃO DOS BLOCOS --- const BLOCK_TYPES = { AIR: 0, GRASS: 1, DIRT: 2, STONE: 3, WOOD: 4, LEAVES: 5, COAL: 6, IRON: 7, }; const BLOCK_COLORS = { [BLOCK_TYPES.AIR]: 'transparent', [BLOCK_TYPES.GRASS]: '#6A994E', [BLOCK_TYPES.DIRT]: '#A98467', [BLOCK_TYPES.STONE]: '#808080', [BLOCK_TYPES.WOOD]: '#6f4e37', [BLOCK_TYPES.LEAVES]: '#386641', [BLOCK_TYPES.COAL]: '#333333', [BLOCK_TYPES.IRON]: '#B27F63', }; const BLOCK_NAMES = { [BLOCK_TYPES.GRASS]: 'Grama', [BLOCK_TYPES.DIRT]: 'Terra', [BLOCK_TYPES.STONE]: 'Pedra', [BLOCK_TYPES.WOOD]: 'Madeira', [BLOCK_TYPES.LEAVES]: 'Folhas', [BLOCK_TYPES.COAL]: 'Carvão', [BLOCK_TYPES.IRON]: 'Ferro', }; // --- ESTADO DO JOGO --- let world = []; const player = { x: (WORLD_WIDTH * BLOCK_SIZE) / 2, y: 0, // Será definido após a geração do mundo width: BLOCK_SIZE * 0.8, height: BLOCK_SIZE * 1.8, vx: 0, vy: 0, onGround: false, }; const camera = { x: 0, y: 0, }; const mouse = { x: 0, y: 0, worldX: 0, worldY: 0, }; const keys = {}; let timeOfDay = 0; // 0 = meio-dia, PI = meia-noite const DAY_CYCLE_SPEED = 0.0005; let inventory = { [BLOCK_TYPES.DIRT]: 20, [BLOCK_TYPES.STONE]: 10, }; let placeableBlocks = [BLOCK_TYPES.DIRT, BLOCK_TYPES.STONE]; let selectedBlockIndex = 0; // --- GERAÇÃO DO MUNDO --- function generateWorld() { console.log("Gerando novo mundo..."); world = Array.from({ length: WORLD_WIDTH }, () => Array(WORLD_HEIGHT).fill(BLOCK_TYPES.AIR)); // Gerar terreno com Perlin-like noise let surfaceLevel = WORLD_HEIGHT / 2; let noise = 0; for (let x = 0; x < WORLD_WIDTH; x++) { noise += (Math.random() - 0.5) * 2; if (Math.random() < 0.1) noise = (Math.random() - 0.5); surfaceLevel += noise; if (surfaceLevel < WORLD_HEIGHT * 0.4) surfaceLevel = WORLD_HEIGHT * 0.4; if (surfaceLevel > WORLD_HEIGHT * 0.6) surfaceLevel = WORLD_HEIGHT * 0.6; const surfaceY = Math.floor(surfaceLevel); for (let y = surfaceY; y < WORLD_HEIGHT; y++) { if (y === surfaceY) { world[x][y] = BLOCK_TYPES.GRASS; } else if (y < surfaceY + 5) { world[x][y] = BLOCK_TYPES.DIRT; } else { // Adicionar minérios const p = Math.random(); if (p < 0.05) world[x][y] = BLOCK_TYPES.COAL; else if (p < 0.08) world[x][y] = BLOCK_TYPES.IRON; else world[x][y] = BLOCK_TYPES.STONE; } } } // Gerar cavernas simples for (let i = 0; i < (WORLD_WIDTH * WORLD_HEIGHT) / 200; i++) { let caveX = Math.floor(Math.random() * WORLD_WIDTH); let caveY = Math.floor(Math.random() * (WORLD_HEIGHT - 80)) + 80; let caveSize = 5 + Math.random() * 15; carveCave(caveX, caveY, caveSize); } // Gerar árvores for (let x = 10; x < WORLD_WIDTH - 10; x++) { if (Math.random() < 0.1) { for (let y = 0; y < WORLD_HEIGHT; y++) { if (world[x][y] === BLOCK_TYPES.GRASS && world[x][y - 1] === BLOCK_TYPES.AIR) { generateTree(x, y - 1); break; } } } } // Posicionar jogador const startX = Math.floor(WORLD_WIDTH / 2); for (let y = 0; y < WORLD_HEIGHT; y++) { if (world[startX][y] !== BLOCK_TYPES.AIR) { player.y = (y - 5) * BLOCK_SIZE; break; } } console.log("Mundo gerado!"); } function carveCave(x, y, radius) { for (let i = -radius; i <= radius; i++) { for (let j = -radius; j <= radius; j++) { if (i*i + j*j <= radius*radius + Math.random() * 5) { const newX = x + i; const newY = y + j; if (newX >= 0 && newX < WORLD_WIDTH && newY >= 0 && newY < WORLD_HEIGHT) { world[newX][newY] = BLOCK_TYPES.AIR; } } } } } function generateTree(x, y) { const height = 4 + Math.floor(Math.random() * 3); // Tronco for (let i = 0; i < height; i++) { if (y - i >= 0) world[x][y - i] = BLOCK_TYPES.WOOD; } // Folhas const canopyY = y - height; for (let dx = -2; dx <= 2; dx++) { for (let dy = -2; dy <= 2; dy++) { if (Math.abs(dx) === 2 && Math.abs(dy) === 2) continue; if(canopyY + dy > 0) world[x + dx][canopyY + dy] = BLOCK_TYPES.LEAVES; } } } // --- LÓGICA DO JOGO (UPDATE) --- function update(deltaTime) { // Movimento do jogador player.vx = 0; if (keys['a'] || keys['ArrowLeft']) player.vx = -PLAYER_SPEED; if (keys['d'] || keys['ArrowRight']) player.vx = PLAYER_SPEED; // Pulo if ((keys['w'] || keys['ArrowUp'] || keys[' ']) && player.onGround) { player.vy = -JUMP_FORCE; player.onGround = false; } // Aplicar física player.vy += GRAVITY; player.x += player.vx; player.y += player.vy; // Colisões com o mundo handleCollisions(); // Limites do mundo if (player.x < 0) player.x = 0; if (player.x + player.width > WORLD_WIDTH * BLOCK_SIZE) { player.x = WORLD_WIDTH * BLOCK_SIZE - player.width; } // Atualizar câmera para seguir o jogador camera.x = player.x - canvas.width / 2; camera.y = player.y - canvas.height / 2; // Manter câmera dentro dos limites do mundo if (camera.x < 0) camera.x = 0; if (camera.y < 0) camera.y = 0; if (camera.x > WORLD_WIDTH * BLOCK_SIZE - canvas.width) camera.x = WORLD_WIDTH * BLOCK_SIZE - canvas.width; if (camera.y > WORLD_HEIGHT * BLOCK_SIZE - canvas.height) camera.y = WORLD_HEIGHT * BLOCK_SIZE - canvas.height; // Atualizar coordenadas do mouse no mundo mouse.worldX = mouse.x + camera.x; mouse.worldY = mouse.y + camera.y; // Atualizar ciclo dia/noite timeOfDay += DAY_CYCLE_SPEED; if (timeOfDay > Math.PI * 2) timeOfDay = 0; } function handleCollisions() { player.onGround = false; const playerLeft = Math.floor(player.x / BLOCK_SIZE); const playerRight = Math.floor((player.x + player.width) / BLOCK_SIZE); const playerTop = Math.floor(player.y / BLOCK_SIZE); const playerBottom = Math.floor((player.y + player.height) / BLOCK_SIZE); for (let x = playerLeft; x <= playerRight; x++) { for (let y = playerTop; y <= playerBottom; y++) { if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT) continue; const block = world[x][y]; if (block !== BLOCK_TYPES.AIR) { const blockX = x * BLOCK_SIZE; const blockY = y * BLOCK_SIZE; // Colisão vertical if (player.y + player.height > blockY && player.y < blockY + BLOCK_SIZE && player.x + player.width > blockX && player.x < blockX + BLOCK_SIZE) { if (player.vy > 0) { // Caindo player.y = blockY - player.height; player.vy = 0; player.onGround = true; } else if (player.vy < 0) { // Batendo a cabeça player.y = blockY + BLOCK_SIZE; player.vy = 0; } } // Colisão horizontal if (player.x + player.width > blockX && player.x < blockX + BLOCK_SIZE && player.y + player.height > blockY + 1 && // +1 para não prender no chão player.y < blockY + BLOCK_SIZE - 1) { if (player.vx > 0) { // Movendo para a direita player.x = blockX - player.width; player.vx = 0; } else if (player.vx < 0) { // Movendo para a esquerda player.x = blockX + BLOCK_SIZE; player.vx = 0; } } } } } } // --- RENDERIZAÇÃO (DRAW) --- function draw() { // Fundo (Céu) const sunAngle = timeOfDay; const r = Math.max(0, 135 * Math.sin(sunAngle) + 20); const g = Math.max(0, 206 * Math.sin(sunAngle) + 20); const b = Math.max(0, 235 * Math.sin(sunAngle) + 50); ctx.fillStyle = `rgb(${r}, ${g}, ${b})`; ctx.fillRect(0, 0, canvas.width, canvas.height); // Salva o estado do canvas e aplica a transformação da câmera ctx.save(); ctx.translate(-camera.x, -camera.y); // Desenhar o mundo const startX = Math.floor(camera.x / BLOCK_SIZE); const endX = Math.ceil((camera.x + canvas.width) / BLOCK_SIZE); const startY = Math.floor(camera.y / BLOCK_SIZE); const endY = Math.ceil((camera.y + canvas.height) / BLOCK_SIZE); for (let x = startX; x < endX; x++) { for (let y = startY; y < endY; y++) { if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT) continue; const blockType = world[x][y]; if (blockType !== BLOCK_TYPES.AIR) { ctx.fillStyle = BLOCK_COLORS[blockType]; ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); } } } // Desenhar o jogador ctx.fillStyle = '#FFADAD'; ctx.fillRect(player.x, player.y, player.width, player.height); // Desenhar a seleção do mouse const mouseBlockX = Math.floor(mouse.worldX / BLOCK_SIZE); const mouseBlockY = Math.floor(mouse.worldY / BLOCK_SIZE); ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)'; ctx.lineWidth = 2; ctx.strokeRect(mouseBlockX * BLOCK_SIZE, mouseBlockY * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); // Restaura o estado do canvas ctx.restore(); // Desenhar UI (fora do save/restore para não ser afetado pela câmera) drawUI(); } function drawUI() { inventoryUI.innerHTML = ''; placeableBlocks.forEach((blockType, index) => { const slot = document.createElement('div'); slot.className = 'inventory-slot'; if (index === selectedBlockIndex) { slot.classList.add('selected'); } const blockDiv = document.createElement('div'); blockDiv.className = 'slot-block'; blockDiv.style.backgroundColor = BLOCK_COLORS[blockType]; const countSpan = document.createElement('span'); countSpan.className = 'slot-count'; countSpan.textContent = inventory[blockType] || 0; slot.appendChild(blockDiv); slot.appendChild(countSpan); inventoryUI.appendChild(slot); }); } // --- CONTROLES E EVENTOS --- window.addEventListener('keydown', (e) => { keys[e.key.toLowerCase()] = true; }); window.addEventListener('keyup', (e) => { keys[e.key.toLowerCase()] = false; }); // Mudar item selecionado window.addEventListener('keydown', (e) => { if (e.key >= '1' && e.key <= '9') { const index = parseInt(e.key) - 1; if (index < placeableBlocks.length) { selectedBlockIndex = index; } } }); canvas.addEventListener('mousemove', (e) => { const rect = canvas.getBoundingClientRect(); mouse.x = e.clientX - rect.left; mouse.y = e.clientY - rect.top; }); canvas.addEventListener('mousedown', (e) => { const blockX = Math.floor(mouse.worldX / BLOCK_SIZE); const blockY = Math.floor(mouse.worldY / BLOCK_SIZE); if (blockX < 0 || blockX >= WORLD_WIDTH || blockY < 0 || blockY >= WORLD_HEIGHT) return; if (e.button === 0) { // Clique esquerdo - Quebrar const blockType = world[blockX][blockY]; if (blockType !== BLOCK_TYPES.AIR) { world[blockX][blockY] = BLOCK_TYPES.AIR; if (BLOCK_NAMES[blockType]) { if (!inventory[blockType]) inventory[blockType] = 0; inventory[blockType]++; // Adicionar ao inventário se não estiver lá if (!placeableBlocks.includes(blockType)) { placeableBlocks.push(blockType); } } } } else if (e.button === 2) { // Clique direito - Colocar const blockToPlace = placeableBlocks[selectedBlockIndex]; if ((inventory[blockToPlace] || 0) > 0 && world[blockX][blockY] === BLOCK_TYPES.AIR) { // Checa se o jogador não está no mesmo espaço const playerRect = {x: player.x, y: player.y, width: player.width, height: player.height}; const blockRect = {x: blockX * BLOCK_SIZE, y: blockY * BLOCK_SIZE, width: BLOCK_SIZE, height: BLOCK_SIZE}; if (!(playerRect.x < blockRect.x + blockRect.width && playerRect.x + playerRect.width > blockRect.x && playerRect.y < blockRect.y + blockRect.height && playerRect.y + playerRect.height > blockRect.y)) { world[blockX][blockY] = blockToPlace; inventory[blockToPlace]--; } } } }); canvas.addEventListener('contextmenu', (e) => e.preventDefault()); // Previne o menu de contexto canvas.addEventListener('wheel', (e) => { if (e.deltaY > 0) { selectedBlockIndex = (selectedBlockIndex + 1) % placeableBlocks.length; } else { selectedBlockIndex = (selectedBlockIndex - 1 + placeableBlocks.length) % placeableBlocks.length; } }); // --- GAME LOOP --- let lastTime = 0; function gameLoop(timestamp) { const deltaTime = timestamp - lastTime; lastTime = timestamp; update(deltaTime / 16.67); // Normalizar para 60fps draw(); requestAnimationFrame(gameLoop); } // --- INICIALIZAÇÃO --- function init() { canvas.width = window.innerWidth * 0.8; canvas.height = window.innerHeight * 0.8; const container = document.getElementById('game-container'); container.style.width = `${canvas.width}px`; container.style.height = `${canvas.height}px`; generateWorld(); requestAnimationFrame(gameLoop); } init(); </script> </body> </html>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.