2017-02-27 1 views
0

저는 간단한 "단어 추측"게임을 만들려고합니다. 나는이 작업을 수행 할 수있는 기능을 가지고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!") 
관련 문제