[英]Can't get while loop to stop my Python program
I'm trying to create a unicorn dice game.我正在尝试创建一个独角兽骰子游戏。 I'm trying to use a while loop to enable the program to stop once the variable loop stop but I cannot get it to work: the loop prints continuously it cannot stop any help?
我正在尝试使用 while 循环来使程序在变量循环停止后停止,但我无法让它工作:循环连续打印它无法停止任何帮助?
import random
PARTS = {1: 'body', 2: 'tail', 3: 'leg', 4: 'head', 5: 'eye', 6: 'mouth', 7: 'wind', 8: 'horn'}
state = []
def throw_dice():
return random.choice(list(PARTS.keys()))
def build_creature(type="unicorn"):
count_till_head = 0
count_till_body = 0
count = 0
all_part_ids = list(PARTS.keys())
while set(all_part_ids) != set(state):
dice_val = throw_dice()
count += 1
if 1 not in state:
count_till_body += 1
if 4 not in state:
count_till_head += 1
print(f"Player rolled a {dice_val} on the dice, that provides the {type}'s part: {PARTS[dice_val]}")
if dice_val in state:
print(f"You already have this part, discarding..")
continue
if dice_val != 1 and 1 not in state:
print(f"You must have the {type}'s body before using any other part! discarding..")
continue
if dice_val in [5, 6, 8] and 4 not in state:
print(f"You must have the {type}'s head before using its {PARTS[dice_val]}! discarding..")
continue
state.append(dice_val)
print(f"Player added the {type}'s {PARTS[dice_val]}")
print("## Summary ##")
print(f"Player successfully assembled the head in {count_till_head} dice rolls.")
print(f"Player successfully assembled the body in {count_till_body} dice rolls.")
print(f"Player has successfully built the {type} in {count} dice rolls.")
if __name__ == "__main__":
build_creature("pegasus")
Be careful with your indentation.小心你的缩进。 You're using
continue
outside of the if
blocks.您在
if
块之外使用continue
。 This means you'll always jump back to the start of the loop before ever appending the current state to you list.这意味着在将当前 state 附加到您的列表之前,您将始终跳回到循环的开始。 Instead try:
而是尝试:
if dice_val in state:
print(f"You already have this part, discarding..")
continue
if dice_val != 1 and 1 not in state:
print(f"You must have the {type}'s body before using any other part! discarding..")
continue
if dice_val in [5, 6, 8] and 4 not in state:
print(f"You must have the {type}'s head before using its {PARTS[dice_val]}! discarding..")
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.