diff --git a/src/App.js b/src/App.js index 899cefc..9923325 100644 --- a/src/App.js +++ b/src/App.js @@ -11,21 +11,51 @@ class App extends React.Component { cardDeck: makeShuffledDeck(), // currCards holds the cards from the current round currCards: [], + hasGameStarted: false, + roundWinner: null, + player1NumRoundsWon: 0, + player2NumRoundsWon: 0, }; } - dealCards = () => { - // this.state.cardDeck.pop() modifies this.state.cardDeck array - const newCurrCards = [this.state.cardDeck.pop(), this.state.cardDeck.pop()]; + // Function to reset game to initial state + resetGame = () => { this.setState({ - currCards: newCurrCards, + cardDeck: makeShuffledDeck(), + currCards: [], + hasGameStarted: false, + roundWinner: null, + player1NumRoundsWon: 0, + player2NumRoundsWon: 0, }); }; - render() { - // You can write JavaScript here, just don't try and set your state! + dealCards = () => { + // Deal last 2 cards to currCards + const newCurrCards = this.state.cardDeck.slice(-2); + // Determine round winner based on card rank + const newRoundWinner = newCurrCards[0].rank > newCurrCards[1].rank ? 1 : 2; + + this.setState((state) => ({ + // Remove last 2 cards from cardDeck + cardDeck: state.cardDeck.slice(0, -2), + currCards: newCurrCards, + hasGameStarted: true, + roundWinner: newRoundWinner, + // Use prev state from setState argument instead of this.state to calculate what next state should be + // nested ternary operator to nest two if statements + player1NumRoundsWon: + newRoundWinner === 1 + ? state.player1NumRoundsWon + 1 + : state.player1NumRoundsWon, + player2NumRoundsWon: + newRoundWinner === 2 + ? state.player2NumRoundsWon + 1 + : state.player2NumRoundsWon, + })); + }; - // You can access your current components state here, as indicated below + render() { const currCardElems = this.state.currCards.map(({ name, suit }) => ( // Give each list element a unique key
{roundWinnerMessage}
} + {this.state.hasGameStarted &&{player1RoundsWonMessage}
} + {this.state.hasGameStarted &&{player2RoundsWonMessage}
} + {this.state.hasGameStarted &&{numRoundsLeftMessage}
} + {/* Render winner message if the game is over */} +{numRoundsLeft === 0 && gameWinnerMessage}