猜字游戏-如何打印空白



我在制作猜谜游戏时遇到了麻烦。当你猜对一个字母时,它会打印出这个字母,而不是空格(_)。

newBlanks = secret[location]不起作用,因为它没有将新的猜测保存在列表blanks中。你可以试着编辑列表,而不是使一个新变量。

print("Hello user! Would you like to guess what word I am thinking of? You may guess one letter at a time!")
print("You also only have 10 guesses!")
secret = "monkey"
count = 10
blanks = ["_"]*len(secret)
print(*blanks)
while count > 0: 
guess = input("What letter would you like to guess? ")
# check if the letter is in the word
if guess in secret:
location = secret.find(guess)
blanks[location] = guess  # Edit the list
print(f"(guessed {guess}) --> ",*blanks)  # print updated list
count = count - 1
# if NOT, tell the player it isn't in the word
else:
print ("that letter is not in the word")
count = count - 1

当正确猜测时,您没有更新blanks。这就是为什么你的猜测没有被保存/显示。

代码:

#Question 3 - Strings 
#get guess from user
print("Hello user! Would you like to guess what word I am thinking of? You may guess one letter at a time!")
print("You also only have 10 guesses!")
secret = "monkey"
blanks = ["_"]*len(secret)
print(*blanks)
count = 10 
while count > 0: 
# if user guessed all letters, they win!
if "".join(blanks) == secret:
print("You win!")
break
guess = input("What letter would you like to guess?")
#check if the letter is in the word
if guess in secret:
location = secret.find(guess)
# store correct guess
blanks[location] = guess
# output new blanks -> sample: _ o _ _ _ _
print(" ".join(blanks))
count = count - 1
#if NOT tell the player it isn't in the word
else:
print ("that letter is not in the word")
count = count - 1

我还添加了一条消息,当用户猜出整个单词时打印。

编码快乐!

我想这对你有帮助。

#Question 3 - Strings
#get guess from user
print("Hello user! Would you like to guess what word I am thinking of? You may guess one letter at a time!")
print("You also only have 10 guesses!")
secret = "good"
secret = list(secret)
newBlanks = ["_"]*len(secret)
print(*newBlanks)
count = 10
while count > 0:
guess = input("What letter would you like to guess?")
#check if the letter is in the word
if guess in secret:
location = secret.index(guess)
secret[location] = '_'
newBlanks[location] = guess
print(newBlanks)
# print(set(secret))
count = count - 1
#if NOT tell the player it isn't in the word
else:
print("that letter is not in the word")
count = count - 1
if set(secret) == {'_'}:
print("You have successfully guessed all the letters!")
break