テトリスを作成するためには、HTML、CSS、JavaScriptを使用します。
まず、HTMLでゲーム画面を作成し、DIVタグでボックスを作成します。CSSでスタイリングをし、JavaScriptで動作を実装します。
以下がテトリスの実装例です。
``` html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScriptテトリス</title>
<style>
#gameBoard {
width: 360px;
height: 600px;
position: relative;
margin: auto;
overflow: hidden;
background-color: #ececec;
border: 30px solid #333;
box-sizing: border-box;
}
.box {
width: 36px;
height: 36px;
position: absolute;
background-color: #fff;
border: 1px solid #ccc;
box-sizing: border-box;
}
</style>
</head>
<body>
<div id="gameBoard"></div>
<script src="script.js"></script>
</body>
</html>
```
JavaScriptで動作を実装します。以下はシンプルな実装例です。
``` javascript
let board = [], piece;
// Create the board
for (let i = 0; i < 18; i++) {
board[i] = [];
for (let j = 0; j < 10; j++) {
board[i][j] = 0;
}
}
// Create a new piece
piece = createPiece();
drawPiece();
// Move the piece down every second
setInterval(moveDown, 1000);
function createPiece() {
// Generate a random piece
let types = ["I", "O", "T", "S", "Z", "J", "L"];
let type = types[Math.floor(Math.random() * types.length)];
let piece = {
type: type,
x: 4,
y: -1,
rotate: 0
};
return piece;
}
function drawPiece() {
// Draw the piece on the board
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (pieces[piece.type][piece.rotate][i][j]) {
let x = piece.x + j;
let y = piece.y + i;
board[y][x] = 1;
drawBox(x, y);
}
}
}
}
function drawBox(x, y) {
// Draw a box on the board
let box = document.createElement("div");
box.className = "box";
box.style.left = x * 36 + "px";
box.style.top = y * 36 + "px";
document.getElementById("gameBoard").appendChild(box);
}
function moveDown() {
// Move the piece down
piece.y++;
if (collision()) {
piece.y--;
placePiece();
piece = createPiece();
}
clearBoard();
drawPiece();
}
function collision() {
// Check for collisions with the board and other pieces
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (pieces[piece.type][piece.rotate][i][j]) {
let x = piece.x + j;
let y = piece.y + i;
if (x < 0 || x >= 10 || y >= 18 || board[y][x]) {
return true;
}
}
}
}
return false;
}
function placePiece() {
// Place the piece on the board permanently
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (pieces[piece.type][piece.rotate][i][j]) {
let x = piece.x + j;
let y = piece.y + i;
board[y][x] = 2;
}
}
}
}
function clearBoard() {
// Remove all boxes from the board
let boardDiv = document.getElementById("gameBoard");
while (boardDiv.firstChild) {
boardDiv.removeChild(boardDiv.firstChild);
}
}
```
このプログラムは、テトリスの一部のみ実装されており、まだ改善の余地がありますが、理解のための参考になれば幸いです。