Как вы очищаете вводимые пользователем данные? - PullRequest
0 голосов
/ 18 апреля 2019

Итак, я создаю торговую систему на Монополии, используя числа.Например, если я хочу что-то добавить, я ввожу число 1, если я хочу что-то удалить, я ввожу число 2 и т. Д. Моя проблема заключается в том, что, если я выхожу из цикла while, в основном код «break»,предыдущий ввод для прерывания также активирует команды if главного меню.Если вы запутались в том, что я пытаюсь сказать, я не знаю, могу ли я публиковать ссылки на этом сайте, но ссылка: https://repl.it/@BrentTersol/Monopoly-Official

if Action == 2 :
      while True:
        replit.clear()
        print("What would you like to give?\n1: Add\n2: Remove\n3: Clear\n4: Offer Trade\n5: Cancel\n6: Switch")
        Action = int(input(">>> "))
        if Action == 1:
          while True:
            replit.clear()
            print("What would you like to add?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
            Action = int(input(">>> "))
            if Action == 1:
              if Turn == 1:
                while True:
                  replit.clear()
                  print("How much money do you want to give for the trade?\nMoney:",str(Player1Money))
                  Action = int(input(">>> "))
                  if Action >= 0 and Action <= (Player1Money):
                    TMoney1 = (Action)
                    print("You added $"+str(TMoney1),"to the trade")
                    time.sleep(2)
                    break
                  else:
                    print("You do not have enough money")
                    break
              if Turn == 2:
                while True:
                  replit.clear()
                  print("How much money do you want to give for the trade?\nMoney:",str(Player2Money))
                  Action = int(input(">>> "))
                  if Action >= 0 and Action <= (Player2Money):
                    TMoney2 = (Action)
                    print("You added $"+str(TMoney2),"to the trade")
                    time.sleep(2)
                    break
                  if Action == "back":
                    break
                  else:
                    print("You do not have enough money")
                    break
            if Action == 2:
              while True:
                replit.clear()
                if Turn == 1:
                  print(Inventory1)
                if Turn == 2:
                  print(Inventory2)
                print("What property do you want to give?")
                Action = int(input(">>> "))
                if Turn == 1:
                  if (Action) in (Inventory1):
                    TProperty1.append((Action))
                    print("Added",(Action),"to the trade")
                    time.sleep(2)
                    break
                  else:
                    print("Item not found in your properties")
                    time.sleep(2)
                    break
                if Turn == 2:
                  if (Action) in (Inventory2):
                    TProperty2 = (Action)
                    print("Added",(Action),"to the trade")
                    time.sleep(2)
                    break
                  else:
                    print("Item not found in your properties")
                    time.sleep(2)
                    break
            if Action == 3:
              if Turn == 1:
                if JailCard1 == 1:
                  TCard1 = 1
                  print("Added Jail Free Card to the trade.")
                  time.sleep(2)
                else:
                  print("You do not own a Jail Free Card")
                  time.sleep(2)
              if Turn == 2:
                if JailCard2 == 1:
                  TCard1 = 1
                  print("Added Jail Free Card to the trade.")
                  time.sleep(2)
                else:
                  print("You do not own a Jail Free Card")
                  time.sleep(2)
            if Action == 4:
              break
        if Action == 2:
          while True:
            replit.clear()
            print("What would you like to remove?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
            Action = int(input(">>> "))
            if Action == 1:
              while True:
                replit.clear()
                if Turn == 1:
                  if TMoney1 == 0:
                    print("There wasn't any money to remove")
                    time.sleep(2)
                  else:
                    TMoney1 = 0
                    print("Removed Cash from offer")
                    time.sleep(2)
                    break
            if Action == 2:
              while True:
                replit.clear()
                print(TProperty1)
                print("What property would you like to remove")
                Action = input(">>> ")
                Action = Action.lower()
                if Turn == 1:
                  if Action == "back":
                    break
                  if (Action) in (TProperty1):
                    TProperty1.remove((Action))
                    print("Removed",(TProperty1),"from trade")
                    time.sleep(2)
                    break
                  else:
                    print("That item did not exist")
                    time.sleep(2)
                if Turn == 2:
                  if (Action) in (TProperty2):
                    TProperty2.remove((Action))
                    print("Removed",(TProperty2),"from trade")
                    time.sleep(2)
                  else:
                    print("That item did not exist")
                    time.sleep(2)
            if Action == 3:
              if Turn == 1:
                if JailCard1 == 1:
                  print("Removed Jail Free Card from trade")
                  TCard1 = 0
                  break
                else:
                  print("Card does not exist in trade")
              if Turn == 2:
                if JailCard2 == 1:
                  print("Removed Jail Free Card from trade")
                  TCard2 = 0
                  break
                else:
                  print("Card does not exist in trade")
            if Action == 4:
              break
        if Action == 3:
          TMoney1 = 0
          TMoney2 = 0
          TProperty1.clear()
          TProperty2.clear()
          TCard1 = 0
          TCard2 = 0
        if Action == 4:
          if Turn == 1:
            while True:
              print("This is what",(Name1),"offers:\n--------------------")
              time.sleep(2)
              print("You get:\nMoney:",(TMoney1),"\nProperty:",(TProperty1),"\nGet out of Jail Free Card:",(TCard1),"\n")
              time.sleep(2)
              print("You give",(Name1)+":\nMoney:",(TMoney2),"\nProperty:",(TProperty2),"\nGet out of Jail Free Card:",(TCard2),"\n")
              time.sleep(2)
              print("Do you accept this Offer? (Y/N):")
              Action = input(">>> ")
              Action = Action.lower()
              if Action == "y":
                print("This is beyond what I can do at this point. Very sorry you took a long time not knowing that it wouldnt work. But this will soon be fixed as soon as I know how to do this")
                time.sleep(5)
              else:
                print("Trade has been rejected")
                time.sleep(2)
                break
        if Action == 5:
          if Turn == 1:
            Turn = 2
          else:
            Turn = 1
        if Action == 6:
          print("This is beyond what I can do. Please wait until I learn how to do this. Thank you.")

1 Ответ

0 голосов
/ 18 апреля 2019

Вы должны реализовать один цикл While True, и он будет сбрасывать пользовательский ввод каждого цикла (если вы перезаписываете его внутри цикла)! Я бы также посоветовал вам воссоздать ваш код в функции вместо нескольких вложенных логических операторов. Пример кода, который получает пользовательский ввод в каждом цикле (в терминах вашего вопроса очищает пользовательский ввод ):

while True:
    big_prompt = """What would you like to do?
    1) say hi
    2) say bye
    3) pay taxes
    4) ???
    5) profit
    6) Exit D:"""
    action = input(big_prompt) # reset user input each loop
    if action not in ["1", "2", "3", "4", "5", "6"]:
        print("Sorry I didn't understand that")
        continue # get a new user input
    # at this point we know user input fits our criteria
    if action == "1":
        print("Hi!")
    elif action == "2":
        print("Bye!")
    # ... you should be putting function calls in these for more complex tasks
    elif action == "6":
        break # this only exits one loop, I think you are trying to use it to 

С выходом образца:

What would you like to do?
    1) say hi
    2) say bye
    3) pay taxes
    4) ???
    5) profit
    6) Exit D:
    >>>1
Hi!
What would you like to do?
    1) say hi
    2) say bye
    3) pay taxes
    4) ???
    5) profit
    6) Exit D:
    >>>6

Process finished with exit code 0

Также было бы неплохо рассмотреть Zen of Python , открыв интерактивный терминал и запустив import this:

>>>import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Где особое примечание мы находим пару вещей, которые применимы здесь:

Квартира лучше вложенной.

Читаемость имеет значение.

Поддержание одного цикла while очень помогает обоим. В какой-то момент в вашем коде вы попадаете в циклы 3 while True:, а затем пытаетесь разбить несколько с помощью одного break, но всегда останетесь в ловушке как минимум на 2 уровня глубиной ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...