我想说的是:" Pizza"
sAnswer = "Pizza"
sReveal = len(sAnswer)* "_ "
上面我已经构建了一个显示" _ _ _ _ _"
的字符串与任何其他Hangman游戏一样,它会包含下划线我的问题是:如何去除空间的sReveal,找到猜到的字母的索引(例如:' z')然后用下划线替换下划线必要时z,然后在其间重建空间,因此它将成为:" _ _ zz _"
我尝试过这样的事情无济于事:
if sLetterGuessed in list(sAnswer):
for character in list(sAnswer):
index = sAnswer.find(sLetterGuessed)
sReveal = sReveal.replace(" ", "")
list(sReveal)[index] = "z"
print sReveal
for char in sReveal:
sReveal = sReveal.strip(" ")
sReveal = sReveal.replace("_", char)
print sReveal
print HangingMan[iErrors]
## The code is just consideration of the route I'm taking with this; the horrible route.
答案 0 :(得分:1)
更新sReveal的简便方法是使用list comp和str.join
:
sAnswer = "Pizza"
sReveal = len(sAnswer)* "_ "
letter_guessed = "z"
# if letter_guessed == current letter in word, add that letter else add a _
sReveal = " ".join([x if x==letter_guessed else "_" for x in sAnswer ])
print(sReveal)
_ _ z z _
我必须为课程做的旧刽子手游戏可能很有用:
def hangman(secret_word):
from string import ascii_lowercase
print ("Welcome to Hangman!")
print ("I am thinking of a word that is {} letters long\n-----------".format(len(secret_word)))
guesses = 8
letters_guessed = []
missed_l = ''
correct_l = ''
secret_word = secret_word.lower()
while True:
# if all the letters in secret_word are in correct_l , the user has won
if all(x in correct_l for x in secret_word):
print ("Congratulations, you won!")
break
# if len missed letters is 8, user has used up all guesses so break/end teh game
elif len(missed_l) == 8:
print ("Sorry, you ran out of guesses. The word was {}.".format(secret_word))
break
print ("You have {} guesses left".format(guesses))
print ("Available Letters: {}".format(" ".join([x for x in ascii_lowercase if x not in letters_guessed])))
guess = raw_input("Please guess a letter: ").lower()
# if guess in letters_guessed user has already guessed that letter
if guess in letters_guessed:
print ("Sorry You've already guessed that letter: {}\n-----------".format(guess))
# else if it is in the word, add guess to correct_l and to letters guessed
elif guess in secret_word:
letters_guessed.append(guess)
correct_l += guess
print("Good guess: {}\n-----------".format(" ".join([x if x in letters_guessed else "_" for x in secret_word])))
# if users guess is not in the word, minus a life/guess
elif guess not in secret_word:
letters_guessed.append(guess)
guesses -= 1
print (" That letter is not in my word: {}\n-----------".format(" ".join([x if x in letters_guessed else "_" for x in secret_word])))
missed_l += guess
答案 1 :(得分:0)
您正在将sReveal转换为列表,但是您没有保存列表,所以它毕竟没有效果。
试试这个:
aReveal = list(sReveal)
index = sAnswer.find(sLetterGuessed)
while index >= 0:
aReveal[index] = sLetterGuessed
index = sAnswer.find(sLetterGuessed, index + 1)
sReveal = ''.join(aReveal)
print sReveal