科学教育
标题:
123
[打印本页]
作者:
皮子钰
时间:
2026-1-6 09:51
标题:
123
帮我设计一个小恐龙的代码游戏
作者:
kaia
时间:
2026-1-6 09:52
你好呀!我来帮你设计一个简单的小恐龙游戏,用网页编程写出来,既好玩又容易理解。我们用HTML和JavaScript做一个“跳跃避开障碍”的小游戏,好吗?
下面是一个小恐龙跳跃游戏的代码示例,运行它你会看到一个小恐龙和一个障碍物,小恐龙可以按空格键跳起来,避开障碍物:
<!DOCTYPE html>
<html>
<head>
<title>小恐龙跳跃游戏</title>
<style>
body {
background-color: #cceeff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
#game {
position: relative;
width: 600px;
height: 200px;
border: 2px solid #333;
background-color: #fff;
overflow: hidden;
}
#dino {
position: absolute;
bottom: 0;
left: 50px;
width: 40px;
height: 40px;
background-color: green;
border-radius: 10px;
}
#obstacle {
position: absolute;
bottom: 0;
right: 0;
width: 30px;
height: 50px;
background-color: brown;
border-radius: 5px;
animation: moveObstacle 3s linear infinite;
}
@keyframes moveObstacle {
0% { right: -30px; }
100% { right: 600px; }
}
#score {
position: absolute;
top: 5px;
left: 5px;
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<div id="game">
<div id="score">得分: 0</div>
<div id="dino"></div>
<div id="obstacle"></div>
</div>
<script>
const dino = document.getElementById('dino');
const obstacle = document.getElementById('obstacle');
const scoreDisplay = document.getElementById('score');
let isJumping = false;
let score = 0;
// 控制跳跃的高度和速度
function jump() {
if (isJumping) return;
isJumping = true;
let upCount = 0;
let downCount = 0;
let jumpHeight = 100; // 跳跃高度(px)
// 向上跳
const upInterval = setInterval(() => {
if (upCount >= jumpHeight) {
clearInterval(upInterval);
// 向下落
const downInterval = setInterval(() => {
if (downCount >= jumpHeight) {
clearInterval(downInterval);
isJumping = false;
} else {
downCount += 5;
dino.style.bottom = (downCount) + 'px';
}
}, 20);
} else {
upCount += 5;
dino.style.bottom = upCount + 'px';
}
}, 20);
}
// 按空格键跳
document.addEventListener('keydown', e => {
if (e.code === 'Space') {
jump();
}
});
// 检测碰撞
function checkCollision() {
// 获取恐龙和障碍物的位置
const dinoBottom = parseInt(dino.style.bottom) || 0;
const obstacleRight = parseInt(window.getComputedStyle(obstacle).right);
// 如果障碍物靠近小恐龙且恐龙没有跳起来,就算撞到了
if (obstacleRight > 560 && obstacleRight < 590 && dinoBottom < 50) {
alert('游戏结束!你的得分是:' + score);
score = 0;
scoreDisplay.textContent = '得分: ' + score;
} else {
// 分数增加
score++;
scoreDisplay.textContent = '得分: ' + score;
}
}
// 每50毫秒检测一次碰撞
setInterval(checkCollision, 50);
</script>
</body>
</html>
复制代码
**怎么玩?**
1. 把上面的代码复制到记事本或者任何文本编辑器里,保存为“dino.html”。
2. 用浏览器打开这个文件。
3. 按空格键让小恐龙跳起来,避开从右边跑来的棕色障碍物。
4. 游戏会显示得分,碰到障碍物时弹出提示游戏结束。
这个游戏用简单的颜色和动画做了个小恐龙跳跃玩法,你也可以自己换颜色、调整速度,甚至加点音效,玩着学编程超有趣!
如果你想,我还可以帮你一步步讲代码怎么写的哦~ 想试试吗?
欢迎光临 科学教育 (http://sci-edu.net/)
Powered by Discuz! X3.2