2013-05-13 14 views
0

下面的代码:在使用random.choice的While循环中,如何随时选择一个随机字母?

# Guess the word program 
# By Roxmate 
# 12/04/2013 

import random 

print \ 
    """\t\t\t ***Welcome to Guess the Word Program*** 

     Your goal is to guess what word the computer has chosen and 
     you have 5 hints per guess, just type help to get the first one. 
     If you wish to exit the program, type in exit. 

     \t\t\tGood Luck! 
    """ 

WORDS = ("book","house","universe") 

gen_word = random.choice(WORDS) 
gen_word_1 = len(gen_word) 
hint_letter = random.choice(gen_word) 
hint = "help" 
quit_game = "exit" 

print "The word that the computer choosed has", gen_word_1, "letters\n" 

guess = raw_input("Your Guess:") 
while guess != quit_game: 
    if guess == gen_word: 
     print "Congrats, you have guessed the word!" 
     break 
    elif guess == hint: 
     print "Hint:: There is a(n)", hint_letter, "in the word\n" 

    else: 
     if guess != gen_word: 
      print "I am sorry that's not the word, try again.\n" 



    guess = raw_input("Your Guess:") 


raw_input() 

的问题是,在

elif guess == hint: 
     print "Hint:: There is a(n)", hint_letter, "in the word\n" 

我不明白为什么它不仅赋予了相同的字母作为一个提示,它不应该挑一个随机的信这个词,每次循环运行?例如我输入帮助,它给了我一个,下一次我输入帮助它会给我b。

回答

0

您只执行一次随机选择。如果你希望它继续发生,你需要在循环中进行。循环不会奇迹般地将所有代码运行在其外。

2

这样做

hint_letter = random.choice(gen_word) 

调用该函数一次,并存储返回值。 然后,你一遍又一遍地重复价值。 你应该这样做:

print "Hint:: There is a(n)", random.choice(gen_word), "in the word\n" 

代替。

+0

哦,我看..谢谢:) – user2371866 2013-05-14 00:09:05

+0

什么样,如果我只希望有5个提示用户?我需要做什么?我需要使用一个空元组和一个for循环来追加到该元组的五次用户使用提示的值,然后显示一些内容以显示用户他不能使用更多提示,或者是否存在更简单的方法呢? – user2371866 2013-05-14 00:24:38

+0

不需要只使用一个计数器,并在用户每次想要提示时增加计数器。 (不要忘记用if语句来检查它)。并注意用户可能会两次显示相同的信件 - 但无论如何都会失去提示。 – 2013-05-14 06:55:24