JavaScript 俄罗斯方块游戏
时间: 2023-08-25 16:07:48 浏览: 82
javascript 游戏俄罗斯方块
以下是一个简单的 JavaScript 俄罗斯方块游戏的示例代码:
```
<html>
<head>
<title>JavaScript 俄罗斯方块游戏</title>
<style>
#game-board {
border: 5px solid black;
width: 300px;
height: 600px;
position: relative;
}
.block {
position: absolute;
width: 30px;
height: 30px;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script>
var board = document.getElementById("game-board");
var blocks = [];
var currentBlock = null;
var intervalId = null;
var score = 0;
function createBlock() {
var block = document.createElement("div");
block.className = "block";
block.style.backgroundColor = getRandomColor();
block.style.top = "0px";
block.style.left = getRandomPosition() + "px";
board.appendChild(block);
return block;
}
function getRandomColor() {
var colors = ["red", "blue", "green", "yellow"];
var index = Math.floor(Math.random() * colors.length);
return colors[index];
}
function getRandomPosition() {
return Math.floor(Math.random() * 270);
}
function moveBlockDown() {
var top = parseInt(currentBlock.style.top);
if (top < 570) {
currentBlock.style.top = (top + 30) + "px";
} else {
clearInterval(intervalId);
checkForCompletedRows();
currentBlock = createBlock();
intervalId = setInterval(moveBlockDown, 500);
}
}
function checkForCompletedRows() {
var rows = {};
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i];
var row = parseInt(block.style.top) / 30;
if (rows[row]) {
rows[row].push(block);
} else {
rows[row] = [block];
}
}
for (var row in rows) {
if (rows[row].length == 10) {
for (var i = 0; i < rows[row].length; i++) {
var block = rows[row][i];
block.parentNode.removeChild(block);
var index = blocks.indexOf(block);
blocks.splice(index, 1);
}
score += 100;
document.getElementById("score").innerHTML = "Score: " + score;
moveBlocksDownAboveRow(row);
}
}
}
function moveBlocksDownAboveRow(row) {
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i];
if (parseInt(block.style.top) < (row * 30)) {
block.style.top = (parseInt(block.style.top) + 30) + "px";
}
}
}
document.addEventListener("keydown", function(event) {
var left = parseInt(currentBlock.style.left);
if (event.keyCode == 37 && left > 0) { // left arrow key
currentBlock.style.left = (left - 30) + "px";
} else if (event.keyCode == 39 && left < 270) { // right arrow key
currentBlock.style.left = (left + 30) + "px";
} else if (event.keyCode == 40) { // down arrow key
clearInterval(intervalId);
intervalId = setInterval(moveBlockDown, 100);
}
});
currentBlock = createBlock();
intervalId = setInterval(moveBlockDown, 500);
</script>
<div id="score">Score: 0</div>
</body>
</html>
```
该代码使用 HTML、CSS 和 JavaScript 创建了一个具有基本游戏逻辑的俄罗斯方块游戏。游戏板上生成随机颜色的方块,玩家可以使用左右箭头键移动方块,使用下箭头键加速下落。当方块堆积到游戏板底部或其他方块上方时,会生成新的方块。当一行方块填满时,该行方块将被移除并增加得分。游戏将在玩家不能再放置新方块时结束。
阅读全文