I want to create simple 2048 game application. My initial board is composed of 16 array elements. This function is meant to generate a value of '2' in a random empty element It works just fine and creates one random '2' for me, but the problem starts when I want to call it twice in a handler I've read about prevState but have no idea how to implement it in this batch of code to work properly.
Here is my game component:
const width = 4;
const Game = () => {
const [Board, setBoard] = useState([]);
const createBoard = () => {
let initialBoard = [];
for (let i = 0; i < width * width; i ) {
initialBoard.push("");
}
return initialBoard;
};
const generate = () => {
let board = [...Board];
let randomNumber = Math.floor(Math.random() * Board.length);
console.log(randomNumber);
if (board[randomNumber] === "") {
board[randomNumber] = 2;
setBoard(board);
} else generate()
};
const handleNewGame = () => {
generate()
}
useEffect(() => {
setBoard(createBoard);
console.log(`Board Created!`);
}, []);
return (
<div className="game-container">
<button onClick={handleNewGame}>NewGame</button>
<div className="game">
{Board.map((value, index) => (
<div className="tile" key={index}>
{value}
</div>
))}
</div>
</div>
);
};
export default Game;
I'll be glad for the workaround.
CodePudding user response:
Just us function instead of value
const generate = () => {
setState(Board => {
let board = [...Board];
while (true) {
let randomNumber = Math.floor(Math.random() * Board.length);
console.log(randomNumber);
if (board[randomNumber] === "") {
board[randomNumber] = 2;
break
}
}
}
}
CodePudding user response:
If i got the problem right, when you clicked New Game, the board was not starting a new one?
Try this:
const generate = () => {
let board = createBoard(); //START FROM A NEW BOARD INSTEAD OF USING THE CURRENT ALREADY STARTED BOARD
let randomNumber = Math.floor(Math.random() * Board.length);
console.log(randomNumber);
if (board[randomNumber] === '') {
board[randomNumber] = 2;
setBoard(board);
} else generate();
};