<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini Terraria</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#game-container {
position: relative;
width: 800px;
height: 600px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
#game-canvas {
background-color: #87CEEB;
display: block;
}
#inventory {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 5px;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
}
.inventory-slot {
width: 40px;
height: 40px;
background-color: #555;
border: 2px solid #777;
display: flex;
justify-content: center;
align-items: center;
font-size: 12px;
color: white;
position: relative;
}
.inventory-slot.selected {
border-color: white;
background-color: #666;
}
.inventory-count {
position: absolute;
bottom: 2px;
right: 2px;
font-size: 10px;
background-color: rgba(0, 0, 0, 0.7);
padding: 1px 3px;
border-radius: 3px;
}
#health-bar {
position: absolute;
top: 10px;
left: 10px;
width: 200px;
height: 20px;
background-color: #555;
border: 2px solid #777;
border-radius: 5px;
}
#health-fill {
height: 100%;
background-color: #e74c3c;
width: 100%;
transition: width 0.3s;
border-radius: 3px;
}
#game-over {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: none;
justify-content: center;
align-items: center;
flex-direction: column;
color: white;
font-size: 24px;
}
#restart-button {
margin-top: 20px;
padding: 10px 20px;
background-color: #2ecc71;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 18px;
color: white;
}
#instructions {
position: absolute;
top: 40px;
left: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 10px;
border-radius: 5px;
font-size: 12px;
max-width: 200px;
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="game-canvas" width="800" height="600"></canvas>
<div id="health-bar">
<div id="health-fill"></div>
</div>
<div id="inventory">
<!-- Inventory slots will be added by JavaScript -->
</div>
<div id="instructions">
<p><strong>Controles:</strong></p>
<p>A/D ou ←/→: Mover</p>
<p>W ou ↑: Pular</p>
<p>Clique Esquerdo: Minerar</p>
<p>Clique Direito: Colocar bloco</p>
<p>1-5: Selecionar slot</p>
<p>E: Criar tábua (precisa de 3 madeiras)</p>
</div>
<div id="game-over">
<div>GAME OVER</div>
<button id="restart-button">Reiniciar</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Game canvas and context
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
// Game constants
const BLOCK_SIZE = 32;
const GRAVITY = 0.5;
const JUMP_FORCE = 12;
const PLAYER_SPEED = 5;
const WORLD_WIDTH = 100; // in blocks
const WORLD_HEIGHT = 50; // in blocks
const BLOCK_TYPES = {
AIR: 0,
DIRT: 1,
STONE: 2,
GRASS: 3,
WOOD: 4,
LEAVES: 5,
WOODEN_PLANK: 6
};
// Game variables
let world = [];
let player = {
x: canvas.width / 2,
y: canvas.height / 2,
width: 24,
height: 48,
velocityX: 0,
velocityY: 0,
isJumping: false,
health: 100,
maxHealth: 100,
facing: 'right'
};
let camera = {
x: 0,
y: 0
};
let inventory = [
{ type: BLOCK_TYPES.DIRT, count: 0 },
{ type: BLOCK_TYPES.STONE, count: 0 },
{ type: BLOCK_TYPES.WOOD, count: 0 },
{ type: BLOCK_TYPES.LEAVES, count: 0 },
{ type: BLOCK_TYPES.WOODEN_PLANK, count: 0 }
];
let selectedInventorySlot = 0;
let isGameOver = false;
// Key states
const keys = {
left: false,
right: false,
up: false
};
// Block colors and properties
const blockColors = {
[BLOCK_TYPES.AIR]: 'transparent',
[BLOCK_TYPES.DIRT]: '#8B4513',
[BLOCK_TYPES.STONE]: '#808080',
[BLOCK_TYPES.GRASS]: '#228B22',
[BLOCK_TYPES.WOOD]: '#A0522D',
[BLOCK_TYPES.LEAVES]: '#006400',
[BLOCK_TYPES.WOODEN_PLANK]: '#DEB887'
};
const blockNames = {
[BLOCK_TYPES.DIRT]: 'Terra',
[BLOCK_TYPES.STONE]: 'Pedra',
[BLOCK_TYPES.GRASS]: 'Grama',
[BLOCK_TYPES.WOOD]: 'Madeira',
[BLOCK_TYPES.LEAVES]: 'Folhas',
[BLOCK_TYPES.WOODEN_PLANK]: 'Tábua'
};
// Initialize inventory UI
function initInventoryUI() {
const inventoryContainer = document.getElementById('inventory');
inventoryContainer.innerHTML = '';
for (let i = 0; i < inventory.length; i++) {
const slot = document.createElement('div');
slot.className = 'inventory-slot';
if (i === selectedInventorySlot) {
slot.classList.add('selected');
}
// Fill slot with block color
slot.style.backgroundColor = blockColors[inventory[i].type];
// Add block name
const name = document.createElement('div');
name.textContent = blockNames[inventory[i].type];
slot.appendChild(name);
// Add count
const count = document.createElement('div');
count.className = 'inventory-count';
count.textContent = inventory[i].count;
slot.appendChild(count);
inventoryContainer.appendChild(slot);
}
}
// Generate world
function generateWorld() {
// Initialize with air
for (let y = 0; y < WORLD_HEIGHT; y++) {
world[y] = [];
for (let x = 0; x < WORLD_WIDTH; x++) {
world[y][x] = BLOCK_TYPES.AIR;
}
}
// Generate terrain
const groundLevel = Math.floor(WORLD_HEIGHT / 2);
for (let x = 0; x < WORLD_WIDTH; x++) {
// Simple terrain height variation
let height = groundLevel + Math.floor(Math.sin(x * 0.1) * 4);
// Place grass at the top
world[height][x] = BLOCK_TYPES.GRASS;
// Fill below with dirt and stone
for (let y = height + 1; y < WORLD_HEIGHT; y++) {
if (y < height + 3 + Math.random() * 2) {
world[y][x] = BLOCK_TYPES.DIRT;
} else {
world[y][x] = BLOCK_TYPES.STONE;
}
}
}
// Generate trees
for (let x = 5; x < WORLD_WIDTH - 5; x += 10 + Math.floor(Math.random() * 10)) {
// Find ground level at this x position
let y = 0;
while (y < WORLD_HEIGHT && world[y][x] === BLOCK_TYPES.AIR) {
y++;
}
if (y < WORLD_HEIGHT && world[y][x] === BLOCK_TYPES.GRASS) {
// Create tree trunk
const treeHeight = 5 + Math.floor(Math.random() * 3);
for (let i = 1; i <= treeHeight; i++) {
if (y - i >= 0) {
world[y - i][x] = BLOCK_TYPES.WOOD;
}
}
// Create tree leaves
const leafSize = 2 + Math.floor(Math.random() * 2);
for (let ly = y - treeHeight - leafSize; ly <= y - treeHeight + 1; ly++) {
for (let lx = x - leafSize; lx <= x + leafSize; lx++) {
if (ly >= 0 && ly < WORLD_HEIGHT && lx >= 0 && lx < WORLD_WIDTH) {
if (Math.random() > 0.2) {
world[ly][lx] = BLOCK_TYPES.LEAVES;
}
}
}
}
}
}
// Position player above ground
for (let y = 0; y < WORLD_HEIGHT; y++) {
if (world[y][Math.floor(WORLD_WIDTH / 2)] !== BLOCK_TYPES.AIR) {
player.y = (y - 2) * BLOCK_SIZE;
player.x = Math.floor(WORLD_WIDTH / 2) * BLOCK_SIZE;
break;
}
}
}
// Update camera position
function updateCamera() {
// Center camera on player
camera.x = player.x - canvas.width / 2 + player.width / 2;
camera.y = player.y - canvas.height / 2 + player.height / 2;
// Clamp camera to world bounds
camera.x = Math.max(0, Math.min(camera.x, WORLD_WIDTH * BLOCK_SIZE - canvas.width));
camera.y = Math.max(0, Math.min(camera.y, WORLD_HEIGHT * BLOCK_SIZE - canvas.height));
}
// Convert world coordinates to screen coordinates
function worldToScreen(x, y) {
return {
x: x - camera.x,
y: y - camera.y
};
}
// Convert screen coordinates to world coordinates
function screenToWorld(x, y) {
return {
x: x + camera.x,
y: y + camera.y
};
}
// Convert world coordinates to grid coordinates
function worldToGrid(x, y) {
return {
x: Math.floor(x / BLOCK_SIZE),
y: Math.floor(y / BLOCK_SIZE)
};
}
// Check if a grid position is valid
function isValidGridPosition(x, y) {
return x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT;
}
// Check if a block is solid
function isSolidBlock(type) {
return type !== BLOCK_TYPES.AIR;
}
// Check player collision with blocks
function checkCollisions() {
// Get grid positions for player corners
const topLeft = worldToGrid(player.x, player.y);
const topRight = worldToGrid(player.x + player.width - 1, player.y);
const bottomLeft = worldToGrid(player.x, player.y + player.height - 1);
const bottomRight = worldToGrid(player.x + player.width - 1, player.y + player.height - 1);
// Check if player is on ground
let onGround = false;
// Bottom collision (feet)
if (player.velocityY > 0) {
if ((isValidGridPosition(bottomLeft.x, bottomLeft.y) && isSolidBlock(world[bottomLeft.y][bottomLeft.x])) ||
(isValidGridPosition(bottomRight.x, bottomRight.y) && isSolidBlock(world[bottomRight.y][bottomRight.x]))) {
player.y = bottomLeft.y * BLOCK_SIZE - player.height;
player.velocityY = 0;
onGround = true;
}
}
// Top collision (head)
if (player.velocityY < 0) {
if ((isValidGridPosition(topLeft.x, topLeft.y) && isSolidBlock(world[topLeft.y][topLeft.x])) ||
(isValidGridPosition(topRight.x, topRight.y) && isSolidBlock(world[topRight.y][topRight.x]))) {
player.y = (topLeft.y + 1) * BLOCK_SIZE;
player.velocityY = 0;
}
}
// Get updated grid positions after Y correction
const newTopLeft = worldToGrid(player.x, player.y);
const newTopRight = worldToGrid(player.x + player.width - 1, player.y);
const newBottomLeft = worldToGrid(player.x, player.y + player.height - 1);
const newBottomRight = worldToGrid(player.x + player.width - 1, player.y + player.height - 1);
// Left collision
if (player.velocityX < 0) {
if ((isValidGridPosition(newTopLeft.x, newTopLeft.y) && isSolidBlock(world[newTopLeft.y][newTopLeft.x])) ||
(isValidGridPosition(newBottomLeft.x, newBottomLeft.y) && isSolidBlock(world[newBottomLeft.y][newBottomLeft.x]))) {
player.x = (newTopLeft.x + 1) * BLOCK_SIZE;
player.velocityX = 0;
}
}
// Right collision
if (player.velocityX > 0) {
if ((isValidGridPosition(newTopRight.x, newTopRight.y) && isSolidBlock(world[newTopRight.y][newTopRight.x])) ||
(isValidGridPosition(newBottomRight.x, newBottomRight.y) && isSolidBlock(world[newBottomRight.y][newBottomRight.x]))) {
player.x = newTopRight.x * BLOCK_SIZE - player.width;
player.velocityX = 0;
}
}
player.isJumping = !onGround;
// World boundaries
if (player.x < 0) player.x = 0;
if (player.x > WORLD_WIDTH * BLOCK_SIZE - player.width) player.x = WORLD_WIDTH * BLOCK_SIZE - player.width;
if (player.y < 0) player.y = 0;
if (player.y > WORLD_HEIGHT * BLOCK_SIZE - player.height) {
player.y = WORLD_HEIGHT * BLOCK_SIZE - player.height;
player.velocityY = 0;
}
}
// Update player
function updatePlayer() {
if (isGameOver) return;
// Apply horizontal movement
if (keys.left) {
player.velocityX = -PLAYER_SPEED;
player.facing = 'left';
} else if (keys.right) {
player.velocityX = PLAYER_SPEED;
player.facing = 'right';
} else {
player.velocityX = 0;
}
// Apply jump
if (keys.up && !player.isJumping) {
player.velocityY = -JUMP_FORCE;
player.isJumping = true;
}
// Apply gravity
player.velocityY += GRAVITY;
// Update position
player.x += player.velocityX;
player.y += player.velocityY;
// Check collisions
checkCollisions();
// Update health bar
document.getElementById('health-fill').style.width = `${(player.health / player.maxHealth) * 100}%`;
// Check if player fell out of the world
if (player.y > WORLD_HEIGHT * BLOCK_SIZE) {
player.health = 0;
}
// Check game over
if (player.health <= 0 && !isGameOver) {
gameOver();
}
}
// Game over
function gameOver() {
isGameOver = true;
document.getElementById('game-over').style.display = 'flex';
}
// Restart game
function restartGame() {
isGameOver = false;
player.health = player.maxHealth;
document.getElementById('game-over').style.display = 'none';
// Reset inventory
for (let i = 0; i < inventory.length; i++) {
inventory[i].count = 0;
}
// Generate new world
generateWorld();
initInventoryUI();
}
// Draw world
function drawWorld() {
// Calculate visible area
const startX = Math.floor(camera.x / BLOCK_SIZE);
const startY = Math.floor(camera.y / BLOCK_SIZE);
const endX = Math.min(startX + Math.ceil(canvas.width / BLOCK_SIZE) + 1, WORLD_WIDTH);
const endY = Math.min(startY + Math.ceil(canvas.height / BLOCK_SIZE) + 1, WORLD_HEIGHT);
// Draw visible blocks
for (let y = startY; y < endY; y++) {
for (let x = startX; x < endX; x++) {
const blockType = world[y][x];
if (blockType !== BLOCK_TYPES.AIR) {
const screenPos = worldToScreen(x * BLOCK_SIZE, y * BLOCK_SIZE);
// Draw block
ctx.fillStyle = blockColors[blockType];
ctx.fillRect(screenPos.x, screenPos.y, BLOCK_SIZE, BLOCK_SIZE);
// Draw block border
ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
ctx.lineWidth = 1;
ctx.strokeRect(screenPos.x, screenPos.y, BLOCK_SIZE, BLOCK_SIZE);
}
}
}
}
// Draw player
function drawPlayer() {
const screenPos = worldToScreen(player.x, player.y);
// Draw player body
ctx.fillStyle = '#FF6347';
ctx.fillRect(screenPos.x, screenPos.y, player.width, player.height);
// Draw player face
ctx.fillStyle = 'white';
if (player.facing === 'right') {
ctx.fillRect(screenPos.x + player.width - 10, screenPos.y + 10, 4, 4);
} else {
ctx.fillRect(screenPos.x + 6, screenPos.y + 10, 4, 4);
}
// Draw player hand based on selected item
const selectedBlock = inventory[selectedInventorySlot].type;
if (selectedBlock !== BLOCK_TYPES.AIR) {
ctx.fillStyle = blockColors[selectedBlock];
if (player.facing === 'right') {
ctx.fillRect(screenPos.x + player.width, screenPos.y + 20, 8, 8);
} else {
ctx.fillRect(screenPos.x - 8, screenPos.y + 20, 8, 8);
}
}
}
// Mine block
function mineBlock(worldX, worldY) {
const gridPos = worldToGrid(worldX, worldY);
if (isValidGridPosition(gridPos.x, gridPos.y)) {
const blockType = world[gridPos.y][gridPos.x];
if (blockType !== BLOCK_TYPES.AIR) {
// Add block to inventory
for (let i = 0; i < inventory.length; i++) {
if (inventory[i].type === blockType) {
inventory[i].count++;
break;
}
}
// Remove block from world
world[gridPos.y][gridPos.x] = BLOCK_TYPES.AIR;
// Update inventory UI
initInventoryUI();
}
}
}
// Place block
function placeBlock(worldX, worldY) {
const gridPos = worldToGrid(worldX, worldY);
if (isValidGridPosition(gridPos.x, gridPos.y)) {
// Check if the target position is air and not occupied by the player
if (world[gridPos.y][gridPos.x] === BLOCK_TYPES.AIR) {
// Check if player is not trying to place a block on himself
const playerGridPos = worldToGrid(player.x, player.y);
const playerGridPosBottom = worldToGrid(player.x, player.y + player.height - 1);
const playerGridPosRight = worldToGrid(player.x + player.width - 1, player.y);
const playerGridPosBottomRight = worldToGrid(player.x + player.width - 1, player.y + player.height - 1);
if ((gridPos.x !== playerGridPos.x || gridPos.y !== playerGridPos.y) &&
(gridPos.x !== playerGridPosBottom.x || gridPos.y !== playerGridPosBottom.y) &&
(gridPos.x !== playerGridPosRight.x || gridPos.y !== playerGridPosRight.y) &&
(gridPos.x !== playerGridPosBottomRight.x || gridPos.y !== playerGridPosBottomRight.y)) {
const selectedBlock = inventory[selectedInventorySlot].type;
// Check if player has this block in inventory
if (inventory[selectedInventorySlot].count > 0) {
// Place block
world[gridPos.y][gridPos.x] = selectedBlock;
// Reduce inventory count
inventory[selectedInventorySlot].count--;
// Update inventory UI
initInventoryUI();
}
}
}
}
}
// Craft wooden planks (3 wood -> 1 wooden plank)
function craftWoodenPlanks() {
// Find wood in inventory
let woodIndex = -1;
let plankIndex = -1;
for (let i = 0; i < inventory.length; i++) {
if (inventory[i].type === BLOCK_TYPES.WOOD) {
woodIndex = i;
}
if (inventory[i].type === BLOCK_TYPES.WOODEN_PLANK) {
plankIndex = i;
}
}
if (woodIndex !== -1 && plankIndex !== -1 && inventory[woodIndex].count >= 3) {
// Craft plank
inventory[woodIndex].count -= 3;
inventory[plankIndex].count += 1;
// Update inventory UI
initInventoryUI();
}
}
// Main game loop
function gameLoop() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update
updatePlayer();
updateCamera();
// Draw
drawWorld();
drawPlayer();
// Request next frame
requestAnimationFrame(gameLoop);
}
// Initialize game
function init() {
// Generate world
generateWorld();
// Initialize inventory UI
initInventoryUI();
// Add event listeners
document.addEventListener('keydown', (e) => {
if (e.key === 'a' || e.key === 'ArrowLeft') keys.left = true;
if (e.key === 'd' || e.key === 'ArrowRight') keys.right = true;
if (e.key === 'w' || e.key === 'ArrowUp') keys.up = true;
// Inventory selection
if (e.key >= '1' && e.key <= '5') {
selectedInventorySlot = parseInt(e.key) - 1;
initInventoryUI();
}
// Crafting
if (e.key === 'e') {
craftWoodenPlanks();
}
});
document.addEventListener('keyup', (e) => {
if (e.key === 'a' || e.key === 'ArrowLeft') keys.left = false;
if (e.key === 'd' || e.key === 'ArrowRight') keys.right = false;
if (e.key === 'w' || e.key === 'ArrowUp') keys.up = false;
});
canvas.addEventListener('mousedown', (e) => {
if (isGameOver) return;
const rect = canvas.getBoundingClientRect();
const screenX = e.clientX - rect.left;
const screenY = e.clientY - rect.top;
const worldPos = screenToWorld(screenX, screenY);
if (e.button === 0) { // Left click
mineBlock(worldPos.x, worldPos.y);
} else if (e.button === 2) { // Right click
placeBlock(worldPos.x, worldPos.y);
}
});
canvas.addEventListener('contextmenu', (e) => {
e.preventDefault(); // Prevent default context menu
});
document.getElementById('restart-button').addEventListener('click', restartGame);
// Start game loop
gameLoop();
}
// Start the game
init();
});
</script>
</body>
</html>
Gostaria que eu explique como o código funciona?