用react写一个俄罗斯方块

未经验证

使用React创建一个俄罗斯方块游戏是一个有趣且具有挑战性的项目。下面我们将构建一个简化版的俄罗斯方块游戏,包括基本的游戏逻辑和UI组件。

1. 创建 React 应用

首先,你需要安装 create-react-app 来快速生成一个新的 React 项目:

npx create-react-app tetris-game
cd tetris-game

然后删除默认的 src/App.js 文件中的内容,并替换为以下代码。

2. 安装必要的依赖

你可以使用一些实用的库来帮助你处理状态管理和其他功能。这里我们只需要基础的 React 库:

npm install

3. 编写游戏逻辑和 UI 组件

我们将创建一个名为 Tetris 的根组件,以及一些辅助函数。

App.js (主组件)

import React, { useState, useEffect } from 'react';

const ROWS = 20;
const COLS = 10;

function App() {
    const [board, setBoard] = useState(Array(ROWS * COLS).fill(0));
    const [tetromino, setTetromino] = useState(null);
    const [gameOver, setGameOver] = useState(false);

    useEffect(() => {
        if (!tetromino) return;
        let newBoard = board.slice();
        for (let i = 0; i < tetromino.shape.length; i++) {
            for (let j = 0; j < tetromino.shape[i].length; j++) {
                if (tetromino.shape[i][j] !== 0) {
                    newBoard[tetromino.y + i][tetromino.x + j] = tetromino.shape[i][j];
                }
            }
        }
        setBoard(newBoard);
    }, [tetromino]);

    useEffect(() => {
        if (gameOver) return;
        const intervalId = setInterval(dropTetromino, 1000); // 每秒下降一次
        return () => clearInterval(intervalId);
    });

    function dropTetromino() {
        let newTetromino = JSON.parse(JSON.stringify(tetromino));
        newTetromino.y++;
        if (checkCollision(newTetromino)) {
            setGameOver(true);
            return;
        }
        setTetromino(newTetromino);
    }

    function checkCollision(newTetromino) {
        for (let i = 0; i < newTetromino.shape.length; i++) {
            for (let j = 0; j < newTetromino.shape[i].length; j++) {
                if (newTetromino.shape[i][j] !== 0 && board[newTetromino.y + i][newTetromino.x + j] !== 0) {
                    return true;
                }
            }
        }
        return false;
    }

    useEffect(() => {
        setTetromino(new Tetromino());
    }, [gameOver]);

    const tetrominos = [
        { type: 'I', shape: [[1, 1, 1, 1]], x: COLS / 2 - 2 },
        // 更多的tetromino形状可以在这里定义
    ];

    function Tetromino() {
        return tetrominos[Math.floor(Math.random() * tetrominos.length)];
    }

    const boardStyle = { display: 'grid', gridTemplateColumns: `repeat(${COLS}, 1fr)`, gap: '0.5px' };
    const cellStyle = { width: '25px', height: '25px', backgroundColor: (val) => val ? 'blue' : 'white', border: '1px solid black' };

    return (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div id="board" style={boardStyle}>
                {board.map((cell, index) => (
                    <div key={index} style={cellStyle[cell]}></div>
                ))}
            </div>
        </div>
    );
}

export default App;

4. 样式调整

你可以在 src/App.css 文件中添加一些基本的样式:

#board {
    display: grid;
    grid-template-columns: repeat(10, 25px);
    gap: 0.5px;
}

.cell {
    width: 25px;
    height: 25px;
    background-color: white;
    border: 1px solid black;
}

5. 运行应用

现在你可以运行你的 React 应用:

npm start

这个基础版本的俄罗斯方块游戏已经具备了基本的游戏逻辑和UI。你可以在上面的基础上添加更多功能,比如旋转、移动、消除整行等,并增加更多的用户界面元素来显示分数和其他状态信息。

这只是简单的开始,你可以根据需要进一步扩展和完善这个游戏。