Middle+
React task: implement a 10x10 game board (100 squares), each square randomly colored (red or green). When clicking on a square, its color changes to the opposite, and recursively, the color of all neighboring cells of the same color (vertically and horizontally) also changes.
sobes.tech AI
Answer from AI
Below is an example implementation of a 10x10 game board in React, where each square has a random color (red or green). When clicked, the color of the square changes to the opposite, and recursively, the colors of all neighboring cells of the same color are also changed vertically and horizontally.
import React, { useState, useEffect } from 'react';
const ROWS = 10;
const COLS = 10;
// Generate a random color: 'red' or 'green'
const randomColor = () => (Math.random() < 0.5 ? 'red' : 'green');
function GameBoard() {
const [board, setBoard] = useState([]);
useEffect(() => {
// Initialize the board with random colors
const initialBoard = Array.from({ length: ROWS }, () =>
Array.from({ length: COLS }, () => randomColor())
);
setBoard(initialBoard);
}, []);
const toggleColor = (color) => (color === 'red' ? 'green' : 'red');
const handleClick = (row, col) => {
const targetColor = board[row][col];
const newBoard = board.map(row => row.slice()); // deep copy
const visited = new Set();
const dfs = (r, c) => {
if (
r < 0 || r >= ROWS ||
c < 0 || c >= COLS ||
visited.has(`${r},${c}`) ||
newBoard[r][c] !== targetColor
) {
return;
}
visited.add(`${r},${c}`);
newBoard[r][c] = toggleColor(targetColor);
// Recursively change the color of neighboring cells
dfs(r - 1, c); // up
dfs(r + 1, c); // down
dfs(r, c - 1); // left
dfs(r, c + 1); // right
};
dfs(row, col);
setBoard(newBoard);
};
return (
<div style={{ display: 'grid', gridTemplateColumns: `repeat(${COLS}, 30px)`, gap: '2px' }}>
{board.map((row, rIdx) =>
row.map((color, cIdx) => (
<div
key={`${rIdx}-${cIdx}`}
onClick={() => handleClick(rIdx, cIdx)}
style={{
width: 30,
height: 30,
backgroundColor: color,
cursor: 'pointer',
border: '1px solid #000',
}}
/>
))
)}
</div>
);
}
export default GameBoard;