用javascript写一个俄罗斯方块小游戏
时间: 2023-03-02 21:16:03 浏览: 134
一个俄罗斯方块小游戏,由java编写.zip
俄罗斯方块是一款非常经典的游戏,使用 JavaScript 和 HTML5 可以很容易地实现。下面是一个简单的俄罗斯方块小游戏的示例,你可以基于这个示例进行修改和扩展。
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>俄罗斯方块</title>
<style>
#game-board {
width: 200px;
height: 400px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="tetris.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
var gameBoard = document.getElementById("game-board");
var ctx = gameBoard.getContext("2d");
var board = [];
for (var row = 0; row < 20; row++) {
board[row] = [];
for (var col = 0; col < 10; col++) {
board[row][col] = 0;
}
}
var pieces = [
// I
[
[1, 1, 1, 1]
],
// J
[
[1, 0, 0],
[1, 1, 1]
],
// L
[
[0, 0, 1],
[1, 1, 1]
],
// O
[
[1, 1],
[1, 1]
],
// S
[
[0, 1, 1],
[1, 1, 0]
],
// T
[
[0, 1, 0],
[1, 1, 1]
],
// Z
[
[1, 1, 0],
[0, 1, 1]
]
];
var colors = [
"#00ffff", // I
"#0000ff", // J
"#ff8000", // L
"#ffff00", // O
"#00ff00", // S
"#8000ff", // T
"#ff0000" // Z
];
var currentPiece = {
piece: pieces[Math.floor(Math.random() * pieces.length)],
row: 0,
col: 3
};
function drawSquare(row, col, color) {
ctx.fillStyle = color;
ctx.fillRect(col * 20, row * 20, 20, 20);
}
function drawBoard() {
for (var row = 0; row < board.length; row++) {
for (var col = 0; col < board[row].length; col++) {
if (board[row][col] !== 0) {
drawSquare(row, col, colors[board[row][col] - 1]);
}
}
}
}
function drawPiece() {
var piece = currentPiece.piece;
var row = currentPiece.row;
var col = currentPiece.col;
for (var r = 0; r < piece.length; r++) {
for (var c = 0; c < piece[r].length; c++) {
if (piece[r][c] === 1) {
drawSquare(row + r, col + c, colors[pieces.indexOf(piece)]);
}
}
}
}
function can
阅读全文