web,js中数组里有很多个移动的方块,当碰到挡板的时候消失 代码
时间: 2024-02-29 16:52:28 浏览: 51
C#编写的俄罗斯方块源代码2个例程,学习借鉴的地方挺多
以下是一个使用 HTML、CSS 和 JavaScript 实现的示例,其中包含多个移动的方块和一个挡板,当方块碰到挡板时,方块会消失。
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>移动方块</title>
<style>
#game {
position: relative;
width: 600px;
height: 400px;
border: 1px solid black;
}
.block {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
border: 1px solid black;
}
#paddle {
position: absolute;
width: 100px;
height: 10px;
background-color: blue;
border: 1px solid black;
bottom: 0;
left: 250px;
}
</style>
</head>
<body>
<div id="game">
<div class="block" style="top: 50px; left: 100px;"></div>
<div class="block" style="top: 100px; left: 200px;"></div>
<div class="block" style="top: 150px; left: 300px;"></div>
<div class="block" style="top: 200px; left: 400px;"></div>
<div id="paddle"></div>
</div>
<script src="script.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
const game = document.getElementById('game');
const blocks = game.getElementsByClassName('block');
const paddle = document.getElementById('paddle');
let score = 0;
function moveBlocks() {
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
let top = parseInt(block.style.top) || 0;
top += 5;
block.style.top = top + 'px';
if (top > game.offsetHeight) {
block.parentNode.removeChild(block);
} else if (isColliding(block, paddle)) {
block.parentNode.removeChild(block);
score++;
console.log('Score:', score);
}
}
}
function isColliding(a, b) {
const aRect = a.getBoundingClientRect();
const bRect = b.getBoundingClientRect();
return !(
aRect.bottom < bRect.top ||
aRect.top > bRect.bottom ||
aRect.right < bRect.left ||
aRect.left > bRect.right
);
}
setInterval(moveBlocks, 50);
```
这段代码会定时地移动每个方块,并检测它是否和挡板碰撞。如果有碰撞,则从页面中移除该方块,并增加得分。可以通过 CSS 调整游戏区域、方块和挡板的样式。
阅读全文