私は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 で"-"
を置き換えることができますどのように?私は他の方法でそれを言い当てようとしましたが、問題は上記の手紙がでないことです。は何度も出現しています。
'もしletter in word:'が一度出現してもtrueになるでしょう、私はその要求が複数回であったと思います。 –
@SoumeshBanerjee質問は複数回出現するかもしれない文字を尋ねます。ハングマンの文脈では、それが(良い)ものであるか、(悪い)ものであるかというように、文字が「単語」にどれくらいの頻度で存在するかは、実際には重要ではありません。 'enumerate'を用いた' for'-loopは正確な一致数を知らなくても動作します。すべての要素をチェックするだけです。 – MSeifert
はい、それは私が言っていること**複数回** と 'もし単語があれば':一度現れても 'True'を返します –