【发布时间】:2020-07-05 18:00:56
【问题描述】:
此代码应生成二十一点手,记分,并计算软 A 的数量。它应该根据游戏类型停止或继续。代码排列不正确,并保持“总”值和/或“手”为空,从而产生无限的 while 循环。如何安排代码以使其返回所需的结果?
import random
def get_card():
#hand = []
card = random.randint(1, 13)
if card == 10 or card == 11 or card == 12 or card == 13:
card = 10
#hand.append(card)
#return hand
return card
def score():
"""
keeps score of the hand and counts saft aces.
"""
hand = []
card = get_card()
#hand = [get_card()]
game_type = input("Enter 'soft'for S17 ot 'hard for H17'.")
total = 0
soft_ace_count = 0
for ele in range(0, len(hand)):
total = total + hand[ele]
while len(hand) <= 5:
while total <= 17 and game_type == 'soft':
if card == 1:
card = 11
hand.append(card)
while total <= 17 and game_type == 'hard':
if card == 1:
hand.append(card)
if ele in hand == 11:
soft_ace_count += 1
return(total, soft_ace_count)
我还想对程序进行模块化,并根据一些用户定义的模拟计算破坏的概率。我不知道如何设置模拟循环以临时保存模拟结果以计算概率。我应该把它们放在一个临时文件中吗?
def main():
try:
num_simulations = int(input("Please enter the desired number of simulations: "))
except ValueError:
print("Please enter an integer value for the nummer of simulations.")
try:
stand_on_value = int(input("Please enter a score value to stand on. "))
except ValueError:
print("Please enter an integer value for the stand-on score.")
try:
game_type = input("Enter 'soft' for S17 or 'hard' for H17.")
except ValueError:
if game_type != 'soft' or game_type != 'hard':
print("Please enter 'soft' or 'hard'.")
for i in range(0, num_simulations):
get_card()
score()
"for-loop to calculate probability of busting as the percentage of busted hands in the simulations."```
【问题讨论】:
-
我认为你可以在你问用户的问题上做得更好......
标签: python while-loop infinite-loop