从Python3.7中的嵌套while循环内继续main while循环

问题描述 投票:0回答:1

我决定制作一个二十一点游戏,我已经完成了,我唯一的问题是有时当你选择再次播放时,程序使用相同的变量值。我很确定我已经将问题隔离到嵌套的while循环,我的代码可以在这里找到:https://pastebin.com/9zr9qCU6我试图让resetGame()函数返回dealer_handplayer_hand的空列表对象但是没有修复它,是否有从这些嵌套的while循环中继续主要while循环的方法?或者我是否必须将每个嵌套的while循环重构为一个单独的函数?

码:

# Blackjack
import random
from card_deck import Deck
from time import sleep
from sys import exit

d = Deck()
deck_of_cards = d.deck_return()
print('*' * 30)
print('*  Welcome to BlackJack!  *')
print('*    Made by: p0seidon    *')
print('*' * 30)


def shuffleDeck(deck):
    random.shuffle(deck)
    random.shuffle(deck)
    random.shuffle(deck)
    return deck


def dealCard(shuffled_deck):
    return random.sample(shuffled_deck, k=2)


def removeFromDeck(hand1, hand2):
    global deck_of_cards
    for x in hand1:
        deck_of_cards.remove(x)

    for x in hand2:
        deck_of_cards.remove(x)


def hit(deck_to_hit):
    return random.choice(deck_to_hit)


def endGame():
    print('Thanks for playing!\n'
          'Better luck next time!')
    sleep(3)
    exit()


def restartGame():
    restart = ''
    restart_list = ['y', 'n']
    while restart not in restart_list:
        restart = input('Would you like to play again? [y/n]: ')

    return restart


def resetGame():
    global deck_of_cards
    print('Loading new deck.\n'
          'Please wait...')
    sleep(3)
    deck_of_cards = d.deck_return()
    return deck_of_cards


play_again = 'y'
while play_again == 'y':
    # shuffles and deals 2 cards to dealer and player
    ready_deck = shuffleDeck(deck_of_cards)
    dealer_hand = dealCard(ready_deck)
    player_hand = dealCard(ready_deck)

    # removes the cards in players hand from the deck, making the game a little more life-like
    removeFromDeck(dealer_hand, player_hand)

    # checks to see if dealer won in the first hand
    if sum(dealer_hand) == 21:
        print('Dealer\'s first hand is', dealer_hand, 'totaling 21.\n'
                                                      'You lose!')
        play_again = restartGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()

    # check to see if player won or busted in the first hand
    if sum(player_hand) == 21:
        print('You win with the initial hand of', player_hand, '\n'
                                                               'CONGRATULATIONS!')
        play_again = restartGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()
    elif sum(player_hand) > 21:
        print('Looks like you busted in your first hand consisting of', player_hand, '\n'
                                                                                     'Better luck next time!')
        play_again = restartGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()

    # shows only one of the dealers card at random and shows the player his hand
    print('DEBUG: dealers hand:', dealer_hand)
    # print('Dealer has', dealer_hand[random.randint(0, 1)], 'the other card is hidden')
    print('You have', player_hand)

    # sums the cards in players hand and dealers hand
    player_sum = sum(player_hand)
    dealer_sum = sum(dealer_hand)

    # player logic
    while player_sum < 21:
        choice = input('Would you like to hit or stay (h/s)?: ')
        if choice == 'h':
            new_player_card = hit(ready_deck)
            player_hand.append(new_player_card)
            print('Current hand:', player_hand)
            player_sum += new_player_card
            if player_sum == 21:  # player wins on hit
                print('You win!\n'
                      'Winning hand:', player_hand)
                play_again = restartGame()
                if play_again == 'y':
                    deck_of_cards = resetGame()
                elif play_again == 'n':
                    endGame()
            elif player_sum > 21:  # player busts on hit
                print('looks like you went overboard. Your final hand was:', player_hand)
                play_again = restartGame()
                if play_again == 'y':
                    deck_of_cards = resetGame()
                    continue
                elif play_again == 'n':
                    endGame()
        elif choice == 's':
            print('You locked in at', player_sum)
            sleep(2)
            break

    # dealer logic
    while dealer_sum < 17:
        print('Dealers hand:', dealer_hand)
        print('Dealer hits..')
        sleep(1)
        new_dealer_card = hit(ready_deck)
        dealer_hand.append(new_dealer_card)
        sleep(0.5)
        dealer_sum += new_dealer_card
        if dealer_sum > 21:  # dealer busts on hit
            print('Dealer has busted!\n'
                  'You Win!')
            print('Dealers losing hand:', dealer_hand)
            play_again = restartGame()
            if play_again == 'y':
                deck_of_cards = resetGame()
                continue
            elif play_again == 'n':
                endGame()
        elif 17 < dealer_sum <= 21:  # dealer stays
            print('Dealers hand:', dealer_hand)
            print('Dealer stays..')
            sleep(1)
            break

    # compares player sum with dealer sum to determine who won
    if player_sum > dealer_sum:
        print('You win!\n'
              'Your winning hand:', player_hand, '\n'
                                                 'Dealers losing hand:', dealer_hand)
        play_again = restartGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()
    elif dealer_sum > player_sum:
        print('Looks like you were unlucky this time...Dealer won..\n'
              'Dealer winning hand:', dealer_hand)
        play_again = restartGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()
    elif player_hand == dealer_hand:
        print('Its a tie!')
        sleep(0.5)
        print('Your hand:', player_hand)
        sleep(0.5)
        print('Dealers hand:', dealer_hand)
        sleep(0.5)
        play_again = resetGame()
        if play_again == 'y':
            deck_of_cards = resetGame()
            continue
        elif play_again == 'n':
            endGame()
`
python while-loop continue
1个回答
0
投票

有没有办法从这些嵌套的while循环中继续main while循环?

没有。看到Python doccontinue总是最内圈。

我是否必须重构每个嵌套while循环到一个单独的函数?

是。那更好。我厌倦了阅读你的代码,因为它很难快速理解。对您的问题更好的模式是这样的:

def play():
    while your_condition:
        while another_condition:
            pass # do something
            yesno = input("yes or no?")
            if yesno == "y":
                return True

terminate = False
while not terminate:
    terminate = play()

通过使用return,您可以找到一种方法来将breakcontinue作为内环的外环。

© www.soinside.com 2019 - 2024. All rights reserved.