Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kitchen-Sink : Add number-guessing game #778

Merged
merged 1 commit into from
Oct 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions packages/kitchen-sink/src/examples/number-guessing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React, { useState, FormEvent } from 'react';
import { block } from 'million/react';
interface NumberGuessingGameProps {}

const NumberGuessingGame: React.FC<NumberGuessingGameProps> = block(() => {
const [systemNumber] = useState(() => Math.floor(Math.random() * 10000) + 1);
const [userNumber, setUserNumber] = useState<number>(0);
const [attempts, setAttempts] = useState<number>(0);
const [message, setMessage] = useState<string>(
'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 (
<div>
<h1>Number Guessing Game</h1>
<p>{message}</p>
<p>Moves taken: {attempts}</p>
<form onSubmit={handleGuess}>
<input
type="number"
value={userNumber}
onChange={(e) => setUserNumber(parseInt(e.target.value))}
/>
<button type="submit">Guess</button>
</form>
<h3>
Fun Fact : This game will take max 14 moves to win . Find out how :)
</h3>
</div>
);
});

export default NumberGuessingGame;
Loading