类型错误:在21点游戏中使用random.chips时,'int'对象不可下标。

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

我得到一个 TypeError int object is not subscriptable 和我的代码是未完成的,我只是想知道我的错误在哪里,我怎么能解决它,谢谢:)

Traceback (most recent call last):

  File "C:\Users\TOSHIBA\.spyder-py3\untitled1.py", line 40, in <module>
    print('You have:' , card_values(player_hand)) # telling the player's value if he stands

  File "C:\Users\TOSHIBA\.spyder-py3\untitled1.py", line 19, in card_values
    if (i[0:1] == 'J' or i[0:1] == 'Q' or i[0:1] == 'K' or i[0:1] == 10):

TypeError: 'int' object is not subscriptable

这是我得到的错误

#Code Begins

print('Welcome to BLACKJACK!') # welcome message

import random #importing random function
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # list for the cards with mixed data types
player_hand = random.choices(cards, k=2) #Drawing the player's cards(hand)
dealer_hand = random.choices(cards, k=2) #Drawing the dealer's cards(hand)

def card_values(the_hand): #function to calculate card values
    the_count = 0 
    ace_count = 0
    for i in the_hand:
        if (i[0:1] == 'J' or i[0:1] == 'Q' or i[0:1] == 'K' or i[0:1] == 10):
            the_count +=10
        elif (i[0:1] != 'A'):
            the_count += int(cards[0:1])
        else:
            ace_count +=1
    if (ace_count == 1 and the_count <= 10):
         the_count += 11
    elif(ace_count != 0):
         the_count += 1
    return the_count 

print ('Your cards are:' , player_hand) #printing the hands
print ("The dealer's cards are:" , '[' ,'X', ',', dealer_hand[0],  ']') #printing the hands


game = input('What would you like to do? H = HIT ME or S = Stand:  ')   #asking the user to hit or stand

if game == 'Hit': #drawing a card to the player's hand if he hits
    player_hand = random.choices(cards , k=1)
else:
    print('You have:' , card_values(player_hand)) # telling the player's value if he stands

while card_values(dealer_hand) <= 16: #adding a card if the dealer's hand is less than 16
    dealer_hand = random.choices(cards , k=1)
python typeerror blackjack
1个回答
1
投票

虽然 @Michael Guidry 的答案是正确的,但我想在此基础上解决风格问题。

你可以把 card_values 的定义,因为这些还不相关。使用显式的变量名更有利于阅读和理解,所以我用了 for i in the_hand:for card in the_hand:. 现在选择的顺序更容易理解 (if aceelif figureselse others 而不是 数字或10elif not aceelse others). 现在,hitstand的选择被封装在一个while循环中,以在用户没有回答 "H "或 "S "但不支持的东西时,再次提问。

import random # Importing random function.

def card_values(the_hand):
    """This function calculate the values of a given hand."""

    the_count = 0 
    ace_count = 0
    for card in the_hand:
        if card == "A":
            ace_count += 1
        elif card in ("J", "Q", "K"):
            the_count += 10
        else:
            the_count += card
    if ace_count == 1 and the_count <= 10:
        the_count += 11
    elif ace_count != 0:
        the_count += 1
    return the_count 

# This is where the game starts.
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # List for the cards with mixed data types.
player_hand = random.choices(cards, k=2) # Drawing the player's cards (hand).
dealer_hand = random.choices(cards, k=2) # Drawing the dealer's cards (hand).
print('Your cards are:', player_hand) # Printing the hands.
print("The dealer's cards are:", '[' ,'X', ',', dealer_hand[0],  ']') # Printing the hands.   

# Ask the user to hit or stand. Repeat until the input is valid.
while True:
    choice = input('What would you like to do? H = HIT ME or S = Stand:  ')
    if choice in ("H", "S"):
        break
    else:
        print(f'Your choice "{choice}" is not supported, please provide the input again.)'

if choice == "H": # Drawing a card to the player's hand if he hits.
    player_hand = random.choices(cards , k=1)
else:
    print(player_hand)
    print('You have: ', card_values(player_hand)) # Telling the player's value if he stands.

while card_values(dealer_hand) <= 16: # Adding a card if the dealer's hand is less than 16.
    dealer_hand = random.choices(cards , k=1)

0
投票

你的问题很简单。i 你的问题很简单: i 是值。在你解决了这个问题之后,你的下一个错误将是这部分内容 the_count += int(cards[0:1]) 应是 the_count += i.

完整的例子

import random #importing random function
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # list for the cards with mixed data types
player_hand = random.choices(cards, k=2) #Drawing the player's cards(hand)
dealer_hand = random.choices(cards, k=2) #Drawing the dealer's cards(hand)

def card_values(the_hand): #function to calculate card values
    the_count = 0 
    ace_count = 0
    for i in the_hand:
        if i in ('J', 'Q', 'K', 10):
            the_count +=10
        elif (i != 'A'):
            the_count += i
        else:
            ace_count +=1
    if (ace_count == 1 and the_count <= 10):
        the_count += 11
    elif(ace_count != 0):
        the_count += 1
    return the_count 

print ('Your cards are:' , player_hand) #printing the hands
print ("The dealer's cards are:" , '[' ,'X', ',', dealer_hand[0],  ']') #printing the hands


game = input('What would you like to do? H = HIT ME or S = Stand:  ')   #asking the user to hit or stand

if game == 'Hit': #drawing a card to the player's hand if he hits
    player_hand = random.choices(cards , k=1)
else:
    print(player_hand)

    print('You have:' , card_values(player_hand)) # telling the player's value if he stands

while card_values(dealer_hand) <= 16: #adding a card if the dealer's hand is less than 16
    dealer_hand = random.choices(cards , k=1)

编辑

如果我们要进入脚本的风格,那么我们可以完全重新开始。这是一个游戏,所以,你首先需要的自动是一个游戏循环。接下来要做的就是简单地用代码 "玩 "这个游戏。在21点游戏中,庄家和玩家拿到一手牌。在游戏循环中,首先要发生的是庄家和玩家拿到一手牌。这两手牌都已经有了一个值,所以我们立即得到它,并一直保持更新。下一步是玩家选择中牌或站牌。我们只需要知道'中'。'hit'是唯一不是游戏结束的选择。最后,我们只需要比较分数来编造合适的信息,并打印所有的游戏属性。然后我们会问用户是否要再次运行这个循环。除了'n'或'no'之外的任何其他选项都是'yes'......不管我们的小信息是否有'y'的说法。

import random, os

# card references
facecards   = ['Ace', 'Jack', 'Queen', 'King']
numcards    = ['2', '3', '4', '5', '6', '7', '8', '9', '10']
# clears the console on windows
clear       = lambda: os.system('cls')


# calculate hand total
def sum(hand):
    c = 0
    for card in hand:
        if card != 'Ace':
            c += 10 if not card in numcards else int(card)
        else:
            c += 11 if c < 11 else 1
    return c


# create a shuffled deck    
def shuffled_deck(shuffles=3, cuts=2):
    deck     = [*facecards, *numcards] * 4
    shuffles = 3 if shuffles < 1 else shuffles
    cuts     = 2 if cuts < 1 else cuts

    for i in range(shuffles):
        random.shuffle(deck)

    for i in range(cuts):
        n = random.randint(1, len(deck))
        deck = [*deck[n::], *deck[0:n]]

    return deck


# the actual game    
def game_loop():
    playing = True              # we wont be 'playing' if the dealer busts
    deck    = shuffled_deck()   # get a fresh deck

    # you get a hand
    player_hand = [deck.pop(0), deck.pop(1)] # simulate alternating cards
    player      = sum(player_hand)

    #the dealer gets a hand
    dealer_hand = [deck.pop(0), deck.pop(0)] 
    dealer      = sum(dealer_hand)

    #the dealer continues to pick until the hand is worth at least 16
    while dealer < 16:
        dealer_hand.append(deck.pop(0))
        dealer  = sum(dealer_hand)
        playing = dealer <= 21

    # allow the player to keep getting hit as long as the player hasn't busted
    while playing:
        if player < 21:
            clear()
            print(f'\tDealer\ttotal: ??\tcards: X, {", ".join(dealer_hand[1::])}\n')
            print(f'\tPlayer\ttotal: {player}\tcards: {", ".join(player_hand)}\n')

            if input('\tTake a hit? (y)es or (n)o: ').lower() in ('y', 'yes'):
                player_hand.append(deck.pop(0))
                player = sum(player_hand)
                continue
            else:
                break
        else: 
            break

    # end of game        
    clear()    
    if player <= 21:
        if dealer > 21 or dealer <= player:
            print('\tCongratulations! You Are The Big Winner!\n')
        else:
            print('\tUnfortunately, You Lose.\n')
    else:
        print('\tYou Busted! Better Luck Next Time.\n')

    print(f'\tDealer\ttotal: {dealer}\tcards: {", ".join(dealer_hand)}\n')
    print(f'\tPlayer\ttotal: {player}\tcards: {", ".join(player_hand)}\n')

    if not input('\tWould you like to play again? (y)es or (n)o: ').lower() in ('n', 'no'):
        game_loop()
© www.soinside.com 2019 - 2024. All rights reserved.