|
| 1 | +import React from "react"; |
| 2 | +import "./App.css"; |
| 3 | +import Dice from "./Dice"; |
| 4 | +import { nanoid } from "nanoid"; |
| 5 | +import Confetti from "react-confetti"; |
| 6 | + |
| 7 | +export default function App() { |
| 8 | + const refreshPage = () => { |
| 9 | + window.location.reload(); |
| 10 | + }; |
| 11 | + const [dice, setDice] = React.useState(generateDice()); |
| 12 | + const [tanzies, setTanzies] = React.useState(false); |
| 13 | + |
| 14 | + React.useEffect(() => { |
| 15 | + const taptruth = dice.every((dice) => dice.tapon); |
| 16 | + if (taptruth) { |
| 17 | + setTanzies(true); |
| 18 | + console.log("You have won the game"); |
| 19 | + } |
| 20 | + }, [dice]); |
| 21 | + |
| 22 | + function useDieObjectData() { |
| 23 | + return { |
| 24 | + diceNum: Math.floor(Math.random() * 10), |
| 25 | + tapon: false, |
| 26 | + id: nanoid(), |
| 27 | + }; |
| 28 | + } |
| 29 | + function generateDice() { |
| 30 | + const newDice = []; |
| 31 | + for (let i = 0; i < 10; i++) { |
| 32 | + newDice.push(useDieObjectData()); |
| 33 | + } |
| 34 | + // console.log(newDice); |
| 35 | + return newDice; |
| 36 | + } |
| 37 | + |
| 38 | + function holdDiceValue(id) { |
| 39 | + setDice((prevDice) => |
| 40 | + prevDice.map((dice) => { |
| 41 | + return dice.id == id ? { ...dice, tapon: !dice.tapon } : dice; |
| 42 | + }) |
| 43 | + ); |
| 44 | + } |
| 45 | + function generateNewDice() { |
| 46 | + setDice((oldDice) => |
| 47 | + oldDice.map((olDice) => { |
| 48 | + return olDice.tapon ? olDice : useDieObjectData(); |
| 49 | + }) |
| 50 | + ); |
| 51 | + } |
| 52 | + function replaygame() { |
| 53 | + setTanzies(false); |
| 54 | + // event.preventDefault() |
| 55 | + dice.tapon === false; |
| 56 | + } |
| 57 | + |
| 58 | + const showDice = dice.map((diceData) => { |
| 59 | + return ( |
| 60 | + <Dice |
| 61 | + value={diceData.diceNum} |
| 62 | + key={diceData.id} |
| 63 | + tapon={diceData.tapon} |
| 64 | + holdDiceValue={() => holdDiceValue(diceData.id)} |
| 65 | + /> |
| 66 | + ); |
| 67 | + }); |
| 68 | + |
| 69 | + return ( |
| 70 | + <div className="container"> |
| 71 | + {tanzies && <Confetti />} |
| 72 | + <div className="textcontainer"> |
| 73 | + <p className="head">Tenzies</p> |
| 74 | + <p className="sub"> |
| 75 | + Roll until all dice are same. Click each dice to freeze it at its |
| 76 | + current value between rolls. |
| 77 | + </p> |
| 78 | + </div> |
| 79 | + {showDice} |
| 80 | + <div className="btn"> |
| 81 | + |
| 82 | + {tanzies ? ( |
| 83 | + <button className="btnroll" onClick={refreshPage}> |
| 84 | + Refresh |
| 85 | + </button> |
| 86 | + ) : ( |
| 87 | + <button className="btnroll" onClick={generateNewDice}> |
| 88 | + Roll |
| 89 | + </button> |
| 90 | + )} |
| 91 | + </div> |
| 92 | + </div> |
| 93 | + ); |
| 94 | +} |
0 commit comments