如何修复“ While Loop in python”在我的代码中不起作用

时间:2019-06-14 05:04:12

标签: python python-3.x pygame pycharm

我是python的新手,尝试学习一些基础知识,因此尝试开发一个小型的HANGMAN游戏。我陷入了while循环格式中,除了HANGMAN列表中的ZERO索引元素外,结果中什么也没显示。

import random
HANGMAN = (
"""
-----
|    |
|
|
|
|
|
|
|
|
|
|
-------
"""
  ,
"""
-----
|   |
|   0
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|   |
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|  /
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|  / \
|
|
|
|
|
|
|
------
""")
print(HANGMAN[0])

play_again = True

while play_again:

         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"]
         chossenword = random.choice(words_list).lower()
         guess = None   #player guess input
         guessed_letters = []   #we add all of the users guesses to this list.
         blank_word = []  #repalcing all the letetrs of the chosen word with dashed symbol.
for letter in chossenword:
    blank_word.append('-')
attempt = 6

while attempt > 0:

        if (attempt!= 0 and "-" in blank_word):

            print(('\n You Have () attempts remaining.').format(attempt))

        try:
            guess == str(input('\n please select a letter between A_Z')).lower()
        except :
            print("that's not a valid input , please try again.")
            continue

        else:
            if not guess.isaplha():
                print('that is not a letter, please try again ')
                continue

            elif len(guess) > 1:
             print("that's is more tahn one letetre , please try again")
             continue

            elif guess in guessed_letters:
                print(" you have already guessed that letter , please try again.")
                continue
            else:
                pass

            guessed_letters.append(guess)

            if guess not in chossenword:
                attempts=-1
                print(HANGMAN[(len(HANGMAN)-1)-attempts])

            else :
                SearchMore = True
                startsearchindex == 0
                while searchMore:
                    try :
                        foundAtIndex = chossenword.index(guess, startsearchindex)
                        blank_word[foundAtIndex]= guess
                        startsearchindex = foundAtIndex + 1
                    except :
                        searchMore = False

            print("".join(blank_word))

            if attempts == 0:
                print("sorry. the game is over , The word was" + chossenword)
                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(chossenword))
                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

在while循环中没有任何作用。

1 个答案:

答案 0 :(得分:2)

我的代码在我的机器上可以正常工作了,并且语法和空白处都比较精细。总体而言,您的方向正确! while循环仅返回HANGMAN循环的第一个元素的原因是因为代码实际上并未减小attempt的值。你在做

attempt=-1

代替

attempt -= 1

,并且每次迭代都将attempt设置为-1。实际上,使用-=运算符会减少它。

也存在语法错误的变量声明(您在Python中使用=而不是==分配变量)和一些不一致的变量用法(attempts而不是attemptsearchmoresearchMore等)。

最后,我将单词列表移到了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

希望这会有所帮助!