2013-12-22 6 views
0

임씨는 단어 게임을하고 있습니다. 사용자를위한 목적은 5 번의 시도에서 5 글자 단어를 추측하는 것입니다. 사용자는 첫 번째 문자를 알 수 있습니다. 그리고 그가 정확한 단어를 얻지 못했지만 올바른 장소에 편지가 있다면 그는 이것을 알게됩니다. 이 코드에 대한 두 가지 질문이파이썬 개선 단어 게임

import random 
list_of_words = ["apple","table", "words", "beers", "plural", "hands"] 
word = random.choice(list_of_words) 

attempts = 5 

for attempt in range(attempts): 
    if attempt == 0: 
     tempList = list(word[0] + ("." * 4)) 
     print("The first letter of the word we are looking for: %s" % "".join(tempList)) 

    answer = raw_input("What is the word we are looking for?:") 
    if len(answer) != 5: 
     print ('Please enter a 5 letter word') 

    Else: 
     if answer != word: 
      wordlist = list(word) 
      answerlist = list(answer) 
      for i in range(min(len(wordlist), len(answerlist))): 
       if wordlist[i] == answerlist[i]: 
        tempList[i] = wordlist[i] 
      print(tempList) 

     else: 
      print("correct, you have guessed the word in:", attempt, "attempts") 

if answer != word: 
    print("Sorry maximum number of tries, the word is: %s" % word) 

:

내 코드입니다

첫 번째 작은 문제 : 사용자가 6 또는 4 글자 단어를주는 경우 인쇄 여전히 것 그 말. 나는 그 단어를 그냥 무시하고 시도는 사용하지 않는다. 그러나

편지가 정확한 (또한 첫 글자도) 주어지면 피드백의 표준 부분이되지 않는다. temp와 함께 이것을 얻으려고하지만 아직 큰 일을하지 못합니다.

내 코드를 정리하기위한 제안도 환영합니다!

감사합니다.

답변

1

코드에서 몇 가지 사항을 변경 했으므로 이제는 사양에 따라 작동합니다. 나는 또한 그것에 설명을 몇 가지 설명을 썼다 :

import random 

list_of_words = ["apple", "table", "words", "beers", "plural", "hands"] 
word = random.choice(list_of_words) 

# changed the loop to a 'while', because i don't want to count the invalid length answers 
# and wanted to exit the loop, when the user guessed correctly 
attempts = 5 
attempt = 0 
correct = False 
while attempt < attempts and not correct: 
    if attempt == 0: 
     # i stored a working copy of the initial hint (ex: "w....") 
     # i'll use this to store the previously correctrly guessed letters 
     tempList = list(word[0] + ("." * 4)) 
     print("The first letter of the word we are looking for: %s" % "".join(tempList)) 

    answer = raw_input("What is the word we are looking for?:") 
    if len(answer) != 5: 
     print("Please enter a 5 letter word") 
    else: 
     if answer != word: 
      # i simplified this loop to comparing the wordlist and answerlist and update templist accordingly 
      wordlist = list(word) 
      answerlist = list(answer) 
      for i in range(min(len(wordlist), len(answerlist))): 
       if wordlist[i] == answerlist[i]: 
        tempList[i] = wordlist[i] 
      print(tempList) 
     else: 
      correct = True 
      print("Correct, you have guessed the word in %s attempts" % (attempt + 1)) 
     attempt += 1 

if answer != word: 
    # also i used string formatting on your prints, so is prints as a string, and not as a tuple. 
    print("Sorry maximum number of tries, the word is: %s" % word) 
+0

@ zord. 와우,이 사람은 대단합니다. 많은 감사합니다! 내 첫 번째 버전에는 'while'이 포함되었지만 나중에 변경되었습니다. 결국 '더 나은'동안 '추측. 고마워, 고마워! 환호 – user3119123

+0

귀하의 환영합니다! :) – zord

1

코드에 몇 가지 문제점이 있습니다.

지금은 1입니다. 나는 샘플 출력에서 ​​다섯 글자 단어 (beeds and bread)를 입력하고 있는데, 여전히 Please enter a 5 letter word을 출력하고 있습니다.

이 두 라인 :

if len(answer) != 4: 
    print ('Please enter a 5 letter word') 

는 확실히이되어야한다 :

if len(answer) != 5: 
    print ('Please enter a 5 letter word') 
    continue 

이 잘못된 입력을 잡아 다시 루프의 둘레에 갈 것입니다.

1

응답 특정 질문 :

  1. 당신은 당신을 추측 편지를 이동하는 경우가 적당한 길이
  2. 의 단어를 입력 할 때까지 그 루프에서 사용자를 유지, 당신의 input 주위에 for 루프가 필요합니다 올바른 장소, 그것은 "abcde" 다음 "fghij" 등 추측하여 승리하는 것은 사소한 것입니다. 당신은 당신의 규칙이 무엇인지에 대해 신중하게 생각할 필요가 있습니다. 당신은 "답변에 있지만 잘못된 장소에있는 추측의 글자"의 별도 목록을 가질 수 있으며 이것을 사용자에게 보여줄 수 있습니다.
  3. 이전에 추측 한 모든 문자로 표시 버전을 유지하려면 표시 문자 목록을 유지하십시오 (display = ["." for letter in answer]).

다른 문제는, 당신은 :

    워드 길이 (특히 len("plural") != 5 등)의
  1. 너무 많은 하드 코딩; 코드를 으로 다시 작성하여 단어의 길이를 사용하십시오. 이렇게하면 더 유연하게됩니다.
  2. 전체 답변을 추측 한 경우에만 사용자에게 알립니다. 그들이 중첩 된 문자로 그것을 얻으면 어떨까요? 그들이 if all(letter != "." for letter in display):으로 테스트하여 그들이 그런 식으로 답변을했는지 확인할 수 있습니다.
  3. 귀하의 목록 이해율 [i for i in answer if answer in word]은 어떤 것에도 할당되지 않습니다.