feat: game logic complete

This commit is contained in:
Mike 2024-07-21 23:29:25 -04:00
parent 4902ed48f9
commit a19e72afaf
2 changed files with 26 additions and 18 deletions

View file

@ -17,8 +17,10 @@ export default function GameBoard(props) {
); );
useEffect(() => { useEffect(() => {
fetchCards({ setCards }); if (props.gameStarted) {
}, []); fetchCards({ setCards });
}
}, [props.gameStarted]);
return ( return (
<> <>

View file

@ -54,28 +54,34 @@ class GameLogic {
} }
updateScore(key) { updateScore(key) {
if (this.score + 1 === this.cards.length) {
alert("You won! 12/12 right");
this.resetGame();
return;
}
// go through game
if (!this.checkClick(key)) { if (!this.checkClick(key)) {
this.setScore(this.score + 1); this.setScore(this.score + 1);
} else { } else {
console.log("Game Over"); this.handleLoss();
if (this.score + 1 > this.highScore) {
this.setHighScore(this.score);
}
// reset state
this.score = 0;
this.setScore(this.score);
this.setGameStarted(false);
} }
} }
async fetchCards() { handleLoss() {
const cards = await fetch("http://localhost:8000/cards"); alert(
const jsonCards = await cards.json(); `Game Over! ${this.score + 1}/${this.cards.length} answers correcet!`,
);
if (this.score + 1 > this.highScore) {
this.setHighScore(this.score);
}
this.resetGame();
}
let gameCards = await jsonCards.map((c) => { resetGame() {
return { ...c, clicked: false, key: crypto.randomUUID() }; // reset state
}); this.score = 0;
this.setScore(this.score);
this.setCards(gameCards); this.setGameStarted(false);
} }
} }