1

私は私の子供のための言葉の寄せ集めゲームに取り組んでいます。ヒントを得るために、推測に「ヒント」と入力できるようにしてほしい。最初の「ヒント」は、単語の最初と最後の文字を示す必要があります。次に「ヒント」と入力すると、単語の最初の 2 文字と最後の 2 文字が表示されるはずです。

彼らが「ヒント」を入力するのは初めてですが、while ループが壊れてしまい、間違って推測したり、「ヒント」を再度入力したりすることはできません。

私は問題がこの行にあることを知っています:

while guess != correct and guess != 'hint':

ユーザーがヒントを複数回入力できるように修正できないようです。

これが私のコードです:

# The computer picks a random word, and then "jumbles" it
# the player has to guess the original word

import random

replay = "y"
while replay == "y":

    print("\n"* 100)
    word = input("Choose a word for your opponent to de-code: ")
    print("\n"* 100)
    # provide a hint if the user wants one
    hint_count = 1

    # create a variable to use later to see if the guess is correct
    correct = word

    # create a empty jumble word
    jumble = ""
    # while the chosen word has letters in it
    while word:
        position = random.randrange(len(word))
    #   add the random letter to the jumble word
        jumble += word[position]
    #   extract a random letter from the chosen word
        word = word[:position] + word[position +1:]

    # start the game
    print(
    """

                Welcome to the Word Jumble!

        Unscramble the letters to make a word.
    (Press the enter key at the prompt to quit.)
    """
    )
    score = 10
    print("The jumble is: ",jumble)

    guess = input("\nType 'hint' for help but lose 3 points. \
                  \nYOUR GUESS: ")

    while guess != correct and guess != 'hint':
        print("Sorry that's not it.")
        score -= 1
        guess = input("Your guess: ")

    if guess == 'hint':
        print("The word starts with '"+ correct[0:hint_count]+"' and ends with '"+correct[len(correct)-hint_count:len(correct)]+"'")
        score -= 3
        hint_count += 1
        guess = input("Your guess: ")

    if guess == correct:
        print("That's it! You guessed it!\n")
        print("Your score is ",score)


    print("Thanks for playing.")

    replay = input("\n\nWould you like to play again (y/n).")
4

2 に答える 2

1

最初の「ヒント」の後、プログラムは推測を求めてから print("Thanks for playing.") に進む必要があります。これは、ヒントをチェックする条件が while ループの外にあるためです。while ループに入れます。

while guess != correct:
    if guess == 'hint':
        print("The word starts with '"+ correct[0:hint_count]+"' and ends with '"+correct[len(correct)-hint_count:len(correct)]+"'")
        score -= 3
        hint_count += 1
        guess = input("Your guess: ")

     else:
        print("Sorry that's not it.")
        score -= 1
        guess = input("Your guess: ")
于 2012-06-28T18:36:26.110 に答える
0

guess == 'hint'問題は、whileループの外側をチェックすることです。次のようなものを試してください

while True:
    guess = input(...)
    if guess == correct:
        # correct
        break
    elif guess == 'hint':
        # show hint
    else:
        # not it, decrement score
于 2012-06-28T18:34:30.917 に答える