Как закончить этот цикл while, чтобы он продолжал повторяться, пока я не получу ошибку индексации списка - PullRequest
0 голосов
/ 26 марта 2019

Я получил код, который должен разделить список карт, а затем сравнить атрибуты карт и затем перемещать карты между ними, пока на компьютере или у пользователя не будет 0 карт.Вот где я борюсь, так как цикл while не прервется и произойдет ошибка индексации списка.Извините, я новичок.Я буду рад ответить на любые вопросы, код здесь: (Извините, это довольно долго.) Заранее спасибо.

Я пытался вернуть значения и использовать 'break', но ни один из них не работал.

Изменить: Обнаружил проблему благодаря Engineero и благодаря Джону Гордану!Теперь это работает!

def comparison(user_deck, comp_deck, x, num_of_cards, cards):

    while len(user_deck) -1 != 0 or len(comp_deck) -1 != 0 :   
      user_points = 0
      comp_points = 0
      x =  random.randint(-1,len(user_deck)-1)
      y =  random.randint(-1,len(comp_deck)-1)

      if x < num_of_cards:
        print(user_deck[x].name)
        print(user_deck[x].exercise, "- Exercise Levels")
        print(user_deck[x].intelligence, "- Intelligence Levels")
        print(user_deck[x].friendliness, "- Friendliness Levels")
        print(user_deck[x].drool, "- Drool Levels")
      class_comparision = input("Which class do you want to compare with?\n")
      ##continued for each attribute
      if class_comparision == "Exercise" or class_comparision == "exercise":
        print(comp_deck[y].name, "\nThis is the computer's card\n")
        print(comp_deck[y].exercise, "- Exercise Levels")
        print(comp_deck[y].friendliness, "- Friendliness Levels")
        print(comp_deck[y].intelligence, "- Intelligence Levels")
        print(comp_deck[y].drool, "- Drool Levels")
        if user_deck[x].exercise >= comp_deck[y].exercise:
          print("You have a higher exercise level!")
          user_points = user_points + 1
          user_deck.append(comp_deck[y])
          del comp_deck[y]
          print(len(user_deck), " This is how many cards you have!")
          print(len(comp_deck), " This is how many cards they have!\n")
        elif user_deck[x].exercise < comp_deck[y].exercise:
          print("You have a lower exercise level!")
          comp_points = comp_points + 1
          comp_deck.append(user_deck[x])
          del user_deck[x]
          print(len(user_deck), " This is how many cards you have!")
          print(len(comp_deck), " This is how many cards they have!\n")
       ##Until here

      elif len(user_deck) == 0 or len(comp_deck) == 0 :
        break
      else:
        print("Try again")
        comparison()   
    return(user_deck, comp_deck, num_of_cards, cards)
    endgame()

Вот ошибка и процесс, который я прошел:

Oliver

3 - Exercise Levels
78 - Intelligence Levels
7 - Friendliness Levels
6 - Drool Levels
Which class do you want to compare with?
intelligence
George

This is the computer's card

5 - Exercise Levels
4 - Friendliness Levels
32 - Intelligence Levels
9 - Drool Levels
You have a higher Intelligence level!
3  This is how many cards you have!
1  This is how many cards they have!

George

5 - Exercise Levels
32 - Intelligence Levels
4 - Friendliness Levels
9 - Drool Levels
Which class do you want to compare with?
drool
Harry

This is the computer's card

5 - Exercise Levels
10 - Friendliness Levels
6 - Intelligence Levels
10 - Drool Levels
You have a lower drool level!
4  This is how many cards you have!
0  This is how many cards they have!

Harry

5 - Exercise Levels
6 - Intelligence Levels
10 - Friendliness Levels
10 - Drool Levels
Which class do you want to compare with?
drool
Traceback (most recent call last):
  File "main.py", line 207, in <module>
    main()
  File "main.py", line 202, in main
    initialisation()
  File "main.py", line 191, in initialisation
    game()
  File "main.py", line 50, in game
    assign_cards(num_of_cards)
  File "main.py", line 75, in assign_cards
    comparison(user_deck, comp_deck, x, num_of_cards, cards)
  File "main.py", line 160, in comparison
    print(comp_deck[y].name, "\nThis is the computer's card\n")
IndexError: list index out of range

Вот новый код:

while len(user_deck) != 0 and len(comp_deck) != 0 :
      user_points = 0
      comp_points = 0
      x =  random.randint(-1,len(user_deck)-1)
      y =  random.randint(-1,len(comp_deck)-1)

      if x < num_of_cards:
        print(user_deck[x].name)
        print(user_deck[x].exercise, "- Exercise Levels")
        print(user_deck[x].intelligence, "- Intelligence Levels")
        print(user_deck[x].friendliness, "- Friendliness Levels")
        print(user_deck[x].drool, "- Drool Levels")
      class_comparision = input("Which class do you want to compare with?\n")
      if class_comparision == "Exercise" or class_comparision == "exercise":
        print(comp_deck[y].name, "\nThis is the computer's card\n")
        print(comp_deck[y].exercise, "- Exercise Levels")
        print(comp_deck[y].friendliness, "- Friendliness Levels")
        print(comp_deck[y].intelligence, "- Intelligence Levels")
        print(comp_deck[y].drool, "- Drool Levels")
        ##Repeated for each attribute
        if user_deck[x].exercise >= comp_deck[y].exercise:
          print("You have a higher exercise level!")
          user_points = user_points + 1
          user_deck.append(comp_deck[y])
          del comp_deck[y]
          print(len(user_deck), " This is how many cards you have!")
          print(len(comp_deck), " This is how many cards they have!\n")
        elif user_deck[x].exercise < comp_deck[y].exercise:
          print("You have a lower exercise level!")
          comp_points = comp_points + 1
          comp_deck.append(user_deck[x])
          del user_deck[x]
          print(len(user_deck), " This is how many cards you have!")
          print(len(comp_deck), " This is how many cards they have!\n")
          ##Until here

1 Ответ

0 голосов
/ 26 марта 2019

comparison вызывает себя рекурсивно (и без каких-либо аргументов);об этом должна заботиться петля.

...