捕鱼达人js的实现
时间: 2023-11-18 15:04:13 浏览: 29
捕鱼达人是一款非常经典的游戏,实现起来也比较简单。以下是一个基于 HTML、CSS 和 JavaScript 实现的简单版本。
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>捕鱼达人</title>
<style>
canvas {
border: 1px solid #ccc;
background-color: #eee;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<script src="fish.js"></script>
</body>
</html>
```
CSS 代码主要是为 canvas 元素添加了一些样式,使其看起来更美观。
JavaScript 代码:
```javascript
// 创建画布
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 创建鱼
var fish = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 20,
speed: 5
};
// 绘制鱼
function drawFish() {
ctx.beginPath();
ctx.arc(fish.x, fish.y, fish.radius, 0, Math.PI * 2);
ctx.fillStyle = "blue";
ctx.fill();
}
// 移动鱼
function moveFish(direction) {
switch(direction) {
case "up":
fish.y -= fish.speed;
break;
case "down":
fish.y += fish.speed;
break;
case "left":
fish.x -= fish.speed;
break;
case "right":
fish.x += fish.speed;
break;
}
}
// 监听键盘事件,控制鱼的移动
document.addEventListener("keydown", function(event) {
switch(event.keyCode) {
case 38: // 上
moveFish("up");
break;
case 40: // 下
moveFish("down");
break;
case 37: // 左
moveFish("left");
break;
case 39: // 右
moveFish("right");
break;
}
});
// 游戏循环
function gameLoop() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制鱼
drawFish();
// 循环调用自身
requestAnimationFrame(gameLoop);
}
// 启动游戏循环
requestAnimationFrame(gameLoop);
```
以上代码实现了一个简单的捕鱼达人游戏,玩家可以通过键盘控制鱼的移动。当然,如果要实现更完整的游戏功能,还需要添加鱼的生命值、吃饵料、避开障碍物等逻辑。