2014-03-01 2 views
1

저는 파이썬을 처음 접했고 행맨 게임에 문제가 있습니다. 그래서 나는 사람이 추측하고있는 단어의 길이와 동일한 양의 하이픈 (-)으로 채워지는 "current"라는 목록을 가지고있다. 그들은 문자를 올바르게 추측 할 때 하이픈을 올바른 위치의 문자로 바꿉니다. 내가 가진 문제는 단어에 같은 글자가 2 개 이상있는 경우 글자가 올 때 처음으로 작동하지만 글자가 이미 추측되어서 작동하지 않으며 이 문제를 어떻게 해결할 지 짐작할 수 있습니다.Python - 한 단어에 여러 문자가있는 행맨 게임

current = "_" * len(theword) 
x = list(current) 
print (x) 

guessed = [] 

while current != theword and lives > 0: 

    print ("You have %d lives left" % lives) 
    guess = input("Please input one letter or type 'exit' to quit.") 
    guess = guess.lower() 


    if guess == "exit": 
     break 
    elif guess in guessed: 

     print ("You have already guessed this letter, please try again.") 



    guessed.append(guess) 

    if guess in theword: 
     index = theword.find(guess) 
     x = list(current) 
     x[index] = guess 
     current = "".join(x) 
     print ("Correct! \nYour guesses: %s" % (guessed)) 
     print(x) 


    else: 
     print ("Incorrect, try again") 
     lives = lives -1 


if current == theword: 
    print ("Well done, you have won!") 

감사

답변

0

대신 :

if guess in theword: 
     index = theword.find(guess) 
     x = list(current) 
     x[index] = guess 
     current = "".join(x) 
     print ("Correct! \nYour guesses: %s" % (guessed)) 
     print(x) 

이 시도해보십시오 string.find-방법을 사용

for index,character in enumerate(theword): 
    x = list(current) 
    if character == guess: 
     x[index] = guess 
1

을, 당신은 단지 문자의 첫 번째 항목을 얻을 말 그대로. 이 방법을 정의하면 모든 항목을 얻을 :

def find_all(word, guess): 
    return [i for i, letter in enumerate(word) if letter == guess] 

당신은 또한 당신이 다시 목록에 추가하지 않도록, 이미 전에 편지를 짐작 한 경우 확인 후 "계속"는 추가해야합니다.

이 작동합니다 :

def find_all(word, guess): 
    return [i for i, letter in enumerate(word) if letter == guess] 

current = "_" * len(theword) 
x = list(current) 
print (x) 

guessed = [] 

while current != theword and lives > 0: 

    print ("You have %d lives left" % lives) 
    guess = input("Please input one letter or type 'exit' to quit.") 
    guess = guess.lower() 


    if guess == "exit": 
     break 
    elif guess in guessed: 
     print ("You have already guessed this letter, please try again.") 
     continue 

    guessed.append(guess) 

    if guess in theword: 
     indices = find_all(theword, guess) 
     x = list(current) 
     for i in indices: 
      x[i] = guess 
      current = "".join(x) 
      print ("Correct! \nYour guesses: %s" % (guessed)) 
      print(x) 

    else: 
     print ("Incorrect, try again") 
     lives = lives -1 
+0

감사합니다 위대한 작품! – user3160631