2017-02-27 8 views
0

私はPythonで単純な "guess the word"ゲームを作成しようとしています。私はこれを行うための機能を持っており、この関数の中で、私はこのコードを持っている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!") 
関連する問題