#python
Вопрос:
Вот код, который у меня есть:
if letter_user not in letters_word:
mistakes = 1
wrong_letters.append(letter_user)
if letter_user not in alphabet:
print('Please only enter ONE letter.')
Я создал список алфавита, и если пользователи угадают, что его нет в этом списке, то они получат предупреждение «Пожалуйста, введите только ОДНУ букву». Однако счетчик «ошибок» все равно увеличивается, что приводит к тому, что пользователь теряет жизнь, чего я не хочу.
Как мне сделать так, чтобы пользователь не потерял жизнь при вводе недопустимого персонажа в этой игре «палач»?
Вот мой полный код:
# importing wordbank
import random
from wordbankcool import wordbank
# hangman graphics
hangman_graphics = ['_',
'__',
'__n |',
'__n |n O',
'__n |n On |',
'__n |n On/|',
'__n |n On/| ',
'__n |n On/| n/',
'__n |n On/| n/ '
]
# code is inside while loop
playagain = 'Y'
while playagain == 'Y':
# alphabet
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# basic functions of the game
mistakes = 0
letters_guessed = []
mistakes_allowed = len(hangman_graphics)
# selecting a random word for the user to guess
word = random.choice(wordbank)
# letters user has guessed guessed incorrectly stored in lists
letters_word = list(word)
wrong_letters = []
print()
# amount of letters the word has
print('The word has {} letters'.format(len(letters_word)))
# while loop which will run until the the number of mistakes = number of mistakes allowed
while mistakes < mistakes_allowed:
print()
print('Incorrect guesses: ', end='')
for letter in wrong_letters:
print('{}, '.format(letter), end='')
print()
print('Guesses left: {}'.format(mistakes_allowed - mistakes))
letter_user = input('Guess a letter: ').lower()
# checking if the letter has been guessed before
while letter_user in letters_guessed or letter_user in wrong_letters:
print()
print('You have already guessed this letter, guess a different one.')
letter_user = input('Guess a letter: ')
# increasing amount of mistakes if the letter that has been guessed is not in the word
if letter_user not in letters_word:
mistakes = 1
wrong_letters.append(letter_user)
if letter_user not in alphabet:
print('Please only enter ONE letter.')
print()
# showing how many letters the user has/has not guessed
print('Word: ', end='')
# if letter is in word, its added to letters guessed
for letter in letters_word:
if letter_user == letter:
letters_guessed.append(letter_user)
# replace letters that haven't been guessed with an underscore
for letter in letters_word:
if letter in letters_guessed:
print(letter ' ', end='')
else:
print('_ ', end='')
print()
# hangman graphics correlate with amount of mistakes made
if mistakes:
print(hangman_graphics[mistakes - 1])
print()
print('-------------------------------------------') # seperator
# ending: user wins
if len(letters_guessed) == len(letters_word):
print()
print(f'You won! The word was {word}!')
print()
playagain = input('Play again? (Y/N) ').upper()
if playagain == 'Y':
word = random.choice(wordbank)
break
elif playagain == 'N':
break
# ending: user loses
if mistakes == mistakes_allowed:
print()
print('Unlucky, better luck next time!')
print()
print(f'The word was {word}.')
print()
playagain = input('Play again? (Y/N) ').upper()
if playagain == 'Y':
word = random.choice(wordbank)
Комментарии:
1. Если вы хотите дать ошибку обратного отсчета, то сделайте 2 переменные, одну для подсчета и одну для ограничения, и установите свой предел использования попыток во время цикла. Если игрок вводит != Правильный ответ и подсчет
Ответ №1:
Вы могли бы переместить проверку на неправильный ввод вверх, чтобы это произошло раньше. Затем вы можете использовать continue
оператор — это в основном переход к концу цикла, пропуская все после него.
if letter_user not in alphabet:
print('Please only enter ONE letter.')
continue
if letter_user not in letters_word:
mistakes = 1
wrong_letters.append(letter_user)
....
Однако у вас уже есть входной цикл, так что вы можете проверить его там.
while True:
letter_user = input('Guess a letter: ').lower()
if letter_user not in alphabet:
print('Please only enter ONE letter.')
elif letter_user in letters_guessed or letter_user in wrong_letters:
print('You have already guessed this letter, guess a different one.')
else:
break