0
SUBTOTAL :

Furniture

Furniture/recent-label

Electronics

Electronics/recent-label

Fashion

Fashion/recent-label

Gadgets

Gadgets/recent-label
Action game

Action game

Size
Price:

Read more

<!DOCTYPE html>
<html>
<head>
    <title>Dodge the Obstacles</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="game-container">
        <div class="player"></div>
        <div class="obstacle"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>
.game-container {
    width: 400px;
    height: 400px;
    border: 1px solid black;
    position: relative;
}

.player, .obstacle {
    position: absolute;
    width: 50px;
    height: 50px;
    background-color: blue;
}

.player {
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
}

.obstacle {
    top: 0;
    right: 0;
}
const player = document.querySelector('.player');
const obstacle = document.querySelector('.obstacle');
const gameContainer = document.querySelector('.game-container');

let playerX = gameContainer.offsetWidth / 2 - player.offsetWidth / 2;
let obstacleX = gameContainer.offsetWidth;
let obstacleY = 0;

function movePlayer(event) {
    if (event.key === 'ArrowLeft') {
        playerX -= 10;
    } else if (event.key === 'ArrowRight') {
        playerX += 10;
    }

    player.style.left = playerX + 'px';
}

function moveObstacle() {
    obstacleX -= 5;
    obstacleY += 5;

    obstacle.style.left = obstacleX + 'px';
    obstacle.style.top = obstacleY + 'px';

    if (obstacleX + obstacle.offsetWidth < 0) {
        obstacleX = gameContainer.offsetWidth;
        obstacleY = 0;
    }

    if (
        playerX < obstacleX + obstacle.offsetWidth &&
        playerX + player.offsetWidth > obstacleX &&
        playerY < obstacleY + obstacle.offsetHeight &&
        playerY + player.offsetHeight > obstacleY
    ) {
        alert('Game Over!');
    }
}

document.addEventListener('keydown', movePlayer);

setInterval(moveObstacle, 20);



0 Reviews

Contact form

Name

Email *

Message *