Я заставил ваш код работать на моей машине с небольшим синтаксисом и поиском пробелов. В целом, вы были на правильном пути! Причина, по которой цикл while
возвращал только первый элемент цикла HANGMAN
, заключалась в том, что код фактически не уменьшал значение attempt
. Вы делали
attempt=-1
вместо
attempt -= 1
и это устанавливало attempt
на -1
каждую итерацию. Использование оператора -=
фактически уменьшит его.
Были также объявления переменных с неправильным синтаксисом (вы назначаете переменные в Python с =
, а не ==
) и некоторые несовместимые использования переменных (attempts
вместо attempt
, searchmore
и searchMore
и т. д.).
Наконец, я переместил список слов за пределы цикла while. Вам не нужно пересоздавать этот список каждый раз, когда выполняется цикл while.
import random
HANGMAN = ("""| | | | | | | | | | | |""" ,
"""| | | 0 | | | | | | | |""" ,
"""| | | 0 | | | | | | | | |
|""" ,
"""| | | 0 |
/| | | | | | | | |""" ,
"""| | | 0 |
/|\ | | | | | | | |""" ,
"""| | | 0 |
/|\ |
/ | | | | | | |""" ,
"""| | | 0 |
/|\ |
/ \ | | | | | | |"""
)
words_list = ['abruptly',
'absurd',
'abyss',
'affix',
'askew',
'avenue',
'awkward',
'axiom',
'azure',
'bagpipes',
'banjo',
'beekeeper',
'bikini',
'blitz',
'blizzard',
'boggle',
'bookworm',
'boxcar',
'boxful',
'buckaroo',
'buffalo',
'buffoon',
'buxom',
'buzzard',
'buzzing',
'buzzwords',
'caliph',
'cobweb',
'cockiness',
'croquet',
'crypt',
'curacao',
'cycle',
'daiquiri',
'dirndl',
'disavow',
'dizzying',
'duplex',
'dearies',
'embezzle',
'equip',
'espionage',
'edouard',
'exodus',
'faking',
'glyph',
'gnarly',
'fixable',
'fjord',
'flapjack',
'flopping',
'foxglove',
'frazzled',
'frizzled',
'fuchsia',
'funny',
'gabby',
'galaxy',
'galvanize',
'gazebo',
'gaiter',
'gimme',
'glowworm',
'gossip',
'grogginess',
'haiku',
'haphazard',
"stronghold",
"stymied",
"subway",
"swivel",
"syndrome",
"thriftless",
"thumbscrew",
"topaz",
"transcript",
"transgress",
"transplant",
"triathlon",
"twelfth",
"twelfths",
"unknown",
"unworthy",
"unzip",
"uptown",
"vaporize",
"vixen",
"vodka",
"voodoo",
"vortex",
"voyeurism",
"walkway",
"waltz",
"wave",
"wavy",
"waxy",
"wellspring",
"wheezy",
"whiskey",
"whizzing",
"whomever",
"wimpy",
"witchcraft",
"wizard",
"woozy",
"wristwatch",
"wavers",
"xylophone",
"yachtsman",
"yippee",
"yoked",
"youthful",
"yummy",
"zephyr",
"zigzag",
"zigzagging",
"zilch",
"zipper",
"zodiac",
"zombie"]
print(HANGMAN[0])
play_again = True
while play_again:
chosen_word = random.choice(words_list)
guess = None #player guess input
guessed_letters = [] #we add all of the user's guesses to this list.
blank_word = [] # replacing all the letters of the chosen word with dashed symbol
for letter in chosen_word: # creating list with dashes instead of letters for the word
blank_word.append('-')
attempt = 6 # the number of incorrect attempts a user gets
while attempt > 0: # while the user still has valid guesses left
if (attempt!= 0 and "-" in blank_word): # while player can still guess
print(('\n You Have {} attempts remaining.').format(attempt)) # tell the user how many attempts are left
try:
guess = str(input('\n please select a letter between A-Z')).lower() # enter a letter, lowercase it
except: # will never hit this
print("that's not a valid input , please try again.")
continue
if not guess.isalpha(): # check if the letter is alphabetical
print('that is not a letter, please try again ')
continue
elif len(guess) > 1:
print("that's is more than one letter , please try again")
continue
elif guess in guessed_letters:
print(" you have already guessed that letter , please try again.")
continue
guessed_letters.append(guess) # add guess to guessed_letters
print("Guessed letters: ", guessed_letters)
if guess not in chosen_word: # if the guessed letter isn't in the chosen_word
attempt -= 1 # reduce # of attempts available
print(HANGMAN[(len(HANGMAN)-1)-attempt]) # print the element of HANGMAN at (length of HANGMAN - 1) - the # of attempts
else: # if the guessed letter IS in the chosen_word
searchMore = True
startsearchindex = 0
while searchMore:
try :
foundAtIndex = chosen_word.index(guess, startsearchindex)
blank_word[foundAtIndex]= guess
startsearchindex = foundAtIndex + 1
except :
searchMore = False
print("".join(blank_word))
if attempt == 0: # no more attempts
print("sorry. the game is over , The word was" + chosen_word)
print("\nWould you like to play again?")
response =input('>').lower()
if response not in ("yes","y"):
play_again = False
print("thanks for playing HANGMAN!")
break
if "-" not in blank_word :
print(("\n Congratualtion! {} was the word").format(chosen_word))
print("\n World you like to play again ?")
response = input('>').lower()
if response not in ("yes","y"):
play_again = False
print("thanks for playing HANGMAN!")
break
Надеюсь, это поможет!