<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Aventura Pixelada!</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #ADD8E6; /* Azul claro */
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
border: 1px solid #000;
background-color: #7CFC00; /* Verde grama */
image-rendering: pixelated; /* Impede o suavizamento das imagens */
}
#game-over-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: none; /* Inicialmente escondido */
justify-content: center;
align-items: center;
color: white;
font-size: 3em;
flex-direction: column;
}
#restart-button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
font-size: 1em;
border-radius: 5px;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="640" height="480"></canvas>
<div id="game-over-overlay">
<h1>Game Over!</h1>
<button id="restart-button">Reiniciar</button>
</div>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const gameOverOverlay = document.getElementById("game-over-overlay");
const restartButton = document.getElementById("restart-button");
// Dimensões do jogo
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
// Jogador
const playerWidth = 32;
const playerHeight = 32;
let playerX = canvasWidth / 2 - playerWidth / 2;
let playerY = canvasHeight - playerHeight - 10;
const playerSpeed = 5;
let isMovingLeft = false;
let isMovingRight = false;
// Obstáculos
const obstacleWidth = 32;
const obstacleHeight = 32;
const obstacles = [];
// Score
let score = 0;
// Estado do Jogo
let gameRunning = true;
// Imagens (sprites)
const playerImage = new Image();
playerImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAhUlEQVR4nO3XMQqDQBRE0bf9E2i0u7k2mYYSbW3sK/94C04iJ657lXw7X0EQEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEQwEZA9gWvF9O0cAAAAASUVORK5CYII="; // Simple pixelated character
const obstacleImage = new Image();
obstacleImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAUklEQVR4nO2XQQqAMAxE55X/X6uJghF8Q68L9sJzJ4oQjQyR7JbQ/Y64Y94R0bW98l4T9J62y42e2Q2S+q+FwQv/q0Q/y71f+Lg91cAAAAASUVORK5CYII="; // Simple pixelated block
// Funções
function spawnObstacle() {
const obstacleX = Math.random() * (canvasWidth - obstacleWidth);
const obstacleY = -obstacleHeight;
obstacles.push({ x: obstacleX, y: obstacleY });
}
function updateObstacles() {
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].y += 3; // Velocidade dos obstáculos
// Remove obstáculos que saíram da tela
if (obstacles[i].y > canvasHeight) {
obstacles.splice(i, 1);
i--;
score++;
}
}
}
function checkCollision() {
for (const obstacle of obstacles) {
if (
playerX < obstacle.x + obstacleWidth &&
playerX + playerWidth > obstacle.x &&
playerY < obstacle.y + obstacleHeight &&
playerY + playerHeight > obstacle.y
) {
// Colisão detectada!
return true;
}
}
return false;
}
function drawPlayer() {
ctx.drawImage(playerImage, playerX, playerY, playerWidth, playerHeight);
}
function drawObstacles() {
for (const obstacle of obstacles) {
ctx.drawImage(obstacleImage, obstacle.x, obstacle.y, obstacleWidth, obstacleHeight);
}
}
function drawScore() {
ctx.fillStyle = "black";
ctx.font = "20px monospace";
ctx.fillText(`Score: ${score}`, 10, 30);
}
function gameOver() {
gameRunning = false;
gameOverOverlay.style.display = "flex";
}
function resetGame() {
gameRunning = true;
gameOverOverlay.style.display = "none";
playerX = canvasWidth / 2 - playerWidth / 2;
playerY = canvasHeight - playerHeight - 10;
obstacles.length = 0; // Limpa o array de obstáculos
score = 0;
}
function update() {
if (!gameRunning) return;
// Movimento do jogador
if (isMovingLeft) {
playerX -= playerSpeed;
if (playerX < 0) playerX = 0; // Limite da esquerda
}
if (isMovingRight) {
playerX += playerSpeed;
if (playerX > canvasWidth - playerWidth) playerX = canvasWidth - playerWidth; // Limite da direita
}
updateObstacles();
// Spawna novos obstáculos (ajustar a taxa)
if (Math.random() < 0.02) { // Ajustar para aumentar ou diminuir a frequência
spawnObstacle();
}
if (checkCollision()) {
gameOver();
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight); // Limpa a tela
drawPlayer();
drawObstacles();
drawScore();
requestAnimationFrame(draw); // Chama o draw novamente
}
// Event Listeners
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft" || event.key === "a") {
isMovingLeft = true;
}
if (event.key === "ArrowRight" || event.key === "d") {
isMovingRight = true;
}
});
document.addEventListener("keyup", (event) => {
if (event.key === "ArrowLeft" || event.key === "a") {
isMovingLeft = false;
}
if (event.key === "ArrowRight" || event.key === "d") {
isMovingRight = false;
}
});
restartButton.addEventListener("click", resetGame);
// Início do Jogo
draw(); // Inicia o loop de desenho
function gameLoop() {
update();
setTimeout(gameLoop, 16); // Aproximadamente 60 FPS
}
gameLoop();
</script>
</body>
</html>
Como usar:
- Copie o código: Copie todo o código HTML acima.
- Crie um arquivo: Crie um novo arquivo de texto e salve-o como
index.html.
- Cole o código: Cole o código que você copiou no arquivo
index.html.
- Abra no navegador: Abra o arquivo
index.html em seu navegador (Chrome, Firefox, Safari, etc.).
Como jogar:
- Setas Esquerda/Direita ou A/D: Movimentam o personagem para a esquerda e para a direita.
- Desvie dos obstáculos: Evite ser atingido pelos blocos que caem.
- Score: Aumenta a cada obstáculo que você desvia.
- Game Over: Se for atingido por um obstáculo, o jogo termina. Clique no botão "Reiniciar" para jogar novamente.
Recursos:
- Simples e divertido: O jogo é propositalmente simples para ser fácil de entender e jogar.
- Estilo Pixel Art: O estilo visual é inspirado em jogos clássicos de pixel art.
- Cores vibrantes: As cores foram escolhidas para criar um visual agradável e chamativo.
- Responsivo: O jogo se adapta ao tamanho da tela do seu dispositivo.
- Imagens Base64: As imagens do jogador e do obstáculo estão embutidas no código usando strings Base64. Isso evita a necessidade de arquivos de imagem separados e simplifica o projeto.
- Game Over Overlay: Uma tela de game over é exibida quando o jogador perde, com um botão para reiniciar o jogo.
- Loop de Jogo: O jogo usa um loop
requestAnimationFrame para atualizar e desenhar continuamente a tela, criando uma animação suave.
Possíveis melhorias:
- Dificuldade crescente: Aumentar a velocidade dos obstáculos com o tempo ou adicionar novos tipos de obstáculos.
- Power-ups: Adicionar itens que dão ao jogador habilidades temporárias (ex: invencibilidade, velocidade).
- Sons: Adicionar efeitos sonoros para ações como pular, colidir e game over.
- Animações: Adicionar animações mais complexas para o jogador e os obstáculos.
- Placar Online: Implementar um sistema para salvar e exibir os melhores scores.
- Mobile: Adaptar os controles para dispositivos móveis (touchscreen).
Este é um bom ponto de partida para criar um jogo 2D simples em HTML. Divirta-se explorando as possibilidades e expandindo o jogo com seus próprios recursos e ideias!