2014-02-27 247 views
0

我有一个用户猜测字母的游戏。他们被显示为神秘作品的空白版本(例如,_____,_等于单词中的字符数)。该程序知道该单词,并且如果他们猜测的字母出现在神秘单词中,则需要替换该单词的空白版本中的每个索引。替换Python中字符的每个实例字符串

例如,如果玩家猜测“p”,单词是“河马”,他们将显示__pp_。但是,我的代码只会替换“p”的第一个实例,代之以__p__

这会更容易处理列表问题吗?

mistakes = 0 
complete = False 
t = False 
words = ['cow','horse','deer','elephant','lion','tiger','baboon','donkey','fox','giraffe'] 

print("\nWelcome to Hangman! Guess the mystery word with less than 6 mistakes!") 


# Process to select word 
word_num = valid_number() 
word = words[word_num] 
#print(word) 
print("\nThe length of the word is: ", str(len(word))) 
attempt = len(word)*"_" 

# Guesses 
while not (mistakes == 6): 
    guess = valid_guess() 
    for letter in word: 
     if guess == letter: 
      print("The letter is in the word.") 
      position = word.index(guess) 
      attempt = attempt [0:position] + guess + attempt [position + 1:] 
      print("Letters matched so far: ", attempt) 
      t = True 
    while (t == False): 
     print("The letter is not in the word.") 
     print("Letters matched so far: ", attempt) 
     mistakes = mistakes + 1 
     hangMan = ["------------", "|   |", "|   O", "|  / |", "|   |", "|  / |\n|\n|"] 
     hang_man() 
     t = True 
    t = False 

回答

2
answer = 'hippo' 
fake = '_'*len(answer) #This appears as _____, which is the place to guess 
fake = list(fake)  #This will convert fake to a list, so that we can access and change it. 
guess = raw_input('What is your guess? ') #Takes input 
for k in range(0, len(answer)): #For statement to loop over the answer (not really over the answer, but the numerical index of the answer) 
    if guess == answer[k] #If the guess is in the answer, 
     fake[k] = guess #change the fake to represent that, EACH TIME IT OCCURS 
print ''.join(fake) #converts from list to string 

这种形式运行:

>>> What is your guess? 
p 
>>> __pp_ 

要遍历所有的一切,我没有使用index,因为index仅返回第一个实例:

>>> var = 'puppy' 
>>> var.index('p') 
0 

所以要做到这一点,我不是通过字母来分析它,而是通过它的放置,使用一个不会将k作为每个字母,而是将其作为一个数字,以便我们可以有效地遍历整个字符串没有它只返回一个变量。

人们还可以使用re,但对于编程新手,最好是明白了什么是如何工作的,而不是从一个模块调用一组函数(除随机数的情况下,没有人希望让他们的自己的伪随机方程:D)

+0

这几乎和我在hang子手游戏中所做的完全一样。 – sayantankhan

+0

不错:)我也是... –

+0

谢谢,这个很容易理解!当我得到第二个时,我会沿着这些路线实施一些事情。 – user3290553

0

基于Find all occurrences of a substring in Python

import re 

guess = valid_guess() 
matches = [m.start() for m in re.finditer(guess, word)] 
if matches: 
    for match in matches: 
     attempt = attempt[0:match] + guess + attempt[match+1:] 
     print("Letters matched so far: ", attempt) 
else: 
    . 
    . 
    .