Home > Blockchain >  How to end a loop?
How to end a loop?

Time:01-16

I have created a game of rock, paper scissors, where the user plays vs the computer. Right now it is stuck in an infinite loop and because I'm new to python I don't know how to end the loop. I've added an example below of how I want it to go. Any help would be appreciated! :)

import random

print("Welcome to the game of rock, paper, scissors!")  

newLi = ["Rock", "Paper", "Scissors"]  
numRandom = newLi[random.randint(0, 3)]
user = False 

while not user:
    user = input("Rock, Paper, Scissors? \nAnswer: ") 
    if user == numRandom: 
        print("It's a tie! Please try again.")  
    elif user == "Rock" or user == "rock":
        if numRandom == "Paper":  
            print("Aw! You lost. Try again!", numRandom, "covers", user)
        else :
            print("Good job! You're the winner!", user, "smashes", numRandom)
    elif user == "Paper" or user == "paper":
        if numRandom == "Scissors":
            print("Aw! You lost. Try again!", numRandom, "cuts", user)
        else :
            print("Good job! You're the winner!", user, "covers", numRandom)
    elif user == "Scissors" or user == "scissors":
        if numRandom == "Rock":
            print("Aw! You lost. Try again!", numRandom, "smashes", user)
        else :
            print("Good job! You're the winner!", user, "cuts", numRandom)
    else:
        print("Invalid answer! Try again.")  

endGame = input("Would you like to keep playing? Y or N\nAnswer: ")

if endGame == "Y"
    KEEP PLAYING
else:
    STOP PLAYING

CodePudding user response:

I've added a user input variable rounds_to_play that asks the user how many rounds they would like to play, this variable will decrement per round until the game is done. You could also add a bool is_playing and say while is_playing and then set the bool to be false when the game is over.

import random

print("Welcome to the game of rock, paper, scissors!")

new_lst = ["Rock", "Paper", "Scissors"]
num_random = new_lst[random.randint(0, 3)]
rounds_to_play = int(input("How many rounds would you like to play: "))

while rounds_to_play > 0:
    user_input = input("Rock, Paper, Scissors? \nAnswer: ")
    if user_input == num_random:
        print("It's a tie! Please try again.")
    elif user_input == "Rock" or user_input == "rock":
        if num_random == "Paper":
            print("Aw! You lost. Try again!", num_random, "covers", user_input)
        else:
            print("Good job! You're the winner!",
                  user_input, "smashes", num_random)
    elif user_input == "Paper" or user_input == "paper":
        if num_random == "Scissors":
            print("Aw! You lost. Try again!", num_random, "cuts", user_input)
        else:
            print("Good job! You're the winner!",
                  user_input, "covers", num_random)
    elif user_input == "Scissors" or user_input == "scissors":
        if num_random == "Rock":
            print("Aw! You lost. Try again!",
                  num_random, "smashes", user_input)
        else:
            print("Good job! You're the winner!",
                  user_input, "cuts", num_random)
    else:
        print("Invalid answer! Try again.")
        rounds_to_play  = 1

    rounds_to_play -= 1

CodePudding user response:

First you will have to get endgame and if else loop inside the while loop. Then you could use a flag variable to start and stop your while loop

import random

print("Welcome to the game of rock, paper, scissors!")

newLi = ["Rock", "Paper", "Scissors"]
numRandom = newLi[random.randint(0, 3)]
flag = True
while flag:
    user = input("Rock, Paper, Scissors? \nAnswer: ")
    if user == numRandom:
        print("It's a tie! Please try again.")
    elif user == "Rock" or user == "rock":
        if numRandom == "Paper":
            print("Aw! You lost. Try again!", numRandom, "covers", user)
        else :
            print("Good job! You're the winner!", user, "smashes", numRandom)
    elif user == "Paper" or user == "paper":
        if numRandom == "Scissors":
            print("Aw! You lost. Try again!", numRandom, "cuts", user)
        else :
            print("Good job! You're the winner!", user, "covers", numRandom)
    elif user == "Scissors" or user == "scissors":
        if numRandom == "Rock":
            print("Aw! You lost. Try again!", numRandom, "smashes", user)
        else :
            print("Good job! You're the winner!", user, "cuts", numRandom)
    else:
        print("Invalid answer! Try again.")

    endGame = input("Would you like to keep playing? Y or N\nAnswer: ")

    if endGame == "Y":
        flag =True
    else:
        flag = False

CodePudding user response:

Based on your question, I concluded that you want to create a rock-paper-scissor "game" in python that will keep going as long as the endGame = 'Y', so defining the user = False on top of your code is not necessary.

You need to define the endGame to be 'Y' at first instead. No need to add any additional flag as well.

For the clarity, I change the variable endGame to continueGame.

Therefore, this should be the algorithm/mechanism of the game in steps:

  1. Define the rock, paper and scissors

  2. Get user's choice

  3. Pick one randomly among rock, paper and scissors.

  4. Print the response

  5. Ask the user whether they want to continue the game:

    • If Y, get back to step 2.
    • If N, end the runtime.

Thus, you need to count the random inside the loop. Otherwise, the result would always be the same every time the user wants to play the game again and again.

You can sanitize the case to make it easier for checking, i.e. using .lower() to lowercase the user input.

import random

print("Welcome to the game of rock, paper, scissors!")

newLi = ["rock", "paper", "scissors"]
continueGame = 'Y'

while continueGame = 'Y':
    user = input("Rock, Paper, Scissors? \nAnswer: ")
    numRandom = newLi[random.randint(0,3)]
    if user.lower() == numRandom:
        print("It's a tie! Please try again.")
    elif user.lower() == "rock":
        if numRandom == "Paper":
            print("Aw! You lost. Try again!", numRandom, "covers", user)
        else :
            print("Good job! You're the winner!", user, "smashes", numRandom)
    elif user.lower() == "paper":
        if numRandom == "Scissors":
            print("Aw! You lost. Try again!", numRandom, "cuts", user)
        else :
            print("Good job! You're the winner!", user, "covers", numRandom)
    elif user.lower() == "scissors":
        if numRandom == "Rock":
            print("Aw! You lost. Try again!", numRandom, "smashes", user)
        else :
            print("Good job! You're the winner!", user, "cuts", numRandom)
    else:
        print("Invalid answer! Try again.")

    continueGame = input("Would you like to keep playing? Y or N\nAnswer: ")

CodePudding user response:

You are stuck in a loop because Python considers code block based on indentation. In you code

import random

print("Welcome to the game of rock, paper, scissors!")  

newLi = ["Rock", "Paper", "Scissors"]  
numRandom = newLi[random.randint(0, 3)]
user = False 

while not user:
    user = input("Rock, Paper, Scissors? \nAnswer: ") 
    if user == numRandom: 
        print("It's a tie! Please try again.")  
    ...  

endGame = input("Would you like to keep playing? Y or N\nAnswer: ")

if endGame == "Y"
    KEEP PLAYING
else:
    STOP PLAYING

If you notice, endGame = ..., if endGame, and your else statements are all on the same level of indentation as your initial while loop. This means they are not actually a part of your loop, but instead would execute only after the loop has been closed.

Step 1, is to indent all of that to be included inside of the code block.

Step 2 is to switch KEEP PLAYING with continue and STOP PLAYING with break.

If you're doing that, you can just change your while loop to be while True

Here is a good link for flow controls of loops.


Not related to question, but since we're here to help, you're going to run into some comparison issues if you allow a user to type a capitalized or lowercase answer.

Look into .lower() and consider using lowercase for everything in this scenario.


End code should look like:

import random

print("Welcome to the game of rock, paper, scissors!")  

newLi = ["Rock", "Paper", "Scissors"]  
numRandom = newLi[random.randint(0, 3)]
user = False 

while True:
    user = input("Rock, Paper, Scissors? \nAnswer: ") 
    if user == numRandom: 
        print("It's a tie! Please try again.")  
    elif user == "Rock" or user == "rock":
        if numRandom == "Paper":  
            print("Aw! You lost. Try again!", numRandom, "covers", user)
        else :
            print("Good job! You're the winner!", user, "smashes", numRandom)
    elif user == "Paper" or user == "paper":
        if numRandom == "Scissors":
            print("Aw! You lost. Try again!", numRandom, "cuts", user)
        else :
            print("Good job! You're the winner!", user, "covers", numRandom)
    elif user == "Scissors" or user == "scissors":
        if numRandom == "Rock":
            print("Aw! You lost. Try again!", numRandom, "smashes", user)
        else :
            print("Good job! You're the winner!", user, "cuts", numRandom)
    else:
        print("Invalid answer! Try again.")  

    endGame = input("Would you like to keep playing? Y or N\nAnswer: ")

    if endGame == "Y"
        continue
    else:
        break

CodePudding user response:

Added an extra flag 'loop' which will end the loop when user says 'N' to continue. If user says 'Y' to continue it will set user to False to get into other while loop.

import random

print("Welcome to the game of rock, paper, scissors!")  

newLi = ["Rock", "Paper", "Scissors"]  
numRandom = newLi[random.randint(0, 3)]
user = False 
loop = True

while(loop):
    while not user:
        user = input("Rock, Paper, Scissors? \nAnswer: ") 
        if user == numRandom: 
            print("It's a tie! Please try again.")  
        elif user == "Rock" or user == "rock":
            if numRandom == "Paper":  
                print("Aw! You lost. Try again!", numRandom, "covers", user)
            else :
                print("Good job! You're the winner!", user, "smashes", numRandom)
        elif user == "Paper" or user == "paper":
            if numRandom == "Scissors":
                print("Aw! You lost. Try again!", numRandom, "cuts", user)
            else :
                print("Good job! You're the winner!", user, "covers", numRandom)
        elif user == "Scissors" or user == "scissors":
            if numRandom == "Rock":
                print("Aw! You lost. Try again!", numRandom, "smashes", user)
            else :
                print("Good job! You're the winner!", user, "cuts", numRandom)
        else:
            print("Invalid answer! Try again.")  

    endGame = input("Would you like to keep playing? Y or N\nAnswer: ")

    if endGame == "N":
        loop=False
    else:
        user=False

CodePudding user response:

You initialize user to False, but user is never later set to True. Thus, the condition of the while statement, which is not user, always evaluates to True. This causes an infinite loop, as a while loop executes code as long as a test condition is True.

Depending on how the game is structured (best-of-three format, one-game format, etc.), you should change your terminating condition. You could, for example, increment a counter (num_games) and end the loop once that counter reaches some fixed value.

Alternatively, you can use break or return statements. The break statement will terminate your while loop. return will terminate the method (and will consequently also terminate your while loop).

  •  Tags:  
  • Related