Skip to content

Instantly share code, notes, and snippets.

@burnall
Last active March 28, 2024 22:47
Show Gist options
  • Save burnall/bb2defb330761fb3fa083a13b03c3f59 to your computer and use it in GitHub Desktop.
Save burnall/bb2defb330761fb3fa083a13b03c3f59 to your computer and use it in GitHub Desktop.
import React from "react"
import Confetti from "react-confetti"
const size = 10
export default function Playground() {
const [tiles, setTiles] = React.useState(getNewTiles)
const tileElements = tiles.map(tile => new Tile(tile))
const isGameOver = new Set(tiles.map(tile => tile.value)).size === 1
const onClick = () => setTiles(isGameOver ? initTiles() : generateTiles())
return (
<div className="playground">
{isGameOver && <Confetti/>}
<div className="playground--tiles">
{tileElements}
</div>
<button
className="playground--btn"
onClick={onClick}>
{isGameOver ? 'Reset Game' : 'Roll'}
</button>
</div>
)
}
function Tile(tile) {
return (
<span
key={tile.key}
onClick={() => toggleTile(tile.key)}
className={tile.isSelected ? 'tile selected' : 'tile'}>
{tile.value}
</span>
);
}
function getNewTiles() {
return [...Array(size)].map((_, index) => ({
value: randomValue(),
key: index,
isSelected: false
});
}
function randomValue() {
return Math.round(Math.random() * 5) + 1
}
function generateTiles(tiles) {
return tiles.map(tile =>
tile.isSelected ?
tile :
{
...tile,
value: randomValue()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment