From de2179607f9c5e70d96c0c582c52a7a4039536fb Mon Sep 17 00:00:00 2001 From: sukritmalpani <119888457+sukritmalpani@users.noreply.github.com> Date: Mon, 23 Oct 2023 16:52:18 +0530 Subject: [PATCH] Add number-guessing game --- .../src/examples/number-guessing.tsx | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 packages/kitchen-sink/src/examples/number-guessing.tsx diff --git a/packages/kitchen-sink/src/examples/number-guessing.tsx b/packages/kitchen-sink/src/examples/number-guessing.tsx new file mode 100644 index 0000000000..a15d0bf803 --- /dev/null +++ b/packages/kitchen-sink/src/examples/number-guessing.tsx @@ -0,0 +1,47 @@ +import React, { useState, FormEvent } from 'react'; +import { block } from 'million/react'; +interface NumberGuessingGameProps {} + +const NumberGuessingGame: React.FC = block(() => { + const [systemNumber] = useState(() => Math.floor(Math.random() * 10000) + 1); + const [userNumber, setUserNumber] = useState(0); + const [attempts, setAttempts] = useState(0); + const [message, setMessage] = useState( + 'Guess the number between 1 and 10000!', + ); + + const handleGuess = (e: FormEvent) => { + e.preventDefault(); + if (userNumber === systemNumber) { + setMessage(`Congratulations, you win in ${attempts} moves!`); + } else { + setAttempts(attempts + 1); + setMessage( + userNumber > systemNumber + ? 'Please decrease your value' + : 'Please increase your value', + ); + } + }; + + return ( +
+

Number Guessing Game

+

{message}

+

Moves taken: {attempts}

+
+ setUserNumber(parseInt(e.target.value))} + /> + +
+

+ Fun Fact : This game will take max 14 moves to win . Find out how :) +

+
+ ); +}); + +export default NumberGuessingGame;