시작 누르기도전에 시작 되고 장애물 추가가 되지 않음

html

        return parseInt(aTime[0]) * 60 + parseInt(aTime[1]) - (parseInt(bTime[0]) * 60 + parseInt(bTime[1]));
    });
    if (scores.length > 10) scores.length = 10; // 랭킹 10명까지 제한
    localStorage.setItem('scores', JSON.stringify(scores));
}

function displayRanking() {
    const scores = JSON.parse(localStorage.getItem('scores')) || [];
    rankingDiv.innerHTML = '<h3>랭킹</h3>' + scores.slice(0, 10).map(score => `<p>${score.name} - ${score.ip} - ${score.time}</p>`).join('');
}

function getUserIP() {
    // 예시 IP를 반환합니다. 실제로는 서버 측에서 IP를 받아와야 합니다.
    return '192.168.0.1';
}

function getRandomPattern() {
    return obstaclePatterns[Math.floor(Math.random() * obstaclePatterns.length)];
}

setInterval(checkCollision, 10);
setInterval(jump, 20);

displayRanking();

css

body {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
}

.controls {
    display: flex;
    gap: 15px;
    margin-top: 20px;
}

.control-button {
    padding: 15px 30px;
    font-size: 18px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    background-color: #3498db;
    color: white;
    transition: background-color 0.3s ease, transform 0.2s ease;
}

.control-button:hover {
    background-color: #2980b9;
    transform: scale(1.05);
}

#timer {
    margin-left: 20px;
    font-size: 20px;
}

.game-container {
    position: relative;
    width: 800px;
    height: 400px;
    border: 2px solid #000;
    overflow: hidden;
    background-color: #fff;
    margin-top: 20px;
}

.player {
    position: absolute;
    bottom: 0;
    left: 50px;
    width: 50px;
    height: 50px;
    background-image: url('https://img.icons8.com/ios-filled/50/000000/person-male.png');
    background-size: cover;
}

.obstacle {
    position: absolute;
    bottom: 0;
    width: 50px;
    height: 50px;
    background-color: #e74c3c;
}

#obstacle1 { right: -50px; }
#obstacle2 { right: -200px; }
#obstacle3 { right: -350px; }

.ranking {
    margin-top: 20px;
    background-color: #ffffffaa;
    padding: 10px;
    border: 1px solid #ccc;
    width: 800px;
}

@keyframes moveObstacle {
    0% {
        right: -50px;
    }
    100% {
        right: 850px;
    }
}

@keyframes moveObstacleReverse {
    0% {
        right: 850px;
    }
    100% {
        right: -50px;
    }
}

@keyframes moveObstacleFast {
    0% {
        right: -50px;
    }
    100% {
        right: 850px;
    }
}

js

const player = document.getElementById('player');
const obstacles = [
    document.getElementById('obstacle1'),
    document.getElementById('obstacle2'),
    document.getElementById('obstacle3')
];
const startButton = document.getElementById('startButton');
const pauseButton = document.getElementById('pauseButton');
const stopButton = document.getElementById('stopButton');
const rankingDiv = document.getElementById('ranking');
const timerDiv = document.getElementById('timer');

let isJumping = false;
let isGameRunning = false;
let isGamePaused = false;
let jumpHeight = 0;
let gameTime = 0;
let gameSpeed = 1.5;
const obstaclePatterns = ['moveObstacle', 'moveObstacleReverse', 'moveObstacleFast'];

startButton.addEventListener('click', startGame);
pauseButton.addEventListener('click', pauseGame);
stopButton.addEventListener('click', stopGame);

document.addEventListener('keydown', function(event) {
    if (event.code === 'Space' && isGameRunning && !isGamePaused) {
        if (!isJumping) {
            isJumping = true;
            jumpHeight = 0;
        }
        jumpHeight += 5;  // 누를 때마다 점프 높이 증가
    }
});

document.addEventListener('keyup', function(event) {
    if (event.code === 'Space') {
        isJumping = false;
    }
});

function startGame() {
    isGameRunning = true;
    isGamePaused = false;
    startButton.style.display = 'none';
    pauseButton.style.display = 'inline-block';
    stopButton.style.display = 'inline-block';
    gameTime = 0;
    gameSpeed = 1.5;
    resetObstacles();
    obstacles.forEach(obstacle => {
        obstacle.style.animationPlayState = 'running';
    });
    updateTimer();
}

function pauseGame() {
    if (isGameRunning) {
        isGamePaused = !isGamePaused;
        obstacles.forEach(obstacle => {
            obstacle.style.animationPlayState = isGamePaused ? 'paused' : 'running';
        });
    }
}

function stopGame() {
    isGameRunning = false;
    obstacles.forEach(obstacle => {
        obstacle.style.animationPlayState = 'paused';
    });
    startButton.style.display = 'inline-block';
    pauseButton.style.display = 'none';
    stopButton.style.display = 'none';
    alert('Game Over');
    saveScore(prompt('이름을 입력하세요:'), getUserIP(), gameTime);
    displayRanking();
    resetGame();
}

function resetGame() {
    isJumping = false;
    isGameRunning = false;
    isGamePaused = false;
    jumpHeight = 0;
    gameTime = 0;
    obstacles.forEach(obstacle => {
        obstacle.style.animation = 'none';
        obstacle.style.right = '-50px';
    });
}

function resetObstacles() {
    obstacles.forEach((obstacle, index) => {
        obstacle.style.animation = 'none';
        obstacle.offsetHeight; // reflow
        obstacle.style.animation = `${getRandomPattern()} ${gameSpeed}s linear infinite`;
        obstacle.style.right = `${-50 - index * 150}px`;
    });
}

function jump() {
    if (isJumping) {
        let bottomValue = parseInt(window.getComputedStyle(player).getPropertyValue('bottom'));
        if (bottomValue + jumpHeight <= 350) {  // 화면 상단을 넘지 않도록 제한
            player.style.bottom = bottomValue + jumpHeight + 'px';
        } else {
            player.style.bottom = '350px';
            isJumping = false; // 상단에 도달하면 자동으로 내려가도록
        }
    } else {
        let bottomValue = parseInt(window.getComputedStyle(player).getPropertyValue('bottom'));
        if (bottomValue > 0) {
            player.style.bottom = bottomValue - 5 + 'px';
        }
    }
}

function checkCollision() {
    if (!isGameRunning || isGamePaused) return;

    const playerRect = player.getBoundingClientRect();
    for (let obstacle of obstacles) {
        const obstacleRect = obstacle.getBoundingClientRect();
        if (
            playerRect.right > obstacleRect.left &&
            playerRect.left < obstacleRect.right &&
            playerRect.bottom > obstacleRect.top
        ) {
            stopGame();
            return;
        }
    }
}

function updateTimer() {
    if (!isGameRunning || isGamePaused) return;

    gameTime++;
    timerDiv.textContent = `시간: ${gameTime}초`;

    if (gameTime % 20 === 0) {
        gameSpeed *= 0.9;
        resetObstacles();
    }

    setTimeout(updateTimer, 1000);
}

function saveScore(name, ip, time) {
    const maskedIP = ip.split('.').slice(0, 3).join('.') + '.***';
    const scores = JSON.parse(localStorage.getItem('scores')) || [];
    scores.push({ name, ip: maskedIP, time: `${Math.floor(time / 60)}분 ${time % 60}초` });
    scores.sort((a, b) => {
        const aTime = a.time.split('분');
        const bTime = b.time.split('분');
               return parseInt(aTime[0]) * 60 + parseInt(aTime[1]) - (parseInt(bTime[0]) * 60 + parseInt(bTime[1]));
    });
    if (scores.length > 10) scores.length = 10; // 랭킹 10명까지 제한
    localStorage.setItem('scores', JSON.stringify(scores));
}

function displayRanking() {
    const scores = JSON.parse(localStorage.getItem('scores')) || [];
    rankingDiv.innerHTML = '<h3>랭킹</h3>' + scores.slice(0, 10).map(score => `<p>${score.name} - ${score.ip} - ${score.time}</p>`).join('');
}

function getUserIP() {
    // 예시 IP를 반환합니다. 실제로는 서버 측에서 IP를 받아와야 합니다.
    return '192.168.0.1';
}

function getRandomPattern() {
    return obstaclePatterns[Math.floor(Math.random() * obstaclePatterns.length)];
}

setInterval(checkCollision, 10);
setInterval(jump, 20);

displayRanking();

Categorized in:

간단 게임,