要制作一个类似于谷歌小恐龙的游戏,你可以使用HTML、CSS和JavaScript来实现。下面是一个简单的示例代码,可以在本地运行,以了解这个游戏的基本结构。

HTML (index.html)
html
CSS (style.css)
css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #f7f7f7;
}
#gameArea {
position: relative;
width: 600px;
height: 200px;
overflow: hidden;
border: 2px solid #333;
}
#dino {
position: absolute;
bottom: 0;
width: 40px;
height: 40px;
background: green;
}
#cactus {
position: absolute;
bottom: 0;
width: 20px;
height: 40px;
background: brown;
left: 600px;
}
#score {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
}
JavaScript (script.js)
javascript
let dino = document.getElementById('dino');
let cactus = document.getElementById('cactus');
let scoreDisplay = document.getElementById('score');
let score = 0;
let jumping = false;
// 跳跃功能
document.addEventListener('keydown', function(event) {
if (event.code === 'Space' && !jumping) {
jumping = true;
dino.classList.add('jump');
setTimeout(() => {
dino.classList.remove('jump');
jumping = false;
}, 800);
}
});
// 创建食草动物
let cactusInterval = setInterval(() => {
let cactusPosition = 600;
let randomTime = Math.random() * 4000 + 1000;
function createCactus() {
let cactus = document.createElement('div');
cactus.classList.add('cactus');
gameArea.appendChild(cactus);
cactus.style.left = cactusPosition + 'px';
let moveInterval = setInterval(() => {
if (cactusPosition <= -20) {
clearInterval(moveInterval);
cactus.remove();
score++;
scoreDisplay.textContent = "分数: " + score;
} else if(cactusPosition > 0 && cactusPosition < 60 && !jumping) {
clearInterval(moveInterval);
alert('游戏结束!分数: ' + score);
clearInterval(cactusInterval);
window.location.reload(); // 重新加载页面
} else {
cactusPosition -= 10;
cactus.style.left = cactusPosition + 'px';
}
}, 20);
}
setTimeout(createCactus, randomTime);
}, 2000);
使用说明
1. 创建一个文件夹,并在其中创建`index.html`、`style.css`和`script.js`三个文件,分别将上述HTML、CSS和JavaScript代码复制到相应的文件中。
2. 使用浏览器打开`index.html`文件。
3. 按空格键控制小恐龙跳跃,避免碰到障碍物(小仙人掌)。
这个代码只是一个简单的示例,你可以在此基础上进行改进,比如添加音效、提升动画效果、调整游戏难度等。祝你编程愉快!

查看详情

查看详情