2017-02-27 130 views
0

我想在Python中創建一個簡單的「猜字」遊戲。我的輸出是一樣的東西:Python:試圖循環查找匹配字符的字符串

String: _____ _____ 
Guess a word: 'e' 

String:_e__o __e_e 
Guess a word: 'h' 

(and so on) 

String: hello there 

我有一個函數來做到這一點,這個函數中我有這樣的代碼:

def guessing(word): 
    count = 0 
    blanks = "_" * len(word) 
    letters_used = "" #empty string 

    while count<len(word): 
     guess = raw_input("Guess a letter:") 
     blanks = list(blanks) 
     #Checks if guesses are valid 
     if len(guess) != 1: 
      print "Please guess only one letter at a time." 
     elif guess not in ("abcdefghijklmnopqrstuvwxyz "): 
      print "Please only guess letters!" 

     #Checks if guess is found in word 
     if guess in word and guess not in letters_used: 
      x = word.index(guess) 
      for x in blanks: 
       blanks[x] = guess 
      letters_used += guess 
      print ("".join(blanks)) 
      print "Number of misses remaining:", len(word)-counter 
      print "There are", str(word.count(guess)) + str(guess) 

guess是原始輸入我從用戶那裏得到的一個猜測,並且letters_used僅僅是用戶已經輸入的猜測集合。我想要做的是根據word.index(guess)循環空白。不幸的是,這返回:

Guess a letter: e 
e___ 
Yes, there are 1e 

幫助將不勝感激!

+0

什麼是'x'?請提供完整的可重複工作代碼。 –

+0

@Anmol Singh Jaggi很抱歉。插入完整的代碼 – Nikitau

回答

2

你的代碼幾乎是正確的。有幾個錯誤我糾正了:

def find_all(needle, haystack): 
    """ 
    Finds all occurances of the string `needle` in the string `haystack` 
    To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3] 
    """ 
    start = 0 
    while True: 
     start = haystack.find(needle, start) 
     if start == -1: return 
     yield start 
     start += 1 


def guessing(word): 
    letters_uncovered_count = 0 
    blanks = "_" * len(word) 
    blanks = list(blanks) 
    letters_used = "" 

    while letters_uncovered_count < len(word): 
     guess = raw_input("Guess a letter:") 

     #Checks if guesses are valid 
     if len(guess) != 1: 
      print "Please guess only one letter at a time." 
     elif guess not in ("abcdefghijklmnopqrstuvwxyz"): 
      print "Please only guess letters!" 

     if guess in letters_used: 
      print("This character has already been guessed correctly before!") 
      continue 

     #Checks if guess is found in word 
     if guess in word: 
      guess_positions = list(find_all(guess, word)) 
      for guess_position in guess_positions: 
       blanks[x] = guess 
       letters_uncovered_count += 1 
      letters_used += guess 
      print ("".join(blanks)) 
      print "Number of misses remaining:", len(word)-letters_uncovered_count 
      print "There are", str(word.count(guess)) + str(guess) 
     else: 
      print("Wrong guess! Try again!")