#python #blackjack
Вопрос:
Я пытался сыграть в блэкджек, и когда я, когда я ввожу H или D для ввода выбора, консоль не допускает никаких моих входов, кроме Ctrl C для вывода 1, и это приводит к ошибке, показанной в выводе 2, когда я ввожу S для ввода выбора
Мой код
from random import choice, shuffle
plain_cards = ['2','3','4','5','6','7','8','9','J', 'K', 'Q', 'A']
HEARTS = chr(9829)
DIAMONDS = chr(9830)
SPADES = chr(9824)
CLUBS = chr(9827)
suits = [HEARTS,DIAMONDS,SPADES,CLUBS]
def get_deck():
deck = [(suit, card) for suit in suits for card in plain_cards]
shuffle(deck)
return deck
def get_cards_value(cards):
total = 0
aces = []
for card in cards:
if card[1].isdigit():
total = int(card[1])
if card[1] == 'K' or card[1] == 'J' or card[1] == 'Q':
total = 10
if card[1] == 'A' :
total = 11
aces.append('A')
for i in aces:
if total > 21:
total -= 10
return total
def game():
print('Welcome to BLACK JACK')
money = 1000
playing = True
game_on = True
while playing:
if money <= 0:
playing = False
print('Thanks for playing but your money is done come back soon')
else:
bet = input('Stake: ')
if not bet.isdigit():
print('Invalid input')
continue
elif int(bet) > money:
print('You don't have enough money')
continue
else:
bet = int(bet)
deck = get_deck()
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
print('Player hand')
print(f'{player_hand} total:{get_cards_value(player_hand)}')
print('Dealer Hand')
print(f'[{dealer_hand[0]}, ###]')
player_total = get_cards_value(player_hand)
dealer_total = get_cards_value(dealer_hand)
while game_on:
if player_total > 21 or dealer_total > 21:
break
choice = input('(S)tand, (D)ouble, (H)it: ')
if choice == 'D':
bet *= 2
money = bet
if choice == 'D' or choice == 'H':
new_card = deck.pop()
player_hand.append(new_card)
break
if choice == 'S':
break
if player_total < 21:
while dealer_total < 17:
new_card = deck.pop()
dealer_hand.append(new_card)
if player_total == 21:
print('You won')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money = bet
elif dealer_total == 21:
print('You lost')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money -= bet
elif player_total > dealer_total:
print('You lost')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money -= bet
elif player_total < dealer_total:
print('You win')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money = bet
game()
Это вывод,когда я ввожу S, H или D
Обратная связь (последний последний звонок):
File "C:/Users/Godfrey Baguma/AppData/Local/Programs/Python/Python39/ssdd.py", line 109, in <module>
game()
File "C:/Users/Godfrey Baguma/AppData/Local/Programs/Python/Python39/ssdd.py", line 82, in game
new_card = deck.pop()
IndexError: pop from empty list
Ответ №1:
Ответ содержится в выводе ошибок там. В частности, в этом блоке:
if player_total < 21:
while dealer_total < 17:
new_card
dealer_hand.append(new_card)
Вы не установили значение new_card (вы хотели сделать его new_card = deck.pop()?), поэтому интерпретатор понятия не имеет, что с ним делать, и выдает ошибки.
Ответ №2:
Ошибка говорит о том, что вы хотите получить доступ к переменной, которая еще не известна. В вашем коде есть ошибка (строка 82 или 83). Поток программы может происходить таким образом, который dealer_hand.append(new_card)
называется, но new_card
еще не известен.
Ответ №3:
Существует бесконечный цикл:
while dealer_total < 17:
new_card = deck.pop()
dealer_hand.append(new_card)
dealer_total
не обновляется, поэтому deck
у игрока заканчиваются карты и он их выбрасывает IndexError
.