小猫跑酷

75 阅读1分钟
小猫跑酷游戏
分数: 0
const cat = document.getElementById('cat'); const obstacle = document.getElementById('obstacle'); const scoreElement = document.getElementById('score'); let score = 0;

function jump() { if (cat.classList != 'jump') { cat.classList.add('jump');

    setTimeout(function() {
        cat.classList.remove('jump');
    }, 300);
}

}

let isAlive = setInterval(function() { let catTop = parseInt(window.getComputedStyle(cat).getPropertyValue('top')); let obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue('left'));

if (obstacleLeft < 80 && obstacleLeft > 0 && catTop >= 150) {
    alert('游戏结束!你的分数是: ' + score);
    score = 0;
    scoreElement.textContent = '分数: ' + score;
    obstacle.style.left = '800px';
} else {
    score++;
    scoreElement.textContent = '分数: ' + score;
    if (obstacleLeft < -30) {
        obstacle.style.left = '800px';
    } else {
        obstacle.style.left = obstacleLeft - 10 + 'px';
    }
}

}, 10);

// 添加跳跃事件监听 document.addEventListener('keydown', function(event) { if (event.key === ' ' || event.key === 'ArrowUp') { jump(); } }); body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; overflow: hidden; }

#game-container { position: relative; width: 800px; height: 200px; border-bottom: 2px solid #333; background-color: #fff; }

#cat { position: absolute; width: 50px; height: 50px; bottom: 0; left: 50px; background-color: #ff6347; }

#obstacle { position: absolute; width: 30px; height: 60px; bottom: 0; right: 0; background-color: #008000; }

#score { position: absolute; top: 20px; right: 20px; font-size: 24px; font-weight: bold; }