<!DOCTYPE html>
<html>
<head>
<title>大鱼吃小鱼</title>
<style>
#gameArea {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.fish {
width: 50px;
height: 50px;
position: absolute;
}
.bigFish {
background-color: blue;
}
.smallFish {
background-color: green;
}
</style>
</head>
<body>
<h1>大鱼吃小鱼</h1>
<div id="gameArea">
<div id="bigFish" class="fish bigFish"></div>
<div id="smallFish" class="fish smallFish"></div>
</div>
<script>
const bigFish = document.getElementById('bigFish');
const smallFish = document.getElementById('smallFish');
let smallFishX = 0;
let smallFishY = 0;
let smallFishSpeedX = 2;
let smallFishSpeedY = 2;
function updateSmallFishPosition() {
smallFishX += smallFishSpeedX;
smallFishY += smallFishSpeedY;
if (smallFishX < 0 || smallFishX + 50 > 400) {
smallFishSpeedX *= -1;
}
if (smallFishY < 0 || smallFishY + 50 > 400) {
smallFishSpeedY *= -1;
}
smallFish.style.left = smallFishX + 'px';
smallFish.style.top = smallFishY + 'px';
}
setInterval(updateSmallFishPosition, 20);
function checkCollision() {
const bigFishRect = bigFish.getBoundingClientRect();
const smallFishRect = smallFish.getBoundingClientRect();
if (bigFishRect.left < smallFishRect.left + smallFishRect.width &&
bigFishRect.left + bigFishRect.width > smallFishRect.left &&
bigFishRect.top < smallFishRect.top + smallFishRect.height &&
bigFishRect.top + bigFishRect.height > smallFishRect.top) {
alert('大鱼吃掉了小鱼!');
smallFishX = 0;
smallFishY = 0;
}
}
setInterval(checkCollision, 100);
</script>
</body>
</html>
你可以将上面的HTML代码复制到文本编辑器中并将文件保存为.html文件,然后在浏览器中打开它以运行“大鱼吃小鱼”游戏。游戏区域被定义为400x400像素的矩形,其中包括一个蓝色的大鱼和一个绿色的小鱼。小鱼将在游戏区域中移动,当小鱼碰到大鱼时,游戏将弹出一个警告框以提示玩家。
#本文所包含的App