honigle/src/App.tsx

83 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-01-09 16:04:33 -05:00
import { useState, useEffect } from "react";
import { Alert } from "./components/alerts/Alert";
2022-01-09 21:02:41 -05:00
import { Grid } from "./components/grid/Grid";
2022-01-08 18:35:47 -05:00
import { Keyboard } from "./components/keyboard/Keyboard";
2022-01-09 16:04:33 -05:00
import { WinModal } from "./components/win-modal/WinModal";
2022-01-09 21:43:58 -05:00
import { isWordInWordList, isWinningWord, solution } from "./lib/words";
function App() {
2022-01-08 18:35:47 -05:00
const [guesses, setGuesses] = useState<string[]>([]);
const [currentGuess, setCurrentGuess] = useState("");
2022-01-09 16:04:33 -05:00
const [isGameWon, setIsGameWon] = useState(false);
const [isWinModalOpen, setIsWinModalOpen] = useState(false);
const [isWordNotFoundAlertOpen, setIsWordNotFoundAlertOpen] = useState(false);
2022-01-09 21:43:58 -05:00
const [isGameLost, setIsGameLost] = useState(false);
2022-01-09 16:04:33 -05:00
useEffect(() => {
if (isGameWon) {
setIsWinModalOpen(true);
}
}, [isGameWon]);
2022-01-08 18:35:47 -05:00
const onChar = (value: string) => {
2022-01-09 16:04:33 -05:00
if (currentGuess.length < 5 && guesses.length < 6) {
2022-01-08 18:35:47 -05:00
setCurrentGuess(`${currentGuess}${value}`);
}
};
const onDelete = () => {
setCurrentGuess(currentGuess.slice(0, -1));
};
const onEnter = () => {
2022-01-09 16:04:33 -05:00
if (!isWordInWordList(currentGuess)) {
setIsWordNotFoundAlertOpen(true);
2022-01-09 21:37:12 -05:00
return setTimeout(() => {
setIsWordNotFoundAlertOpen(false);
}, 2000);
2022-01-09 16:04:33 -05:00
}
2022-01-09 21:43:58 -05:00
const winningWord = isWinningWord(currentGuess);
2022-01-09 16:04:33 -05:00
if (currentGuess.length === 5 && guesses.length < 6 && !isGameWon) {
2022-01-08 18:35:47 -05:00
setGuesses([...guesses, currentGuess]);
setCurrentGuess("");
2022-01-09 21:43:58 -05:00
if (winningWord) {
return setIsGameWon(true);
}
if (guesses.length === 5) {
setIsGameLost(true);
return setTimeout(() => {
setIsGameLost(false);
}, 2000);
}
2022-01-08 18:35:47 -05:00
}
};
return (
<div className="py-8 max-w-7xl mx-auto sm:px-6 lg:px-8">
<Alert message="Word not found" isOpen={isWordNotFoundAlertOpen} />
2022-01-09 21:43:58 -05:00
<Alert
message={`You lost, the word was ${solution}`}
isOpen={isGameLost}
/>
2022-01-09 21:02:41 -05:00
<Grid guesses={guesses} currentGuess={currentGuess} />
2022-01-09 17:06:37 -05:00
<Keyboard
onChar={onChar}
onDelete={onDelete}
onEnter={onEnter}
guesses={guesses}
/>
2022-01-09 16:04:33 -05:00
<WinModal
isOpen={isWinModalOpen}
handleClose={() => setIsWinModalOpen(false)}
2022-01-09 21:58:34 -05:00
guesses={guesses}
2022-01-09 16:04:33 -05:00
/>
</div>
);
}
export default App;