Я выполняю простое обучающее упражнение по созданию игры в блэкджек из командной строки. Большую часть времени кажется, что почти все работает. У меня есть странная ошибка, которую я пока не смог выяснить. В функции FinalCheck после того, как она выдаст ответ о том, кто выиграл (в большом блоке if/elif), она повторит строку print(f"Final Score (...)"), и comp_score будет рассчитана только с использованием первых двух чисел в списке, а затем она попытается снова оценить операторы if в FinalCheck.
import random
card_deck = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# boolean starter key
start = input("Would you like to play blackjack? Y or N ")
player_deck = []
comp_deck = []
ace11 = 11
game_over = False
def PlayAgain():
global player_deck
global comp_deck
global game_over
new_game = input("Would you like to play again? Y or N ")
if new_game.lower() == "y":
player_deck = []
comp_deck = []
game_over = False
NewRound()
elif new_game.lower() == "n":
print("Well there you go. ")
else:
return
def NewRound():
# dealer delivers the first round of cards to the player and dealer
global game_over
global player_deck
print("New Round: Here are your cards. ")
FirstDeal()
Check()
while game_over == False:
if player_deck[0] == player_deck[1]:
HSS()
else:
HS()
PlayAgain()
# Hit or Stand (HS)
def HS():
choice = input("Enter H for hit, or S for stand. ").lower()
if choice == "h":
Hit()
elif choice == "s":
Stand()
else:
print("Sorry, I didn't catch that. Try again. ")
HS()
# Hit, Stand, or Split (HSS)
def HSS():
choice = input("Enter H for hit, T for split, or S for stand. ").lower()
if choice == "h":
Hit()
elif choice == "s":
Stand()
elif choice == "t":
Split()
else:
print("Sorry, I didn't catch that. Try again. ")
HSS()
def FirstDeal():
global player_deck
global comp_deck
# rand num of set of cards for each player
player_deck.append(random.choice(card_deck))
player_deck.append(random.choice(card_deck))
p1 = int(player_deck[0])
p2 = int(player_deck[1])
comp_deck.append(random.choice(card_deck))
comp_deck.append(random.choice(card_deck))
c1 = int(comp_deck[0])
c2 = int(comp_deck[1])
print(f"Player's cards are {p1} and {p2}. ")
print(f"The sum of your cards is {p1+p2}. ")
print(f"Computer's first card is {c1}. ")
def Check():
# computer checks the status of the table and the game, and moves accordingly
global player_deck
global comp_deck
global ace11
global game_over
player_score = sum(player_deck)
comp_score = sum(comp_deck)
print(f"Your score is {player_score}. ")
if player_score > 21:
if ace11 in player_deck:
player_deck[player_deck.index(11)] = 1
print("Your ace is now a 1 instead of 11. You got another chance. ")
Check()
else:
print("Game over. You passed 21. Dealer wins. ")
game_over = True
elif player_score == 21:
if comp_score == 21:
print("Check Draw. ")
game_over = True
else:
print("Blackjack! You won with 21! ")
game_over = True
else:
print("Good luck, human. ")
def FinalCheck():
# end game check
global player_deck
global comp_deck
global game_over
player_score = sum(player_deck)
comp_score = sum(comp_deck)
print("Entered FinalCheck. ")
Check()
if comp_score < 16:
comp_deck.append(random.choice(card_deck))
print("Computer took another card. ")
FinalCheck()
else:
print("Let's see the cards. ")
print(f"Final Scores: Player score is {player_score}. Dealer score is {comp_score}. ")
if comp_score > 21:
if 11 in comp_deck:
comp_deck[comp_deck.index(11)] = 1
print("Dealer had an Ace. It's been turned to 1. Let's check again. ")
FinalCheck()
else:
print("Player wins by default. ")
game_over = True
elif comp_score > player_score:
print("The house always wins. ")
game_over = True
elif comp_score == player_score:
print("FinalCheck Draw. ")
game_over = True
elif comp_score < player_score:
print("Player wins with a greater score. ")
game_over = True
else:
print("Something went wrong here in FinalCheck. ")
def Hit():
global player_deck
player_deck.append(random.choice(card_deck))
Check()
def Stand():
FinalCheck()
def Split():
print("Banana split. ")
NewRound()
Подробнее здесь: https://stackoverflow.com/questions/798 ... the-values
Как эта часть функции снова выполняется и изменяется значения? [закрыто] ⇐ Python
Программы на Python
1767268174
Anonymous
Я выполняю простое обучающее упражнение по созданию игры в блэкджек из командной строки. Большую часть времени кажется, что почти все работает. У меня есть странная ошибка, которую я пока не смог выяснить. В функции FinalCheck после того, как она выдаст ответ о том, кто выиграл (в большом блоке if/elif), она повторит строку print(f"Final Score (...)"), и comp_score будет рассчитана только с использованием первых двух чисел в списке, а затем она попытается снова оценить операторы if в FinalCheck.
import random
card_deck = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# boolean starter key
start = input("Would you like to play blackjack? Y or N ")
player_deck = []
comp_deck = []
ace11 = 11
game_over = False
def PlayAgain():
global player_deck
global comp_deck
global game_over
new_game = input("Would you like to play again? Y or N ")
if new_game.lower() == "y":
player_deck = []
comp_deck = []
game_over = False
NewRound()
elif new_game.lower() == "n":
print("Well there you go. ")
else:
return
def NewRound():
# dealer delivers the first round of cards to the player and dealer
global game_over
global player_deck
print("New Round: Here are your cards. ")
FirstDeal()
Check()
while game_over == False:
if player_deck[0] == player_deck[1]:
HSS()
else:
HS()
PlayAgain()
# Hit or Stand (HS)
def HS():
choice = input("Enter H for hit, or S for stand. ").lower()
if choice == "h":
Hit()
elif choice == "s":
Stand()
else:
print("Sorry, I didn't catch that. Try again. ")
HS()
# Hit, Stand, or Split (HSS)
def HSS():
choice = input("Enter H for hit, T for split, or S for stand. ").lower()
if choice == "h":
Hit()
elif choice == "s":
Stand()
elif choice == "t":
Split()
else:
print("Sorry, I didn't catch that. Try again. ")
HSS()
def FirstDeal():
global player_deck
global comp_deck
# rand num of set of cards for each player
player_deck.append(random.choice(card_deck))
player_deck.append(random.choice(card_deck))
p1 = int(player_deck[0])
p2 = int(player_deck[1])
comp_deck.append(random.choice(card_deck))
comp_deck.append(random.choice(card_deck))
c1 = int(comp_deck[0])
c2 = int(comp_deck[1])
print(f"Player's cards are {p1} and {p2}. ")
print(f"The sum of your cards is {p1+p2}. ")
print(f"Computer's first card is {c1}. ")
def Check():
# computer checks the status of the table and the game, and moves accordingly
global player_deck
global comp_deck
global ace11
global game_over
player_score = sum(player_deck)
comp_score = sum(comp_deck)
print(f"Your score is {player_score}. ")
if player_score > 21:
if ace11 in player_deck:
player_deck[player_deck.index(11)] = 1
print("Your ace is now a 1 instead of 11. You got another chance. ")
Check()
else:
print("Game over. You passed 21. Dealer wins. ")
game_over = True
elif player_score == 21:
if comp_score == 21:
print("Check Draw. ")
game_over = True
else:
print("Blackjack! You won with 21! ")
game_over = True
else:
print("Good luck, human. ")
def FinalCheck():
# end game check
global player_deck
global comp_deck
global game_over
player_score = sum(player_deck)
comp_score = sum(comp_deck)
print("Entered FinalCheck. ")
Check()
if comp_score < 16:
comp_deck.append(random.choice(card_deck))
print("Computer took another card. ")
FinalCheck()
else:
print("Let's see the cards. ")
print(f"Final Scores: Player score is {player_score}. Dealer score is {comp_score}. ")
if comp_score > 21:
if 11 in comp_deck:
comp_deck[comp_deck.index(11)] = 1
print("Dealer had an Ace. It's been turned to 1. Let's check again. ")
FinalCheck()
else:
print("Player wins by default. ")
game_over = True
elif comp_score > player_score:
print("The house always wins. ")
game_over = True
elif comp_score == player_score:
print("FinalCheck Draw. ")
game_over = True
elif comp_score < player_score:
print("Player wins with a greater score. ")
game_over = True
else:
print("Something went wrong here in FinalCheck. ")
def Hit():
global player_deck
player_deck.append(random.choice(card_deck))
Check()
def Stand():
FinalCheck()
def Split():
print("Banana split. ")
NewRound()
Подробнее здесь: [url]https://stackoverflow.com/questions/79858020/how-is-this-running-part-of-the-function-again-and-changing-the-values[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия