0

我曾尝试使用 python 创建一个 BLACKJACK 游戏(实际上我正在学习 python)。目前我还没有设置下注命令(这是在我的 Account 类中编写的)。我只从我的 Account 类中取名字。

我有一个主文件:blackjack.py 和两个文件中的类:deckofcards.py、account.py 我只从帐户类访问名称,所以我不会把那么长的混乱放在这里。

二十一点.py:

from account import Account

player = Account('kalaLokia')
cards = DeckOfCards()
play = False
playershand = []
dealershand = []
action = ''
blackjack = False


def showCards(items, name):
    '''
    Shows {name}'s cards and hand value
    '''
    print(f"{name}'s hand: ")
    print(f"\t{' - '.join(items)}")
    print(f"Hand value: {cards.handValue(items)}")


def bust(hand):
    '''
    Whether a someone has busted or not
    '''
    if(cards.handValue(hand) > 21):
        return True
    return False


def dealersMove():
    '''
    Dealers move: executes when player calls "stand"
    Dealer perform hit until he gets bust, wins or his hand value becomes >= 17
    When hand value is >17 and players has greater value, dealer loses ;-)
    '''
    global blackjack

    if(cards.handValue(dealershand) == 21):
        print('Dealer got a BLACKJACK')
        print('Dealer WINS')
        return
    elif(blackjack):
        print(f'{player.name} got a BLACKJACK')
        print(f'{player.name} WINS')
        blackjack=False
        return

    while(not bust(dealershand)):

        if(cards.handValue(dealershand) > cards.handValue(playershand)):
            print('Dealer WINS')
            showCards(dealershand, 'Dealer')
            break
        elif(cards.handValue(dealershand) == cards.handValue(playershand)):
            print("It's a TIE!!\n Dealer WINS")
            break
        elif(cards.handValue(dealershand) > 17):
            print(f'Dealer loses\n{player.name} has WON.')
            print(f'{cards.handValue(playershand)} > {cards.handValue(dealershand)}')
            break

        dealershand.append(cards.hit())
    else:
        print(f'Dealer busts! \n{player.name} has WON the game.')


def start():
    '''
    The actiona that can be performed
    '''
    global blackjack

    if(cards.handValue(playershand) == 21): 
        blackjack = True
        dealersMove()
        return
    while(not bust(playershand)):

        action = input(
            f"{player.name}'s turn: Do you want to hit or stand ? ").lower()
        if(action == 'hit'):
            playershand.append(cards.hit())
            showCards(playershand, player.name)
        elif(action == 'stand'):
            dealersMove()
            break
        else:
            print('Please enter a valid action !')
    else:
        print(f'{player.name} has been BUSTED')


if __name__ == "__main__":

    print(f'Hello {player.name}, Welcome to BlackJack Game')
    # Tell game rules here, may be
    response = input('Do you want to start the game (Y/n)? ').lower()
    if(response != 'y'):
        play = False
        print('You have been exited the game')
    else:
        play = True
    # Ask for bet amount later
    while(play):
        cards = DeckOfCards()
        cards.shuffle()
        print('Cards on the table is now shuffled')
        playershand = list(cards.initiate())
        dealershand = list(cards.initiate())
        print(
            f"{player.name}'s hand:\n   {playershand[0]} - {playershand[1]}\nHand value: {cards.handValue(playershand)}\n")
        print(f"Dealer's hand:\n   {dealershand[0]} - ?\n")

        start()

        if(input('Do you want to play again (Y/n)?').lower() != 'y'):
            print('The End')
            play = False

卡片组.py:

import random

class DeckOfCards():
    '''
    All talks here is about cards
    '''
    cards = {'A':11,'K':10,'Q':10,'J':10,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10}

    def __init__(self):
        '''
        Initialize deck of cards
        '''
        self.deck = list(self.cards.keys())*4

    def shuffle(self):
        '''
        Simply shuffles the deck of cards
        '''
        return random.shuffle(self.deck)

    def handValue(self, hand):
        '''
        Calculates and returns the hand value, expecting a string value to be feeded.
        '''
        result = 0

        for element in hand:
            result = result + self.cards[element]

        while('A' in hand and result > 21):
            if(hand[0]=='A'):
                result = result - 10
            # Somehow this hand.pop is poping out from main value itself. Why ???
            hand.pop(0)

            if(hand == []):
                break  

        return result

    def hit(self):
        '''
        Pop out and returns the last card in the deck
        '''
        return self.deck.pop()

    def initiate(self):
        '''
        Pop out 2 cards from the deck and return as a tuple
        '''
        return (self.deck.pop(), self.deck.pop() )

问题:
当我手上有一张 ACE 并且我的手牌值大于 21 时,while 条件在handValue函数(位于 DeckofCards 类中)中按原样执行。问题是,在该while条件执行后,playershand (在主文件中声明)我刚刚传递给该handValue函数的内容为空。这hand.pop(0)实际上似乎是从主对象本身弹出的值playershand(看来我是这样)。

当我在那之后按下一个击键时,我得到一张新卡,所有其他卡都被弹出。我不明白为什么会这样。

On hit(user enter hit) :实际上我将playershand(玩家手上的卡片,它是一个列表)传递给函数showCards (也在主文件中),它将它作为参数项并将其传递给handValue类中的函数DeckOfCards

那么为什么会这样呢?即使我将 playerhand 作为参数传递给其他函数,pop() 函数如何影响仅访问 handValue 类中的手对象的 playerhand?

我在github repo中有完整的代码来测试,文件夹 blackjack 中的文件

4

0 回答 0