Vou criar um jogo 2D estilo Terraria completo em um único arquivo HTML. Aqui está:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terraria 2D - Mini Game</title>
<style>
body {
margin: 0;
padding: 0;
background: #1a1a2e;
font-family: Arial, sans-serif;
overflow: hidden;
}
#gameContainer {
position: relative;
width: 100vw;
height: 100vh;
}
#gameCanvas {
border: 2px solid #333;
background: linear-gradient(to bottom, #87CEEB 0%, #87CEEB 30%, #654321 100%);
}
#ui {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: rgba(0,0,0,0.7);
padding: 10px;
border-radius: 5px;
font-size: 14px;
}
#inventory {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 5px;
}
.inventory-slot {
width: 50px;
height: 50px;
border: 2px solid #666;
background: rgba(0,0,0,0.8);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 12px;
cursor: pointer;
position: relative;
}
.inventory-slot.selected {
border-color: #ffd700;
}
.inventory-count {
position: absolute;
bottom: 2px;
right: 2px;
font-size: 10px;
color: #ffd700;
}
#crafting {
position: absolute;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.8);
color: white;
padding: 10px;
border-radius: 5px;
max-width: 200px;
}
.craft-recipe {
margin: 5px 0;
padding: 5px;
border: 1px solid #666;
cursor: pointer;
font-size: 12px;
}
.craft-recipe:hover {
background: rgba(255,255,255,0.1);
}
#controls {
position: absolute;
bottom: 10px;
right: 10px;
color: white;
background: rgba(0,0,0,0.7);
padding: 10px;
border-radius: 5px;
font-size: 12px;
}
</style>
</head>
<body>
<div id="gameContainer">
<canvas id="gameCanvas" width="1200" height="800"></canvas>
<div id="ui">
<div>Vida: <span id="health">100</span>/100</div>
<div>Posição: (<span id="playerX">0</span>, <span id="playerY">0</span>)</div>
<div>Bloco Selecionado: <span id="selectedBlock">Nenhum</span></div>
</div>
<div id="inventory">
<div class="inventory-slot selected" data-slot="0">
<span class="item-icon">⛏️</span>
</div>
<div class="inventory-slot" data-slot="1"></div>
<div class="inventory-slot" data-slot="2"></div>
<div class="inventory-slot" data-slot="3"></div>
<div class="inventory-slot" data-slot="4"></div>
<div class="inventory-slot" data-slot="5"></div>
<div class="inventory-slot" data-slot="6"></div>
<div class="inventory-slot" data-slot="7"></div>
</div>
<div id="crafting">
<h3>Crafting</h3>
<div class="craft-recipe" onclick="craft('wood_sword')">
Espada de Madeira: 5 Madeira
</div>
<div class="craft-recipe" onclick="craft('stone_pickaxe')">
Picareta de Pedra: 3 Pedra + 2 Madeira
</div>
<div class="craft-recipe" onclick="craft('torch')">
Tocha: 1 Madeira + 1 Carvão
</div>
</div>
<div id="controls">
<div>WASD - Mover</div>
<div>Mouse - Minerar/Colocar</div>
<div>1-8 - Selecionar Item</div>
<div>E - Atacar</div>
</div>
</div>
<script>
// Configurações do jogo
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const BLOCK_SIZE = 20;
const WORLD_WIDTH = 200;
const WORLD_HEIGHT = 100;
// Tipos de blocos
const BLOCK_TYPES = {
AIR: 0,
GRASS: 1,
DIRT: 2,
STONE: 3,
WOOD: 4,
COAL: 5,
IRON: 6,
WATER: 7
};
// Cores dos blocos
const BLOCK_COLORS = {
[BLOCK_TYPES.AIR]: 'transparent',
[BLOCK_TYPES.GRASS]: '#7cfc00',
[BLOCK_TYPES.DIRT]: '#8b4513',
[BLOCK_TYPES.STONE]: '#696969',
[BLOCK_TYPES.WOOD]: '#daa520',
[BLOCK_TYPES.COAL]: '#2f2f2f',
[BLOCK_TYPES.IRON]: '#b0c4de',
[BLOCK_TYPES.WATER]: '#4169e1'
};
// Ícones dos itens
const ITEM_ICONS = {
pickaxe: '⛏️',
[BLOCK_TYPES.WOOD]: '🟫',
[BLOCK_TYPES.STONE]: '🟫',
[BLOCK_TYPES.COAL]: '⚫',
[BLOCK_TYPES.IRON]: '⚪',
[BLOCK_TYPES.DIRT]: '🟤',
[BLOCK_TYPES.GRASS]: '🟢',
wood_sword: '⚔️',
stone_pickaxe: '⛏️',
torch: '🔥'
};
// Estado do jogo
let gameState = {
world: [],
player: {
x: WORLD_WIDTH / 2 * BLOCK_SIZE,
y: 30 * BLOCK_SIZE,
width: BLOCK_SIZE - 4,
height: BLOCK_SIZE * 1.5,
health: 100,
maxHealth: 100,
velocityY: 0,
onGround: false,
facingRight: true
},
camera: {
x: 0,
y: 0
},
inventory: {
slots: [
{ type: 'pickaxe', count: 1 },
null, null, null, null, null, null, null
],
selectedSlot: 0
},
enemies: [],
particles: [],
keys: {}
};
// Inicializar mundo
function generateWorld() {
gameState.world = [];
for (let x = 0; x < WORLD_WIDTH; x++) {
gameState.world[x] = [];
// Gerar altura do terreno
const surfaceHeight = 40 + Math.sin(x * 0.1) * 5 + Math.sin(x * 0.03) * 10;
for (let y = 0; y < WORLD_HEIGHT; y++) {
if (y < surfaceHeight) {
gameState.world[x][y] = BLOCK_TYPES.AIR;
} else if (y === Math.floor(surfaceHeight)) {
gameState.world[x][y] = BLOCK_TYPES.GRASS;
} else if (y < surfaceHeight + 5) {
gameState.world[x][y] = BLOCK_TYPES.DIRT;
} else {
gameState.world[x][y] = BLOCK_TYPES.STONE;
// Gerar minérios
if (Math.random() < 0.02) {
gameState.world[x][y] = BLOCK_TYPES.COAL;
} else if (Math.random() < 0.005 && y > surfaceHeight + 10) {
gameState.world[x][y] = BLOCK_TYPES.IRON;
}
}
}
}
// Gerar árvores
for (let i = 0; i < 50; i++) {
const x = Math.floor(Math.random() * WORLD_WIDTH);
const surfaceY = findSurface(x);
if (surfaceY > 0 && gameState.world[x][surfaceY] === BLOCK_TYPES.GRASS) {
// Tronco
for (let y = surfaceY - 4; y < surfaceY; y++) {
if (y >= 0) gameState.world[x][y] = BLOCK_TYPES.WOOD;
}
}
}
}
function findSurface(x) {
for (let y = 0; y < WORLD_HEIGHT; y++) {
if (gameState.world[x] && gameState.world[x][y] !== BLOCK_TYPES.AIR) {
return y;
}
}
return WORLD_HEIGHT - 1;
}
// Gerar inimigos
function spawnEnemies() {
if (gameState.enemies.length < 5 && Math.random() < 0.01) {
const x = (gameState.camera.x + Math.random() * canvas.width) / BLOCK_SIZE;
const surfaceY = findSurface(Math.floor(x));
gameState.enemies.push({
x: x * BLOCK_SIZE,
y: (surfaceY - 2) * BLOCK_SIZE,
width: BLOCK_SIZE,
height: BLOCK_SIZE,
health: 50,
maxHealth: 50,
velocityX: (Math.random() - 0.5) * 2,
velocityY: 0,
type: 'slime'
});
}
}
// Input handling
document.addEventListener('keydown', (e) => {
gameState.keys[e.key.toLowerCase()] = true;
// Seleção de slot do inventário
const num = parseInt(e.key);
if (num >= 1 && num <= 8) {
gameState.inventory.selectedSlot = num - 1;
updateInventoryUI();
}
});
document.addEventListener('keyup', (e) => {
gameState.keys[e.key.toLowerCase()] = false;
});
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left + gameState.camera.x;
const mouseY = e.clientY - rect.top + gameState.camera.y;
const blockX = Math.floor(mouseX / BLOCK_SIZE);
const blockY = Math.floor(mouseY / BLOCK_SIZE);
if (e.button === 0) { // Clique esquerdo - minerar
mineBlock(blockX, blockY);
} else if (e.button === 2) { // Clique direito - colocar
placeBlock(blockX, blockY);
}
});
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
// Seleção de slots do inventário
document.querySelectorAll('.inventory-slot').forEach((slot, index) => {
slot.addEventListener('click', () => {
gameState.inventory.selectedSlot = index;
updateInventoryUI();
});
});
function mineBlock(x, y) {
if (x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT) {
const blockType = gameState.world[x][y];
if (blockType !== BLOCK_TYPES.AIR) {
// Adicionar ao inventário
addToInventory(blockType, 1);
// Remover bloco
gameState.world[x][y] = BLOCK_TYPES.AIR;
// Efeito de partículas
createParticles(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_COLORS[blockType]);
}
}
}
function placeBlock(x, y) {
if (x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT) {
const selectedItem = gameState.inventory.slots[gameState.inventory.selectedSlot];
if (selectedItem && selectedItem.type !== 'pickaxe' && selectedItem.type !== 'wood_sword' && selectedItem.type !== 'stone_pickaxe' && selectedItem.type !== 'torch') {
if (gameState.world[x][y] === BLOCK_TYPES.AIR) {
gameState.world[x][y] = selectedItem.type;
removeFromInventory(gameState.inventory.selectedSlot, 1);
}
}
}
}
function addToInventory(itemType, count) {
// Procurar slot existente com o mesmo item
for (let i = 0; i < gameState.inventory.slots.length; i++) {
const slot = gameState.inventory.slots[i];
if (slot && slot.type === itemType) {
slot.count += count;
updateInventoryUI();
return;
}
}
// Procurar slot vazio
for (let i = 0; i < gameState.inventory.slots.length; i++) {
if (!gameState.inventory.slots[i]) {
gameState.inventory.slots[i] = { type: itemType, count: count };
updateInventoryUI();
return;
}
}
}
function removeFromInventory(slotIndex, count) {
const slot = gameState.inventory.slots[slotIndex];
if (slot) {
slot.count -= count;
if (slot.count <= 0) {
gameState.inventory.slots[slotIndex] = null;
}
updateInventoryUI();
}
}
function updateInventoryUI() {
document.querySelectorAll('.inventory-slot').forEach((element, index) => {
const slot = gameState.inventory.slots[index];
element.classList.toggle('selected', index === gameState.inventory.selectedSlot);
if (slot) {
element.innerHTML = `
<span class="item-icon">${ITEM_ICONS[slot.type] || '❓'}</span>
<span class="inventory-count">${slot.count > 1 ? slot.count : ''}</span>
`;
} else {
element.innerHTML = '';
}
});
const selectedItem = gameState.inventory.slots[gameState.inventory.selectedSlot];
document.getElementById('selectedBlock').textContent = selectedItem ? (ITEM_ICONS[selectedItem.type] || 'Item') : 'Nenhum';
}
function createParticles(x, y, color) {
for (let i = 0; i < 5; i++) {
gameState.particles.push({
x: x + Math.random() * BLOCK_SIZE,
y: y + Math.random() * BLOCK_SIZE,
velocityX: (Math.random() - 0.5) * 4,
velocityY: (Math.random() - 0.5) * 4 - 2,
life: 30,
maxLife: 30,
color: color
});
}
}
// Sistema de crafting
const RECIPES = {
wood_sword: {
materials: { [BLOCK_TYPES.WOOD]: 5 },
result: { type: 'wood_sword', count: 1 }
},
stone_pickaxe: {
materials: { [BLOCK_TYPES.STONE]: 3, [BLOCK_TYPES.WOOD]: 2 },
result: { type: 'stone_pickaxe', count: 1 }
},
torch: {
materials: { [BLOCK_TYPES.WOOD]: 1, [BLOCK_TYPES.COAL]: 1 },
result: { type: 'torch', count: 4 }
}
};
function craft(recipeId) {
const recipe = RECIPES[recipeId];
if (!recipe) return;
// Verificar se tem materiais
for (const [materialType, needed] of Object.entries(recipe.materials)) {
let available = 0;
for (const slot of gameState.inventory.slots) {
if (slot && slot.type == materialType) {
available += slot.count;
}
}
if (available < needed) {
alert('Materiais insuficientes!');
return;
}
}
// Consumir materiais
for (const [materialType, needed] of Object.entries(recipe.materials)) {
let toRemove = needed;
for (let i = 0; i < gameState.inventory.slots.length && toRemove > 0; i++) {
const slot = gameState.inventory.slots[i];
if (slot && slot.type == materialType) {
const remove = Math.min(slot.count, toRemove);
removeFromInventory(i, remove);
toRemove -= remove;
}
}
}
// Adicionar resultado
addToInventory(recipe.result.type, recipe.result.count);
}
// Physics
function updatePhysics() {
// Player physics
const player = gameState.player;
// Gravidade
player.velocityY += 0.5;
// Movimento horizontal
if (gameState.keys['a']) {
player.x -= 3;
player.facingRight = false;
}
if (gameState.keys['d']) {
player.x += 3;
player.facingRight = true;
}
// Pulo
if (gameState.keys['w'] && player.onGround) {
player.velocityY = -12;
player.onGround = false;
}
// Ataque
if (gameState.keys['e']) {
attackEnemies();
}
// Aplicar velocidade Y
player.y += player.velocityY;
// Colisão com o mundo
checkCollisions();
// Atualizar câmera
gameState.camera.x = player.x - canvas.width / 2;
gameState.camera.y = player.y - canvas.height / 2;
// Limitar câmera
gameState.camera.x = Math.max(0, Math.min(gameState.camera.x, WORLD_WIDTH * BLOCK_SIZE - canvas.width));
gameState.camera.y = Math.max(0, Math.min(gameState.camera.y, WORLD_HEIGHT * BLOCK_SIZE - canvas.height));
// Atualizar inimigos
updateEnemies();
// Atualizar partículas
updateParticles();
// Spawn inimigos
spawnEnemies();
}
function checkCollisions() {
const player = gameState.player;
// Verificar colisão com blocos
const leftBlock = Math.floor(player.x / BLOCK_SIZE);
const rightBlock = Math.floor((player.x + player.width) / BLOCK_SIZE);
const topBlock = Math.floor(player.y / BLOCK_SIZE);
const bottomBlock = Math.floor((player.y + player.height) / BLOCK_SIZE);
// Colisão vertical
player.onGround = false;
for (let x = leftBlock; x <= rightBlock; x++) {
for (let y = topBlock; y <= bottomBlock; y++) {
if (x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT) {
if (gameState.world[x][y] !== BLOCK_TYPES.AIR) {
const blockLeft = x * BLOCK_SIZE;
const blockRight = (x + 1) * BLOCK_SIZE;
const blockTop = y * BLOCK_SIZE;
const blockBottom = (y + 1) * BLOCK_SIZE;
// Colisão vertical
if (player.velocityY > 0) { // Caindo
if (player.y + player.height > blockTop && player.y < blockTop) {
player.y = blockTop - player.height;
player.velocityY = 0;
player.onGround = true;
}
} else if (player.velocityY < 0) { // Subindo
if (player.y < blockBottom && player.y + player.height > blockBottom) {
player.y = blockBottom;
player.velocityY = 0;
}
}
}
}
}
}
// Limitar player no mundo
player.x = Math.max(0, Math.min(player.x, WORLD_WIDTH * BLOCK_SIZE - player.width));
player.y = Math.max(0, Math.min(player.y, WORLD_HEIGHT * BLOCK_SIZE - player.height));
}
function updateEnemies() {
gameState.enemies.forEach((enemy, index) => {
// IA simples - mover em direção ao player
const dx = gameState.player.x - enemy.x;
const distance = Math.abs(dx);
if (distance < 200) {
enemy.velocityX = dx > 0 ? 1 : -1;
}
enemy.x += enemy.velocityX;
enemy.velocityY += 0.5; // Gravidade
enemy.y += enemy.velocityY;
// Colisão com o chão (simplificada)
const blockY = Math.floor((enemy.y + enemy.height) / BLOCK_SIZE);
const blockX = Math.floor(enemy.x / BLOCK_SIZE);
if (blockX >= 0 && blockX < WORLD_WIDTH && blockY >= 0 && blockY < WORLD_HEIGHT) {
if (gameState.world[blockX][blockY] !== BLOCK_TYPES.AIR) {
enemy.y = blockY * BLOCK_SIZE - enemy.height;
enemy.velocityY = 0;
}
}
// Verificar colisão com player
if (Math.abs(enemy.x - gameState.player.x) < 30 && Math.abs(enemy.y - gameState.player.y) < 30) {
gameState.player.health -= 0.5;
if (gameState.player.health <= 0) {
respawnPlayer();
}
}
// Remover inimigos muito longe
if (Math.abs(enemy.x - gameState.player.x) > 500) {
gameState.enemies.splice(index, 1);
}
});
}
function attackEnemies() {
const attackRange = 40;
const selectedItem = gameState.inventory.slots[gameState.inventory.selectedSlot];
let damage = 10;
if (selectedItem && (selectedItem.type === 'wood_sword' || selectedItem.type === 'stone_pickaxe')) {
damage = selectedItem.type === 'wood_sword' ? 25 : 20;
}
gameState.enemies.forEach((enemy, index) => {
const distance = Math.sqrt(
Math.pow(enemy.x - gameState.player.x, 2) +
Math.pow(enemy.y - gameState.player.y, 2)
);
if (distance < attackRange) {
enemy.health -= damage;
if (enemy.health <= 0) {
// Drop items
if (Math.random() < 0.5) {
addToInventory(BLOCK_TYPES.COAL, 1);
}
gameState.enemies.splice(index, 1);
}
}
});
}
function updateParticles() {
gameState.particles.forEach((particle, index) => {
particle.x += particle.velocityX;
particle.y += particle.velocityY;
particle.velocityY += 0.2; // Gravidade
particle.life--;
if (particle.life <= 0) {
gameState.particles.splice(index, 1);
}
});
}
function respawnPlayer() {
gameState.player.x = WORLD_WIDTH / 2 * BLOCK_SIZE;
gameState.player.y = 30 * BLOCK_SIZE;
gameState.player.health = gameState.player.maxHealth;
gameState.player.velocityY = 0;
}
// Rendering
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Desenhar mundo
for (let x = 0; x < WORLD_WIDTH; x++) {
for (let y = 0; y < WORLD_HEIGHT; y++) {
const blockType = gameState.world[x][y];
if (blockType !== BLOCK_TYPES.AIR) {
const screenX = x * BLOCK_SIZE - gameState.camera.x;
const screenY = y * BLOCK_SIZE - gameState.camera.y;
if (screenX > -BLOCK_SIZE && screenX < canvas.width &&
screenY > -BLOCK_SIZE && screenY < canvas.height) {
ctx.fillStyle = BLOCK_COLORS[blockType];
ctx.fillRect(screenX, screenY, BLOCK_SIZE, BLOCK_SIZE);
// Borda dos blocos
ctx.strokeStyle = 'rgba(0,0,0,0.2)';
ctx.lineWidth = 1;
ctx.strokeRect(screenX, screenY, BLOCK_SIZE, BLOCK_SIZE);
}
}
}
}
// Desenhar player
const playerScreenX = gameState.player.x - gameState.camera.x;
const playerScreenY = gameState.player.y - gameState.camera.y;
ctx.fillStyle = '#ff6b6b';
ctx.fillRect(playerScreenX, playerScreenY, gameState.player.width, gameState.player.height);
// Desenhar olhos do player
ctx.fillStyle = 'white';
const eyeY = playerScreenY + 4;
const eyeSize = 3;
if (gameState.player.facingRight) {
ctx.fillRect(playerScreenX + 8, eyeY, eyeSize, eyeSize);
ctx.fillRect(playerScreenX + 12, eyeY, eyeSize, eyeSize);
} else {
ctx.fillRect(playerScreenX + 2, eyeY, eyeSize, eyeSize);
ctx.fillRect(playerScreenX + 6, eyeY, eyeSize, eyeSize);
}
// Desenhar inimigos
gameState.enemies.forEach(enemy => {
const enemyScreenX = enemy.x - gameState.camera.x;
const enemyScreenY = enemy.y - gameState.camera.y;
if (enemyScreenX > -BLOCK_SIZE && enemyScreenX < canvas.width &&
enemyScreenY > -BLOCK_SIZE && enemyScreenY < canvas.height) {
ctx.fillStyle = '#32cd32';
ctx.fillRect(enemyScreenX, enemyScreenY, enemy.width, enemy.height);
// Barra de vida do inimigo
const healthPercent = enemy.health / enemy.maxHealth;
ctx.fillStyle = 'red';
ctx.fillRect(enemyScreenX, enemyScreenY - 8, enemy.width, 4);
ctx.fillStyle = 'green';
ctx.fillRect(enemyScreenX, enemyScreenY - 8, enemy.width * healthPercent, 4);
}
});
// Desenhar partículas
gameState.particles.forEach(particle => {
const particleScreenX = particle.x - gameState.camera.x;
const particleScreenY = particle.y - gameState.camera.y;
const alpha = particle.life / particle.maxLife;
ctx.fillStyle = particle.color.replace('rgb', 'rgba').replace(')', `, ${alpha})`);
ctx.fillRect(particleScreenX, particleScreenY, 3, 3);
});
// Atualizar UI
document.getElementById('health').textContent = Math.max(0, Math.floor(gameState.player.health));
document.getElementById('playerX').textContent = Math.floor(gameState.player.x / BLOCK_SIZE);
document.getElementById('playerY').textContent = Math.floor(gameState.player.y / BLOCK_SIZE);
}
// Game loop
function gameLoop() {
updatePhysics();
render();
requestAnimationFrame(gameLoop);
}
// Inicializar jogo
generateWorld();
updateInventoryUI();
gameLoop();
</script>
</body>
</html>
Este é um jogo 2D completo estilo Terraria com as seguintes funcionalidades:
🎮 Características principais:
- Mundo procedural: Geração automática de terreno com diferentes camadas (grama, terra, pedra)
- Sistema de mineração: Clique esquerdo para minerar blocos
- Sistema de construção: Clique direito para colocar blocos
- Inventário: 8 slots com sistema de seleção (teclas 1-8)
- Sistema de crafting: Receitas para criar ferramentas e itens
- Física realista: Gravidade, colisões, pulos
- Inimigos: Slimes que perseguem o jogador
- Sistema de combate: Ataque com diferentes armas
- Recursos: Madeira, pedra, carvão, ferro
- Partículas: Efeitos visuais ao minerar
🕹️ Controles:
- WASD: Movimento do personagem
- Mouse: Minerar (esquerdo) / Colocar blocos (direito)
- 1-8: Selecionar items do inventário
- E: Atacar inimigos
⚒️ Sistema de Crafting:
- Espada de Madeira: 5 Madeira
- Picareta de Pedra: 3 Pedra + 2 Madeira
- Tocha: 1 Madeira + 1 Carvão
O jogo inclui geração procedural de mundo, sistema de vida, inimigos com IA, efeitos de partículas e uma interface completa. É totalmente jogável e expansível!