kcwu229 / Mobile-App-BlackJack-Game

4 stars 0 forks source link

Once I click the 'Hit' button, how does the updated cards can be shown on screen #20

Closed kcwu229 closed 3 months ago

kcwu229 commented 3 months ago

https://poe.com/s/z1CVPEp20BSA0bbd5QGP

To display the new card drawn by the player on the UI after clicking the "Hit" button, you can update the state of the QuickGamePage widget and trigger a rebuild of the widget tree.

Here's how you can modify the code to achieve this:

  1. Convert the QuickGamePage class to a StatefulWidget instead of a StatelessWidget.
  2. Create a _QuickGamePageState class that extends State<QuickGamePage>.
  3. Move the game state-related properties and methods to the _QuickGamePageState class.
  4. Update the _drawCardFromDeck() method to call setState() to trigger a rebuild of the widget tree.

Here's the updated code:

class QuickGamePage extends StatefulWidget {
  @override
  _QuickGamePageState createState() => _QuickGamePageState();
}

class _QuickGamePageState extends State<QuickGamePage> {
  // create the instance
  late InitalGameState gs;
  late Player dealer;
  late Player cpu1;
  late Player cpu2;
  late Player player;

  @override
  void initState() {
    super.initState();
    gs = InitalGameState();
    dealer = gs.getPlayer('dealer');
    cpu1 = gs.getPlayer('cpu1');
    cpu2 = gs.getPlayer('cpu2');
    player = gs.getPlayer('player');
  }

  void _drawCardFromDeck() {
    print('button pressed');
    gs.drawCard(player.inHand, gs.deck);
    print(player.inHand.length);
    setState(() {
      // Update the UI to reflect the new card in the player's hand
    });
  }

  List<Widget> dealerHandWidgets(Player player) {
    return player.inHand
        .map((card) => MyCard(suit: card.suit, rank: card.rank))
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ... (rest of the build method)
    );
  }
}

In the updated code:

  1. The QuickGamePage class is now a StatefulWidget, and the _QuickGamePageState class contains the game state-related properties and methods.
  2. The _drawCardFromDeck() method now calls setState() to trigger a rebuild of the widget tree after the player draws a card.
  3. You'll need to update the UI in the setState() block to reflect the new card in the player's hand. This could involve updating the Row that displays the player's cards, or any other relevant UI elements.

By converting the QuickGamePage to a StatefulWidget and updating the state when the player draws a card, the UI will be automatically updated to display the new card in the player's hand.