vendredi 18 octobre 2019

Python - Replaying While Loop Dice Roll Game

I know there should be a super obvious fix here but I've been working on this dice game for too long now and I've confused myself.

How should I get the below loop to replay if the user types in an invalid response after being asked if they want to roll the dice again?

I can't get it to work without messing with the while loop. Here's what I have so far


# Ask the player if they want to play again

another_attempt = input("Roll dice again [y|n]?")

# Loop to allow the player to play again

while another_attempt == 'y':

        import random
        die1 = random.randint(1,6)
        die2 = random.randint(1,6)
        die3 = random.randint(1,6)
        die4 = random.randint(1,6)
        die5 = random.randint(1,6)

        dicescore = 0
        if die1 == 3:
            dicescore += 2
        if die2 == 3:
            dicescore += 2
        if die3 == 3:
            dicescore += 2
        if die4 == 3:
            dicescore += 2
        if die5 == 3:
            dicescore += 2
        if die1 == 5:
            dicescore += 4
        if die2 == 5:
            dicescore += 4
        if die3 == 5:
            dicescore += 4
        if die4 == 5:
            dicescore += 4
        if die5 == 5:
            dicescore += 4

        dice.display_dice(die1, die2, die3, die4, die5)
        roll_guess = int(input("Please enter your guess for the roll: "))
        if roll_guess == dicescore :
            print("Well done! You guessed it!")
            correct += 1
            rounds +=1
            if correct >= 4:
                print("""Congratulations! You have worked out the secret!
Make sure you don't tell anyone!""")
        elif roll_guess % 2 == 0:
            print("No sorry, it's", dicescore, "not", roll_guess)
            incorrect += 1
            rounds +=1
        else:
            print("No sorry, it's ", dicescore, " not ", roll_guess, \
                    ". The score is always even.", sep='')
            incorrect += 1
            rounds +=1
        another_attempt = input('Roll dice again [y|n]? ')

# Say Goodbye if the user no longer wants to play

if another_attempt == 'n':
    print("""Game Summary
===========

You played""", rounds, """games
|--> Number of correct guesses:""", correct, """
|--> Number of incorrect guesses:""", incorrect, """
Thanks for playing!""")
    exit()

#Prompt the user to choose a valid response

else:
    print("Please enter either 'y' or 'n'.")

Aucun commentaire:

Enregistrer un commentaire