Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Яйцо в бегах</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <audio src="https://drive.google.com/uc?export=download&id=1GHze3jZbu1Dj7Rv5mllbPNC4Pcn900qo" autoplay loop></audio>
    
    <div id="gameContainer">
        <div id="score">0 секунд</div>
        <div id="gameArea">
            <div id="egg"></div>
        </div>
        <div id="instructions">Используйте стрелки на клавиатуре, чтобы не дать яйцу превратиться в яичницу</div>
        <button id="playButton">Играть</button>
        <button id="restartButton" style="display:none;">Играть заново</button>
        <div id="finalScore" style="display:none;"></div>
    </div>
    <script src="game.js"></script>
</body>
</html>

              
            
!

CSS

              
                body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
    font-family: Arial, sans-serif;
}

#gameContainer {
    text-align: center;
    position: relative;
    width: 800px;
}

#gameArea {
    position: relative;
    width: 800px;
    height: 600px;
    border: 2px solid #000;
    background-image: url('https://i.postimg.cc/vTmSTcz4/image.jpg');
    background-size: cover;
    background-position: center;
    margin: 20px auto;
}

#egg {
    width: 100px;
    height: 100px;
    background-image: url('https://i.postimg.cc/B6LhDdFg/image.png');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    position: absolute;
    top: 210px;
    left: 340px;
}

.pan {
    width: 200px;
    height: 200px;
    background-image: url('https://i.postimg.cc/63FG2PVC/image.png');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    position: absolute;
    visibility: visible;
}

#playButton,
#restartButton {
    padding: 10px 20px;
    font-size: 16px;
    margin: 10px;
    background-color: green;
    color: white;
    border: none;
    cursor: pointer;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 20px;
}

#score {
    font-size: 24px;
    margin-top: 10px;
    position: absolute;
    top: 10px;
    left: 50%;
    transform: translateX(-50%);
    background-color: white;
    padding: 5px 10px;
    border: 2px solid #000;
    border-radius: 5px;
}

#finalScore {
    font-size: 32px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: black; /* Changed color to black */
    background-color: white;
    padding: 10px 20px;
    border: 2px solid #000;
    border-radius: 5px;
}

#instructions {
    font-size: 18px;
    position: absolute;
    left: 50%;
    top: 60%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 10px 20px;
    border: 2px solid #000;
    border-radius: 5px;
}

              
            
!

JS

              
                const egg = document.getElementById('egg');
const playButton = document.getElementById('playButton');
const restartButton = document.getElementById('restartButton');
const gameArea = document.getElementById('gameArea');
const scoreDisplay = document.getElementById('score');
const finalScore = document.getElementById('finalScore');
const instructions = document.getElementById('instructions');

let gameInterval, panInterval, startTime;
let bestScore = localStorage.getItem('bestScore') ? parseFloat(localStorage.getItem('bestScore')) : 0;

function startGame() {
    playButton.style.display = 'none';
    restartButton.style.display = 'none';
    finalScore.style.display = 'none';
    instructions.style.display = 'none';
    egg.style.left = '360px';
    egg.style.top = '240px';
    startTime = Date.now();
    scoreDisplay.innerText = '0 секунд';

    document.addEventListener('keydown', moveEgg);
    gameInterval = setInterval(updateScore, 100);
    panInterval = setInterval(spawnPan, 2000);
}

function endGame() {
    clearInterval(gameInterval);
    clearInterval(panInterval);
    document.removeEventListener('keydown', moveEgg);
    document.querySelectorAll('.pan').forEach(pan => pan.remove());
    const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);

    if (parseFloat(elapsedTime) > bestScore) {
        bestScore = parseFloat(elapsedTime);
        localStorage.setItem('bestScore', bestScore);
    }

    finalScore.innerHTML = `Ты продержался <span class="time">${elapsedTime}</span> секунд<br>Лучший результат: <span class="best-time">${bestScore}</span> секунд`;
    finalScore.style.display = 'block';
    restartButton.style.display = 'block';
}

function updateScore() {
    const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
    scoreDisplay.innerText = `${elapsedTime} секунд`;
}

function spawnPan() {
    const pan = document.createElement('div');
    pan.classList.add('pan');

    let x, y;
    do {
        x = Math.random() * (gameArea.clientWidth - 200);
        y = Math.random() * (gameArea.clientHeight - 200);
    } while (isOverlappingEgg(x, y));

    pan.style.left = `${x}px`;
    pan.style.top = `${y}px`;
    
    gameArea.appendChild(pan);
    movePan(pan, Math.random() * Math.PI * 2);
}

function movePan(pan, direction) {
    const speed = 2;
    let deltaX = Math.cos(direction) * speed;
    let deltaY = Math.sin(direction) * speed;

    function step() {
        const rect = pan.getBoundingClientRect();
        const areaRect = gameArea.getBoundingClientRect();

        if (rect.left + deltaX < areaRect.left || rect.right + deltaX > areaRect.right) {
            deltaX = -deltaX;
        }
        if (rect.top + deltaY < areaRect.top || rect.bottom + deltaY > areaRect.bottom) {
            deltaY = -deltaY;
        }
        pan.style.left = `${pan.offsetLeft + deltaX}px`;
        pan.style.top = `${pan.offsetTop + deltaY}px`;

        if (checkCollision(egg, pan)) {
            endGame();
        } else {
            requestAnimationFrame(step);
        }
    }
    requestAnimationFrame(step);
}

function moveEgg(event) {
    const eggRect = egg.getBoundingClientRect();
    const step = 10;
    const areaRect = gameArea.getBoundingClientRect();
    switch (event.key) {
        case 'ArrowUp':
            if (eggRect.top > areaRect.top) {
                egg.style.top = `${egg.offsetTop - step}px`;
            }
            break;
        case 'ArrowDown':
            if (eggRect.bottom < areaRect.bottom) {
                egg.style.top = `${egg.offsetTop + step}px`;
            }
            break;
        case 'ArrowLeft':
            if (eggRect.left > areaRect.left) {
                egg.style.left = `${egg.offsetLeft - step}px`;
            }
            break;
        case 'ArrowRight':
            if (eggRect.right < areaRect.right) {
                egg.style.left = `${egg.offsetLeft + step}px`;
            }
            break;
    }
    checkPanCollision();
}

function isOverlappingEgg(x, y) {
    const eggRect = egg.getBoundingClientRect();
    const panRect = { left: x, top: y, right: x + 200, bottom: y + 200 };

    return !(
        eggRect.right < panRect.left ||
        eggRect.left > panRect.right ||
        eggRect.bottom < panRect.top ||
        eggRect.top > panRect.bottom
    );
}

function checkPanCollision() {
    const pans = document.querySelectorAll('.pan');
    pans.forEach(pan => {
        if (checkCollision(egg, pan)) {
            endGame();
        }
    });
}

function checkCollision(rect1, rect2) {
    const rect1Bounds = rect1.getBoundingClientRect();
    const rect2Bounds = rect2.getBoundingClientRect();

    return !(
        rect1Bounds.top >= rect2Bounds.bottom ||
        rect1Bounds.bottom <= rect2Bounds.top ||
        rect1Bounds.left >= rect2Bounds.right ||
        rect1Bounds.right <= rect2Bounds.left
    );
}

playButton.addEventListener('click', startGame);
restartButton.addEventListener('click', startGame);

              
            
!
999px

Console