我试图制作一个基于文本的刽子手游戏。我有两个清单:
我可以检查第一个列表中的单词并替换它,只有在有一次出现时才会替换它。
例如:这个词是' DEAD'并且用户输入D.输出将是D ***,因为它只找到一个。
从一个列表替换到另一个列表的当前代码:
if guess() == True:
pos = word.index(guessed)
display[pos] = word[pos]
print('Correct: ', display)
如何更改代码以便替换列表中的每个匹配项?
答案 0 :(得分:4)
您可以使用zip
来逐字母地比较当前完成的字符串的答案。然后在join
中使用生成器表达式来检查字母是否正确,否则不要更改它。您仍然需要添加逻辑来跟踪他们是如何被绞死的。
answer = 'dictionary'
current = '*'*len(answer) # Produces '**********'
while current != answer:
guess = input('guess a letter: ')
current = ''.join(guess if guess == letter else blank for blank, letter in zip(current, answer))
print(current, '\n')
测试
guess a letter: i
*i**i*****
guess a letter: d
di**i*****
guess a letter: c
dic*i*****
guess a letter: t
dicti*****
guess a letter: n
dicti*n***
guess a letter: l # Note this letter was wrong so the word didn't change
dicti*n***
guess a letter: o
diction***
guess a letter: r
diction*r*
guess a letter: a
dictionar*
guess a letter: y
dictionary
答案 1 :(得分:0)
word = "DEAD"
inp = "D"
print("".join([s if inp == s else "_" for s in word]))
D__D
你也应该使用if guess()
if guess() == True
,如果guess()在返回布尔值时为True或False。
如果您正在使用功能:
secret_word = "DEAD"
def is_guessed(secret_word, letters_guessed):
return all(x in letters_guessed for x in secret_word)
def get_guessed_word(secret_word, guessed):
return "".join([letter if letter in guessed else "_" for letter in secret_word])
letters_guessed = set()
guess = ""
lives = 5
while True:
if is_guessed(secret_word,letters_guessed):
print("Congratulations you guessed {}.".format(secret_word))
break
elif lives == 0:
print("Out of lives the word was {}.".format(secret_word))
break
print("You have {} lives remaining".format(lives))
inp = input("Enter a letter ").upper()
if inp in letters_guessed:
print("Already picked that letter")
continue
letters_guessed.add(inp)
if inp.lower() in secret_word:
print("Good guess")
print(get_guessed_word(secret_word, letters_guessed))
else:
print("{} is not in the word".format(inp))
lives -= 1
答案 2 :(得分:0)
word = "dead"
right_answer = set() #1
def replace_star(): # this part is relevant to your quesiton
uncoverd = "" # first it makes a empty string
for char in word: # loops trough every character in the word
if char in right_answer: # if the character is in the set of right_answers
uncoverd += char # it adds the character to the empty string
else: # if is not
uncoverd += "*" # it add a '*'
return uncoverd # returns the new word with all the character replaced with eiter a '*' or the guesses right character
score = 10
while True:
uncoverd = replace_star()
print ("Word:",uncoverd)
answer = input("Guess one character of the word.\n>>")
if answer in word: # 2
print ("Spot on!")
right_answer.add(answer) # 3
if right_answer == set(word): # 4
print ("You Win!")
print ("The word was:", word)
break
else:
score -= 1
print ("Wrong")
print ("Score: '%s'"%score)
if score == 0:
print ("You Lose!")
break
通过使用set,您可以检查序列中的所有唯一项是否存在于另一个
中word
right_answer
集right_answer
是否等于单词中的字符集。