我是编程新手,但我已经开始教几个月了。我写了一个猜词游戏程序。该计划做了以下事情:
dictionary
的预定义词组中选择一个词。["_", "_", "_", "H", "_", "_"]
。["_", "_", "_", "H", "_", "_"]
,这样用户就可以跟踪他/她的位置。 以下是代码:
import random
dictionary = ("CROWS", "GOAT", "MONKEY", "COW", "HORSE", "SNAKE")
answer = random.choice(dictionary)
answer_length = len(answer)
victory = True
print("""
I have chosen a word. Your job is to guess it. I will help you
keep track.
""")
print("The word I have chosen is {} letters long.\n".format(answer_length))
underscores = []
for character in answer:
underscores.append("_")
print(underscores)
while victory:
guess = input("\nPlease guess a letter: ").strip().capitalize()
def pos(guess):
position = 0
for letter in answer:
if letter != guess:
position += 1
else:
print("Correct!")
break
return position
def update_board(x):
global underscores
if guess in answer:
underscores[x] = guess
else:
print("This letter is not in the word")
return underscores
def winner():
global underscores
global victory
if "_" not in underscores:
print("YOU HAVE WON!")
victory = False
x = pos(guess)
print(update_board(x))
winner()
现在,我遇到的问题是:程序工作正常,提供计算机从字典中选择的单词中没有任何重复的字母。您会注意到字典中的单词都由唯一字符组成。但是,如果字典中包含单词“CHICKEN”,则程序可能会遇到问题。
想象一下,电脑选择了'CHICKEN',然后你猜到了字母'C'。该计划将返回:
Correct!
["C", "_", "_", "_", "_", "_", "_"]
此外,如果你再次猜到C,它就会打印
Correct!
["C", "_", "_", "_", "_", "_", "_"]
一次。理想情况下,我想要它做的是在用户第一次猜到'C'时返回["C", "_", "_", "C", "_", "_", "_"]
。目前,只有字典中的所有单词都没有任何重复出现的字符时,游戏才能运行。
您可以提供任何帮助,我们将不胜感激。谢谢!
答案 0 :(得分:2)
一旦在pos(guess)
中找到一个,我们就会停下来检查是否有其他事件发生。因此,您只能获得第一次出现。显然,要解决这个问题,不要在找到东西时停下来。而是每次都完整地完成这个词。
E.g。在pos(guess)
中,返回在单词中找到字母的索引列表,并在update_board(x)
循环遍历您获得的索引,而不是仅用猜测替换一个下划线。
答案 1 :(得分:1)
您可以使用数组来解决它:
import random
dictionary = ("CROWS","CHICKEN")
answer = random.choice(dictionary)
answer_length = len(answer)
victory = True
print("""
I have chosen a word. Your job is to guess it. I will help you
keep track.
""")
print("The word I have chosen is {} letters long.\n".format(answer_length))
underscores = []
for character in answer:
underscores.append("_")
print(underscores)
ar=[]
while victory:
guess = input("\nPlease guess a letter: ").strip().capitalize()
def pos(guess):
position = 0
for letter in answer:
if letter != guess:
position += 1
else:
print("Correct!")
ar.append(position)
position += 1
return ar
def update_board(x):
global underscores
if guess in answer:
underscores[x] = guess
else:
print("This letter is not in the word")
return underscores
def winner():
global underscores
global victory
if "_" not in underscores:
print("YOU HAVE WON!")
victory = False
pos(guess)
for x in ar:
print(update_board(x))
del ar [:]
winner()