Я пытаюсь написать программу для задания, в которой вы вводите определенную команду, и вы можете играть в Rock-Paper-Scissors-Lizard-Spock против компьютера. Это было сделано и работало, пока я не понял, что инструкции по назначению хотели, чтобы я сделал это так, чтобы вы продолжали играть в игру, пока один человек не получил пять побед.Новичок для Python - почему черт мой мой цикл не работает?
Так что я думал, никаких больших сделок, давайте бросим петлю while и некоторые переменные, чтобы отслеживать выигрыши. Но когда я запускаю программу, она работает только один раз. Я не знаю, что я делаю неправильно, так как это должно сработать. Это мой первый опыт работы с Python (версия 3.3) и этой IDE, поэтому мне действительно нужна помощь. Обычно я просто отлаживаю, но я не могу понять, как работать в этой среде IDE.
Вот мой код. Тревога во время цикла находится на дне. Я почти уверен, что все внутри класса работает. Я хотел бы отметить, что я уже пробовал пока (computerWins < 5 и userWins < 5), поэтому я не думаю, что это проблема.
import random
computerWins = 0
userWins = 0
print ('SELECTION KEY:\nRock = r\nPaper = p\nScissors = sc\nLizard = l\nSpock = sp')
class rockPaperScissorsLizardSpock:
#Two methods for converting from strings to numbers
#convert name to number using if/elif/else
#also converts abbreviated versions of the name
def convertName(name):
if(name == 'rock' or name == 'r'):
return 0
elif(name == 'Spock' or name == 'sp'):
return 1
elif(name == 'paper' or name == 'p'):
return 2
elif(name == 'lizard' or name == 'l'):
return 3
elif(name == 'scissors' or name == 'sc'):
return 4
else:
print ('Error: Invalid name')
#convert number to a name using if/elif/else
def convertNum(number):
if(number == 0):
return 'rock'
elif(number == 1):
return 'Spock'
elif(number == 2):
return 'paper'
elif(number == 3):
return 'lizard'
elif(number == 4):
return 'scissors'
else:
print ('Error: Invalid number')
#User selects an option, and their selection is saved in the 'choice' variable
#Using a while loop so that the user cannot input something other than one of the legal options
prompt = True
while(prompt):
i = input('\nEnter your selection: ')
if(i=='r' or i=='p' or i=='sc' or i=='l' or i=='sp'):
prompt = False
else:
print('Invalid input.')
prompt = True
#Convert the user's selection first to a number and then to its full string
userNum = convertName(i)
userChoice = convertNum(userNum)
#Generate random guess for the computer's choice using random.randrange()
compNum = random.randrange(0, 4)
#Convert the computer's choice to a string
compChoice = convertNum(compNum)
print ('You chose', userChoice)
print ('The computer has chosen', compChoice)
#Determine the difference between the players' number selections
difference = (compNum - userNum) % 5
#Use 'difference' to determine who the winner of the round is
if(difference == 1 or difference == 2):
print ('The computer wins this round.')
computerWins = computerWins+1
elif (difference == 4 or difference == 3):
print ('You win this round!')
userWins = userWins+1
elif(difference == 0):
print ('This round ended up being a tie.')
#Plays the game until someone has won five times
while(computerWins != 5 and userWins != 5):
rockPaperScissorsLizardSpock()
if(computerWins == 5 and userWins != 5):
print ('The computer wins.')
elif(computerWins != 5 and userWins == 5):
print ('You win!')
Код является очень сложным для чего-то так просто. –
что в мире «класс rockPaperScissorsLizardSpock:» должен делать. И да, путь к сложному для чего-то настолько простого. – letsc
Я должен сделать, чтобы пользователь вводил эти буквы, а использование чисел в соответствии со значениями казалось самым простым способом сделать это. Если бы это был java, или я не должен был делать такие конкретные вещи, это было бы проще. У вас есть предложения по этому вопросу? – lovechicken