Как мне остановить этот цикл в Python? - PullRequest
0 голосов
/ 07 октября 2018

Это работает именно так, как я хочу, за исключением того, что я не могу остановить его, когда пользователь вводит недопустимую опцию.Это игра «Рок, бумага, ножницы», которая не только регистрирует вводимые пользователем данные, но и сохраняет счет текущего раунда и сохраняет итоговый счет всех раундов, пока игра не закончится ... что, как сейчас, никогда не происходит.Как мне закончить эту игру, когда пользователь вводит неверную опцию?Я пытался использовать break, но это неверно.

def rock_paper_scissors():
    playerScore = 0
    computerScore = 0

    print("")

    player = input("Choose Rock, Paper, or Scissors: ")
    player = player.lower()

    choices = ["rock", "paper", "scissors"]

    computer = random.choice(choices)


    if player == computer:
        print("I chose " + str(computer) + " and you chose " + player + ". It's a tie!")
    elif player == "rock" and computer == "scissors":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "paper" and computer == "rock":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "scissors" and computer == "paper":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif computer == "rock" and player == "scissors":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "paper" and player == "rock":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "scissors" and player == "paper":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    else:
        print("Sorry, but you entered an invalid option.  The game has ended.  See below for the final score.  Thank you for playing")
        print("")
        print("Your score:", str(playerScore) + ", Computer score:", str(computerScore))

    return playerScore, computerScore

playerFinal = 0
computerFinal = 0

while True:
    player, computer = rock_paper_scissors()
    playerFinal += player
    computerFinal += computer
    print("Your score:", str(playerFinal) + ", Computer score:", computerFinal)

Ответы [ 4 ]

0 голосов
/ 07 октября 2018

Измените условие зацикливания с:

while True:

на:

while True and (player+computer) != 0 :

При неверном выборе пользователя счет за этот раунд будет равен 0, и в следующий раз цикл не будетпройти условие.

0 голосов
/ 07 октября 2018

Просто добавьте break после неверного выбора. Вы можете позволить игроку прокручивать в это время с минус

if player < 0
   playerFinal = -1 * player
   break
0 голосов
/ 07 октября 2018

Эту проблему можно решить, просто добавив флаг, чтобы проверить, нужно ли завершить цикл while True.Здесь:

import random
def rock_paper_scissors():
    playerScore = 0
    computerScore = 0
    flag = False

    print("")

    player = input("Choose Rock, Paper, or Scissors: ")
    player = player.lower()

    choices = ["rock", "paper", "scissors"]

    computer = random.choice(choices)


    if player == computer:
        print("I chose " + str(computer) + " and you chose " + player + ". It's a tie!")
    elif player == "rock" and computer == "scissors":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "paper" and computer == "rock":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "scissors" and computer == "paper":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif computer == "rock" and player == "scissors":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "paper" and player == "rock":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "scissors" and player == "paper":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    else:
        flag = True
        print("Sorry, but you entered an invalid option.  The game has ended.  See below for the final score.  Thank you for playing")
        print("")
        print("Your score:", str(playerScore) + ", Computer score:", str(computerScore))

    return playerScore, computerScore, flag

playerFinal = 0
computerFinal = 0

while True:
    player, computer, flag = rock_paper_scissors()
    playerFinal += player
    computerFinal += computer
    print("Your score:", str(playerFinal) + ", Computer score:", computerFinal)
    if flag:
        break
0 голосов
/ 07 октября 2018

Если возвращенные результаты равны нулю, игрок ввел неправильный ввод, и вы можете разорвать цикл.

while True:
    player, computer = rock_paper_scissors()
    if player == 0 and computer == 0:
        break
    playerFinal += player
    computerFinal += computer
    print("Your score:", str(playerFinal) + ", Computer score:", computerFinal)
...