You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中创建符合棋子移动规则的19×19网格?

React棋盘网格实现需求

我用React编写了一个19×19的网格代码,计划实现黑后(Black-queen)和白后(white-queen)两种棋子,移动规则如下:

  • 黑后仅能在偶行偶列(白色背景单元格)移动
  • 白后仅能在奇行奇列(深灰色背景单元格)移动

以下是我的实现代码:

function Board() {
  const [gridCells, setGridCells] = useState([]);

  const handleClick = (id) => {
    console.log("King is clicked!", id);
  };

  useEffect(() => {
    const TOTAL = 19 * 19;
    const newGridCells = [];

    for (let i = 0; i < TOTAL; i++) {
      const row = Math.floor(i / 19);
      const col = i % 19;
      const colorClassName = row % 2 === 1 || col % 2 === 1 ? "red" : "green";

       newGridCells.push(
          <div
            key={i}
            id={`${row}_${col}`}
            className={`grid-cell ${colorClassName}`}
            chess="null"
            onClick={() => handleClick(`${row}_${col}`)}
          />
        );
    }

    setGridCells(newGridCells);
  }, []);

  return (
    <div id="GridContainer" className="colored-grid">
      {gridCells}
    </div>
  );
}

我需要让这个网格呈现出棋盘式配色效果:偶行偶列为白色单元格,奇行奇列为深灰色单元格,以此匹配两种棋子的移动区域。

内容的提问来源于stack exchange,提问作者balaji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:15:57