From a19e72afaf3124c9218f72f4dfe53c6a8ee43818 Mon Sep 17 00:00:00 2001 From: Mike Smith <89040888+smiggiddy@users.noreply.github.com> Date: Sun, 21 Jul 2024 23:29:25 -0400 Subject: [PATCH] feat: game logic complete --- .../mg-frontend/src/components/gameboard.jsx | 6 ++- memory-game/mg-frontend/src/gameLogic.js | 38 +++++++++++-------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/memory-game/mg-frontend/src/components/gameboard.jsx b/memory-game/mg-frontend/src/components/gameboard.jsx index 24c7b38..8966ceb 100644 --- a/memory-game/mg-frontend/src/components/gameboard.jsx +++ b/memory-game/mg-frontend/src/components/gameboard.jsx @@ -17,8 +17,10 @@ export default function GameBoard(props) { ); useEffect(() => { - fetchCards({ setCards }); - }, []); + if (props.gameStarted) { + fetchCards({ setCards }); + } + }, [props.gameStarted]); return ( <> diff --git a/memory-game/mg-frontend/src/gameLogic.js b/memory-game/mg-frontend/src/gameLogic.js index 72ce56a..e2c1cbf 100644 --- a/memory-game/mg-frontend/src/gameLogic.js +++ b/memory-game/mg-frontend/src/gameLogic.js @@ -54,28 +54,34 @@ class GameLogic { } 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)) { this.setScore(this.score + 1); } else { - console.log("Game Over"); - if (this.score + 1 > this.highScore) { - this.setHighScore(this.score); - } - // reset state - this.score = 0; - this.setScore(this.score); - this.setGameStarted(false); + this.handleLoss(); } } - async fetchCards() { - const cards = await fetch("http://localhost:8000/cards"); - const jsonCards = await cards.json(); + handleLoss() { + alert( + `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) => { - return { ...c, clicked: false, key: crypto.randomUUID() }; - }); - - this.setCards(gameCards); + resetGame() { + // reset state + this.score = 0; + this.setScore(this.score); + this.setGameStarted(false); } }