Программа циклов на основе пользовательского ввода - PullRequest
0 голосов
/ 09 мая 2019

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

Я мог бы скопировать и вставить код внутри оператора If, если пользователь несколько раз выбирает yes, но это очень неэффективно, и я считаю, что должен быть более простой способ.

import random
selection = ("Rock", "Paper", "Scissors")
user1 = input("Pick Rock, Paper, or Scissors: ").upper()
computer = random.choice(selection)
if (user1 == "ROCK"):
        if (computer == "Paper"):
            print ("The computer selected: " + (computer))
            print ("You lost")
        elif (computer == "Scissors"):
            print ("The computer selected: " + (computer))
            print ("You win")
        elif (computer == "Rock"):
            print ("The computer selected: " + (computer))
            print ("Tie")
        else:
            print ("Uh oh something went wrong. Please try again")
elif (user1 == "PAPER"):
            if (computer == "Scissors"):
                print ("The computer selected: " + (computer))
                print ("You lost")
            elif (computer == "Rock"):
                print ("The computer selected: " + (computer))
                print ("You win")
            elif (computer == "Paper"):
                print ("The computer selected: " + (computer))
                print ("Tie")
            else:
                print ("Uh oh something went wrong. Please try again")
elif (user1 == "SCISSORS"):
        if (computer == "Rock"):
            print ("The computer selected: " + (computer))
            print ("You lost")
        elif (computer == "Paper"):
            print ("The computer selected: " + (computer))
            print ("You win")
        elif (computer == "Scissors"):
            print ("The computer selected: " + (computer))
            print ("Tie")
        else:
                print ("Uh oh something went wrong. Please try again")
else:
            print ("Invalid Selection")
while True:
    # main program
    while True:
        answer = input('Run again? (y/n): ')
        if answer in ('y', 'n'):
            break
        print ('Invalid input.')
    if answer == 'y':
        continue
    else:
        print ('Goodbye')
        break

Мой ожидаемый результат - когда пользователь набирает «y» и попадет в игру, игра начнется снова, но на данный момент, когда пользователь вводит «y», она просто повторяет то же самое: «Хотели бы вы сыграть снова? потому что у меня нет никакого реального кода внутри оператора If, но я не знаю, что мне нужно добавить к нему, чтобы получить желаемый результат.

Ответы [ 3 ]

0 голосов
/ 09 мая 2019

Вы можете определить функцию:

def play_game():
    selection = ("Rock", "Paper", "Scissors")
    user1 = input("Pick Rock, Paper, or Scissors: ").upper()
    computer = random.choice(selection)
    # ...
    # ...
    # ...
    else:
        print ("Invalid Selection")

И вызывать ее в зависимости от пользовательского ввода в цикле, например:

play_game()    
while True:
    answer = input('Run again? (y/n): ')
    if answer.lower() == 'y':
        play_game()
    elif answer.lower() == 'n':
        break
    else:
        print ('Invalid input.')
0 голосов
/ 09 мая 2019

Вы также можете включить цикл while в игровую функцию, если хотите

import random
import time

class RockPaperScissors:

    def __init__(self):
        self.elements = ['rock', 'paper', 'scissors']
        self.valid_inputs = ['1','2','3']

    def win_checker(self, cpu_choice, user_choice):
        if ((user_choice == '2' and cpu_choice == 'rock')
        or (user_choice == '1' and cpu_choice == 'scissors')
        or(user_choice == '3' and cpu_choice == 'paper')):
            print('YOU WON')
        else:
            print('You Lost. Computer chose, ', cpu_choice.upper())

    def input_validator(self, user_input):
        if user_input in self.valid_inputs:
            return True

    def play_again(self):
       if input("Do You Want To Play Again? Y/N?").lower() == 'y':
           return True
       else: return False

    def game(self):
        for option in self.elements:
            print(option)
            time.sleep(1)
        user_guess = input('1: Rock, 2:Paper, 3:Scissors: ')
        if self.input_validator == True:
            cpu_choice = random.choice(self.elements)
            self.win_checker(cpu_choice,user_guess)
        else: print('Invalid Input')

play_again = True
while play_again == True:      
    RockPaperScissors().game()
    play_again = RockPaperScissors().play_again()
0 голосов
/ 09 мая 2019

Когда вы набираете Продолжить, он будет повторять оператор снова и снова

вот решение для вашего кода

import random


while Continue:
    selection = ("Rock", "Paper", "Scissors")
    user1 = input("Pick Rock, Paper, or Scissors: ").upper()
    computer = random.choice(selection)
    if (user1 == "ROCK"):
            if (computer == "Paper"):
                print ("The computer selected: " + (computer))
                print ("You lost")
            elif (computer == "Scissors"):
                print ("The computer selected: " + (computer))
                print ("You win")
            elif (computer == "Rock"):
                print ("The computer selected: " + (computer))
                print ("Tie")
            else:
                print ("Uh oh something went wrong. Please try again")
    elif (user1 == "PAPER"):
                if (computer == "Scissors"):
                    print ("The computer selected: " + (computer))
                    print ("You lost")
                elif (computer == "Rock"):
                    print ("The computer selected: " + (computer))
                    print ("You win")
                elif (computer == "Paper"):
                    print ("The computer selected: " + (computer))
                    print ("Tie")
                else:
                    print ("Uh oh something went wrong. Please try again")
    elif (user1 == "SCISSORS"):
            if (computer == "Rock"):
                print ("The computer selected: " + (computer))
                print ("You lost")
            elif (computer == "Paper"):
                print ("The computer selected: " + (computer))
                print ("You win")
            elif (computer == "Scissors"):
                print ("The computer selected: " + (computer))
                print ("Tie")
            else:
                print ("Uh oh something went wrong. Please try again")
    else:
        print ("Invalid Selection")

    answer = input('Run again? (y/n): ')
    while True:
        if answer in ('y', 'n'):
            print ('Invalid input.')
        if answer == 'y':
            Continue = True
        else:
            print ('Goodbye')
            Continue = False
            break
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...