TypeError: ‚int‘ object is not subscriptable in blackjack game using random.choices
TypeError: ‚int‘ object is not subscriptable in blackjack game using random.choices
我得到一个 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)
您的问题很简单: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)
编辑
如果我们要进入脚本风格,那么我们可以完全重新开始。这是一款游戏,因此您首先需要的自然是游戏循环。接下来要做的就是 'play' 代码游戏。在二十一点中,庄家和玩家各执一词。游戏循环中发生的第一件事是庄家和玩家拿到牌。这两只手都已经有了一个值,所以我们立即获取它并一直保持更新。下一步是玩家选择被击中或站立。我们只需要知道'hit'。 '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()
虽然@Michael Guidry 的回答是正确的,但我想以此为基础来解决样式问题。
您可以将 card_values
定义放在顶部的牌和手牌之前,因为它们还不相关。使用显式变量名更利于阅读和理解,因此我将 for i in the_hand:
替换为 for card in the_hand:
。这些选项现在按照更容易理解的顺序排序(if ace/elif figures/else others 而不是 if figures or 10/elif not ace/else其他)。 hit/stand 选项现在包含在一个 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)
我得到一个 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)
您的问题很简单: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)
编辑
如果我们要进入脚本风格,那么我们可以完全重新开始。这是一款游戏,因此您首先需要的自然是游戏循环。接下来要做的就是 'play' 代码游戏。在二十一点中,庄家和玩家各执一词。游戏循环中发生的第一件事是庄家和玩家拿到牌。这两只手都已经有了一个值,所以我们立即获取它并一直保持更新。下一步是玩家选择被击中或站立。我们只需要知道'hit'。 '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()
虽然@Michael Guidry 的回答是正确的,但我想以此为基础来解决样式问题。
您可以将 card_values
定义放在顶部的牌和手牌之前,因为它们还不相关。使用显式变量名更利于阅读和理解,因此我将 for i in the_hand:
替换为 for card in the_hand:
。这些选项现在按照更容易理解的顺序排序(if ace/elif figures/else others 而不是 if figures or 10/elif not ace/else其他)。 hit/stand 选项现在包含在一个 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)