Untitled
unknown
plain_text
a year ago
3.1 kB
14
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Action Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="game-container">
<div id="player"></div>
<div id="enemy"></div>
</div>
<script src="script.js"></script>
</body>
</html>
3. Add CSS for Styling
Create a style.css file to define the visuals of your game.
css
Copy
Edit
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #222;
overflow: hidden;
}
#game-container {
position: relative;
width: 800px;
height: 400px;
background-color: #333;
overflow: hidden;
border: 2px solid white;
}
#player {
position: absolute;
width: 40px;
height: 40px;
background-color: blue;
bottom: 10px;
left: 10px;
}
#enemy {
position: absolute;
width: 40px;
height: 40px;
background-color: red;
top: 10px;
left: 50%;
transform: translateX(-50%);
}
4. Add JavaScript for Game Logic
Create a script.js file to implement the game's behavior.
javascript
Copy
Edit
const player = document.getElementById('player');
const enemy = document.getElementById('enemy');
const gameContainer = document.getElementById('game-container');
let playerPosition = { x: 10, y: 350 };
let enemyPosition = { x: 400, y: 10 };
let enemySpeed = 2;
// Move player using arrow keys
document.addEventListener('keydown', (event) => {
const step = 10;
if (event.key === 'ArrowUp' && playerPosition.y > 0) {
playerPosition.y -= step;
}
if (event.key === 'ArrowDown' && playerPosition.y < 360) {
playerPosition.y += step;
}
if (event.key === 'ArrowLeft' && playerPosition.x > 0) {
playerPosition.x -= step;
}
if (event.key === 'ArrowRight' && playerPosition.x < 760) {
playerPosition.x += step;
}
player.style.transform = `translate(${playerPosition.x}px, ${playerPosition.y}px)`;
});
// Move enemy automatically
function moveEnemy() {
enemyPosition.y += enemySpeed;
if (enemyPosition.y > 360 || enemyPosition.y < 0) {
enemySpeed *= -1; // Change direction
}
enemy.style.transform = `translate(${enemyPosition.x}px, ${enemyPosition.y}px)`;
}
// Check for collision
function checkCollision() {
const playerRect = player.getBoundingClientRect();
const enemyRect = enemy.getBoundingClientRect();
if (
playerRect.left < enemyRect.right &&
playerRect.right > enemyRect.left &&
playerRect.top < enemyRect.bottom &&
playerRect.bottom > enemyRect.top
) {
alert('Game Over!');
resetGame();
}
}
// Reset game
function resetGame() {
playerPosition = { x: 10, y: 350 };
enemyPosition = { x: 400, y: 10 };
enemySpeed = 2;
player.style.transform = `translate(${playerPosition.x}px, ${playerPosition.y}px)`;
enemy.style.transform = `translate(${enemyPosition.x}px, ${enemyPosition.y}px)`;
}
// Game loop
function gameLoop() {
moveEnemy();
checkCollision();
requestAnimationFrame(gameLoop);
}
gameLoop();Editor is loading...
Leave a Comment