>

파이썬을 처음 접하고 몇 가지 기본 사항을 배우려고 노력하면서 작은 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

    구문에서 약간의 구문과 공백을 사용하여 컴퓨터에서 코드를 작업했습니다. 전반적으로, 당신은 올바른 길을 가고있었습니다! while 의 이유  루프는 HANGMAN 의 첫 번째 요소 만 반환했습니다.  루프는 코드가 실제로 attempt 를 감소시키지 않았기 때문입니다.  값. 당신은하고있었습니다

    attempt=-1

    대신

    attempt -= 1

    그리고 그것은 attempt 를 설정했다   -1 로  각 반복. -= 사용하기  연산자는 실제로 그것을 줄입니다.

    잘못된 구문을 가진 변수 선언도있었습니다 ( = 를 사용하여 파이썬에서 변수를 할당합니다) == 가 아닌 ) 및 일부 일관되지 않은 변수 사용법 ( 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
    
    

    이것이 도움이되기를 바랍니다!

관련 자료

  • 이전 javascript - Firefox에서 windowgetSelection () toString ()이 작동하지 않습니다 (Chrome에서 작동)
  • 다음 java - intellij 경로에서 찾기는 항상 발생하지 않습니다