2014-02-27 241 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: 
    . 
    . 
    .