2017-06-01 7 views
1

私はPythonの悪名高いハングマンゲームをやっています。ここに私のコードは次のとおりです。複数の文字が表示されてもリスト内の文字を置き換える

import random 
import string 
WORDLIST_FILENAME = "words.txt" 
def load_words(): 
    inFile = open(WORDLIST_FILENAME, 'r', 0) 
    line = inFile.readline() 
    wordlist = string.split(line) 
    return wordlist 
def choose_word(wordlist): 
    return random.choice(wordlist) 
wordlist = load_words() 
word=list(choose_word(wordlist))   #I read that it's preferable to 
print "Welcome to the game, Hangman!"  #use lists as string are more 
print "I am thinking of a word that is", len(word), "letters long." #tricky 
def check(word):       #because they are immutable and 
    guesses=20       #some problems might arise 
    let="abcdefghijklmnopqrstuvwxyz" 
    altword=list(len(word)*"-") 
    while "-" in altword and guesses>0: 
     print "You have", guesses, "guesses left." 
     print "Available letters: ", let 
     letter=raw_input("Please guess a letter: ") 
     newlet=let.replace(letter, "") 
     let=newlet 
     if letter in word: 
      index=word.index(letter)   #here is the problem when a 
      altword[index]=letter    #letter appears more than once 
      print "Good guess: ", ''.join(map(str, altword)) 
     else: 
      guesses=guesses-1 
      print "Oops! That letter is not in my word: ", ''.join(map(str, altword)) 
    if guesses<=0: 
     print "Sorry, you've been hanged! The word is: ", ''.join(map(str, word)) 
    else: 
     print "Congratulations, you won!" 
check(word) 

手紙が複数回表示された場合、私はaltword "-"を置き換えることができますどのように?私は他の方法でそれを言い当てようとしましたが、問題は上記の手紙がでないことです。は何度も出現しています。

答えて

0

あなたがドン」出現回数を数える必要があります。ゲームロジックにとっては、推測された文字が正しい(言葉で)か正しくない(言葉ではない)場合にのみ重要です。あなたはenumerateとシンプルfor -loopを使用することができ、すべての試合交換するには

if letter in word: 
    for idx, char in enumerate(word): # go through the word (remembering the index) 
     if char == letter:    # check if it is a match 
      altword[idx] = letter  # replace the character at idx in "altword" with "letter" 
    print "Good guess: ", ''.join(map(str, altword)) 
else: 
    guesses -= 1 
    print "Oops! That letter is not in my word: ", ''.join(map(str, altword)) 
+0

'もしletter in word:'が一度出現してもtrueになるでしょう、私はその要求が複数回であったと思います。 –

+0

@SoumeshBanerjee質問は複数回出現するかもしれない文字を尋ねます。ハングマンの文脈では、それが(良い)ものであるか、(悪い)ものであるかというように、文字が「単語」にどれくらいの頻度で存在するかは、実際には重要ではありません。 'enumerate'を用いた' for'-loopは正確な一致数を知らなくても動作します。すべての要素をチェックするだけです。 – MSeifert

+0

はい、それは私が言っていること**複数回** と 'もし単語があれば':一度現れても 'True'を返します –

0

は、単にあなたが、これはリンゴ であなたのpの発生を与えるこの

'apple'.count('p') 

のように確認することもできますし、文章内の単語を検出するために、同じを使用することができます

"apple are red and bananas are yellow and oranges are orange".count("and") 
+0

しかし、これを単に** **のカウントを提供します。質問は試合の**インデックス**を求めます。 – MSeifert

+0

はこの行に答えました ** _問題は、上記の手紙が任意の単語に複数回出現することがありますが、何らかの理由でそれを確認する必要があります。** –

+0

ありがとう、これを覚えてみてください! – Dima

関連する問題