JSFiddle - React, Tailwind, and code Playground
by dj19910501
HTML
<div id="container"></div>
CSS
.board {
font-size: 20px;
display: flex;
flex-direction: column;
justify-content: center;
}
.row {
display: flex;
justify-content: center;
}
.cell {
display: flex;
background: rgb(60, 60, 60);
width: 50px;
height: 50px;
border: solid 1px white;
align-items: center;
justify-content: center;
cursor: pointer;
color: white;
}
.cell:hover {
background: black;
}
React
const App = () => {
return <Board />;
};
const SIZE = 4;
const getRandomState = () => {
const results = [];
const indexes = new Set(Array(SIZE*SIZE).fill(0).map((v, i) => i));
while (indexes.size) {
const randomIndex = parseInt(Math.random() * (SIZE * SIZE * 2));
console.log(randomIndex)
if (indexes.has(randomIndex)) {
results.push(randomIndex === SIZE * SIZE - 1 ? "" : randomIndex + 1);
indexes.delete(randomIndex);
}
}
return results;
};
const INITIAL_STATE = Array(SIZE*SIZE).fill(0).map((v, i) => i === SIZE * SIZE - 1 ? "" : i + 1);
const Board = () => {
const [state, setState] = React.useState(getRandomState());
const clickHandler = React.useCallback(index => {
if (state[index] === "") return;
let smallerIndex, largerIndex;
// above
if (index > SIZE - 1 && state[index - SIZE] === "") {
smallerIndex = index - SIZE;
largerIndex = index;
}
// below
if (index < SIZE * (SIZE - 1) && state[index + SIZE] === "") {
smallerIndex = index;
largerIndex = index + SIZE;
}
// left
if (index % SIZE && state[index - 1] === "") {
smallerIndex = index - 1;
largerIndex = index;
}
// right
if (index % SIZE < SIZE - 1 && state[index + 1] === "") {
smallerIndex = index;
largerIndex = index + 1;
}
if (smallerIndex !== undefined && largerIndex !== undefined) {
setState(state => ([
...state.slice(0, smallerIndex),
state[largerIndex],
...state.slice(smallerIndex + 1, largerIndex),
state[smallerIndex],
...state.slice(largerIndex + 1)
]));
}
}, [state]);
const rows = [];
for (let i = 0; i < SIZE; i++) {
rows.push(<Row rowIndex={i} key={i} state={state} clickHandler={clickHandler} />);
}
return (
<div className="board">
{rows}
{INITIAL_STATE.join("")}
{
state.join("") === INITIAL_STATE.join("") ? (<div>Win</div>) : (<div>Not...