js 棍子游戏
时间: 2023-07-08 15:09:12 浏览: 114
JS 棍子游戏是一款基于 JavaScript 编写的小游戏,玩家需要控制一根棍子跳过障碍物,挑战最高分数。
以下是简单的实现步骤:
1. 创建一个 HTML 页面,包括画布和计分器。
2. 使用 JavaScript 创建一个棍子对象,设置其初始位置和大小。
3. 创建一个障碍物对象数组,设置其初始位置和大小。
4. 在画布上绘制棍子和障碍物。
5. 监听用户按键事件,当用户按下空格键时,棍子开始伸长。
6. 当棍子的长度达到一定值时,障碍物开始向左移动。
7. 当障碍物撞到棍子时,游戏结束,显示最终得分。
具体实现可以参考以下代码:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Stick Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<div id="score">Score: 0</div>
<script src="stickgame.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
// 创建画布和计分器
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var score = 0;
var scoreElem = document.getElementById("score");
// 创建棍子对象
var stick = {
x: canvas.width / 2,
y: canvas.height - 50,
length: 0,
speed: 5,
color: "black",
draw: function() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y - this.length);
ctx.lineWidth = 10;
ctx.strokeStyle = this.color;
ctx.stroke();
},
update: function() {
if (this.length < canvas.height - 50) {
this.length += this.speed;
}
},
reset: function() {
this.length = 0;
}
};
// 创建障碍物对象数组
var obstacles = [];
for (var i = 0; i < 5; i++) {
var obstacle = {
x: i * canvas.width / 5 + 200,
y: canvas.height - 50,
width: 50,
height: 50,
speed: 5,
color: "red",
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
},
update: function() {
this.x -= this.speed;
if (this.x < -this.width) {
this.x = canvas.width;
score++;
scoreElem.innerHTML = "Score: " + score;
}
},
reset: function() {
this.x = i * canvas.width / 5 + 200;
}
};
obstacles.push(obstacle);
}
// 绘制棍子和障碍物
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stick.draw();
obstacles.forEach(function(obstacle) {
obstacle.draw();
});
}
// 更新棍子和障碍物
function update() {
stick.update();
obstacles.forEach(function(obstacle) {
obstacle.update();
});
}
// 监听用户按键事件
document.addEventListener("keydown", function(event) {
if (event.keyCode === 32) { // 空格键
if (stick.length === 0) {
stick.speed = 10;
}
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 32) { // 空格键
if (stick.length > 0) {
stick.speed = 5;
var stickEnd = stick.y - stick.length;
var obstacleLeft = obstacles[0].x;
var obstacleRight = obstacles[0].x + obstacles[0].width;
if (stickEnd >= canvas.height - 50 && stickEnd <= canvas.height - 50 + 20 && stickEnd >= obstacleLeft && stickEnd <= obstacleRight) {
alert("Game over! Your score is " + score);
score = 0;
scoreElem.innerHTML = "Score: " + score;
stick.reset();
obstacles.forEach(function(obstacle) {
obstacle.reset();
});
}
}
}
});
// 游戏循环
function loop() {
draw();
update();
requestAnimationFrame(loop);
}
loop();
```
阅读全文