0

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?

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")

1 Answer 1

1

Be careful with your indentation. You're using continue outside of the if blocks. This means you'll always jump back to the start of the loop before ever appending the current state to you list. 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
Sign up to request clarification or add additional context in comments.

1 Comment

A chain of elifs would be more appropriate to skip the next if when a previous one triggered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.