kcwu229 / Mobile-App-BlackJack-Game

4 stars 0 forks source link

How to pause the looping until the player has response (click on the button) #23

Closed kcwu229 closed 3 months ago

kcwu229 commented 3 months ago
  1. put the looping function on frontend page (future void function with async)
  2. set the flag
  3. set the await Future.any([ Future.delayed(Duration(days: 365 * 10 ^ 10), () {}

to wait for player take action


code :

import 'dart:async'; import 'dart:io';

import 'package:flutter/material.dart'; import 'package:flutter_blackjack/model/card.dart'; import 'package:flutter_blackjack/model/cardBack.dart'; import 'package:flutter_blackjack/model/deck.dart'; import 'package:flutter_blackjack/model/gameLogic.dart'; import 'package:flutter_blackjack/model/player.dart'; import 'package:flutter_blackjack/model/playerIcon.dart'; import 'package:flutter_blackjack/model/suit.dart';

// one of the function on mainPage // ignore: must_be_immutable class QuickGamePage extends StatefulWidget { @override _QuickGamePageState createState() => _QuickGamePageState(); }

class _QuickGamePageState extends State { // create the instance InitalGameState gs = InitalGameState(); bool playerResponsed = false; Completer completer = Completer(); bool playerTurn = false;

@override void initState() { super.initState(); loop(); }

// looping the round; Future loop() async { List players = gs.players;

// if not all the players are bust, the game would go on

while ((gs.countBust(players) + gs.countStand(players)) < players.length) {
  setState(() {
    playerResponsed = false;
  });
  for (var player in players) {
    await Future.delayed(const Duration(seconds: 2));
    // if player not stand / bust, he/ she can take action
    if ((player.hasStand == false) & (player.isBust == false)) {
      player.actionEnded = false;

      if (player.isPlayer == true) {
        setState(() {
          playerTurn = true;
        });
        if ((player.actionEnded == false) &
            (player.hasStand == false) &
            (player.isBust == false) &
            (player.gotNaturalBlackJack == false)) {
          if ((playerResponsed == false) && (player.isBust == false)) {
            //await waitForResponse;
            await Future.any([
              Future.delayed(Duration(days: 365 * 10 ^ 10), () {
                setState(() {
                  playerResponsed = true;
                  playerTurn = false;
                });
              }),
              completer.future,
            ]);
          }
        }
      } else {
        if (player.score < 15) {
          gs.hit(player);
          setState(() {});
        } else {
          gs.stand(player);
        }
      }
    }
  }
}

}

late Player dealer = gs.getPlayer('dealer'); late Player cpu1 = gs.getPlayer('cpu1'); late Player cpu2 = gs.getPlayer('cpu2'); late Player player = gs.getPlayer('player');

// add String String _playerAction = 'waiting';

void hit() { gs.hit(player); gs.playerEndTurn(player); setState(() { playerTurn = false; }); completer.complete(); }

void stand() { gs.stand(player); gs.playerEndTurn(player); setState(() { playerTurn = false; }); completer.complete(); }

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

@override Widget build(BuildContext context) { return Scaffold( body: Container( width: MediaQuery.of(context).size.width, decoration: const BoxDecoration(color: Colors.green), child: Center( child: Container( width: MediaQuery.of(context).size.width, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // Dealer's card in hand Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (var card in dealer.inHand) Container( child: card, ), Offstage( child: Container( child: Text('${dealer.score}'), ), offstage: !dealer.showScore, ) ], ),

          // Player's card in hand
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Row(children: [
                for (var card in gs.getPlayer('cpu1').inHand)
                  Container(child: card)
              ]),
              /*Offstage(
                child: Container(
                  child: Text('${cpu1.score}'),
                ),
                offstage: !cpu1.showScore,
              ),*/
              Row(children: [
                for (var card in gs.getPlayer('player').inHand)
                  Container(child: card)
              ]),
              /*Offstage(
                child: Container(
                  child: Text('${player.score}'),
                ),
                offstage: !player.showScore,
              ),*/
              Row(children: [
                for (var card in gs.getPlayer('cpu2').inHand)
                  Container(child: card)
              ]),
              /*
              Offstage(
                child: Container(
                  child: Text('${cpu2.score}'),
                ),
                offstage: !cpu2.showScore,
              ),*/
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              playerIcon(),
              playerIcon(),
              playerIcon(),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Visibility(
                  visible: ((playerResponsed == false) &&
                      (player.hasStand == false) &&
                      (player.isBust == false) &&
                      (player.gotNaturalBlackJack == false) &&
                      (playerTurn == true)),
                  child: ElevatedButton(
                      onPressed: () async {
                        setState(() {
                          playerResponsed = true;
                          hit();
                          completer.isCompleted;
                        });
                        await completer.future;
                        setState(() {
                          playerResponsed = false;
                          completer = Completer<void>();
                        });
                      },
                      child: Text('Hit'))),
              Visibility(
                  visible: ((playerResponsed == false) &&
                      (player.hasStand == false) &&
                      (player.isBust == false) &&
                      (player.gotNaturalBlackJack == false) &&
                      (playerTurn == true)),
                  child: ElevatedButton(
                      onPressed: () async {
                        setState(() {
                          playerResponsed = true;
                          stand();
                          completer.isCompleted;
                        });
                        await completer.future;
                        setState(() {
                          playerResponsed = false;
                          completer = Completer<void>();
                        });
                      },
                      child: Text('Stand'))),
            ],
          ),
        ],
      ),
    ),
  ),
));

} }