2012-06-28 2 views
1

Я работаю над игрой для своих детей. Я хочу, чтобы они могли ввести «намек» в предположение, чтобы получить подсказку. Первый «намек» должен дать первую и последнюю буквы слова. В следующий раз, когда они набирают «подсказку», должны быть указаны первые две и последние две буквы слова .. и т. Д.Python while loop для проверки двух истинных/ложных элементов

У меня он работает в первый раз, когда они набирают «подсказку», но затем цикл 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).") 
+1

Ваша проблема заключается в том, что цикл 'while' позволяет пользователю вводить гадание или' hint', но ввод «подсказки» выходит из цикла. Вот почему пользователь может использовать «hint» только один раз (и после этого один намек на то, что пользователь только вводит еще одно слово). Сейчас есть несколько ответов, и любой из них устранит проблему. Вы хотите, чтобы цикл while while не выходил, пока пользователь не получил слово правильно, и вы хотите, чтобы каждый ответ, который пользователь вводил, оценивался отдельно (правильно ли это «подсказка»? Также, возможно, это «quit» '?) – steveha

+0

Это логическая проблема, а не проблема программирования. –

+0

@ Программирование KarlKnechtel - это сама логическая проблема. – erm3nda

ответ

0

Проблема заключается в том, что вы проверить guess == 'hint' вне цикла. Попробуйте что-то вроде

while True: 
    guess = input(...) 
    if guess == correct: 
     # correct 
     break 
    elif guess == 'hint': 
     # show hint 
    else: 
     # not it, decrement score 
+2

Кстати, есть намного более простые способы создания беспорядка. Посмотрите на [random.shuffle] (http://docs.python.org/library/random.html#random.shuffle). –

1

После первого «намека» программа должна попросить угадать, а затем продолжить на печать («Спасибо за игру.»), Так как условный, чтобы проверить намек находится вне цикла в то время как , Поместите его в цикл 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: ")