【发布时间】:2017-11-02 13:05:30
【问题描述】:
我正在为 Python 制作臭名昭著的 Hangman 游戏。这是我的代码:
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)
我如何替换替代词中的"-"如果该字母出现多次?我试图用其他方式表达它,但问题是所述字母可能不在任何给定单词中出现多次,我需要先以某种方式检查。
【问题讨论】: