首先,请原谅我的英语。这是我的第二语言。
我正在尝试完成一个子手游戏。
这是我的粗略代码:
WORDS_LIST = ["I do not know"]
answer = list(random.choice(WORDS_LIST))
for char in answer:
if (char.isalpha()):
list1.append(char)
else:
list1.append("")
for char in list1:
if char == "":
guess_box.append(" ")
else:
guess_box.append("_")
print(' '.join(guess))
player_choice = input("\nguess a letter: ")
for item in range(0, len(ANSWER)):
if ANSWER[item] == player_choice:
guess_box[item] = player_choice
elif ANSWER[item][0] == player_choice[0]:
guess_box[item] = player_choice.upper()
您可以看到此打印出的图案
_ _ _ _ _ _ _ _ _ _
我的第一个大写字母有问题。我不确定如何将用户输入与列表中的单个大写字母进行比较。请帮助我解决这个问题,有人吗?
示例输出:
I do not know
答案 0 :(得分:2)
在评论发送时,您可以使用char.lower()
,但我看到了其他一些可以帮助您的内容,因此这里有一些提示和花絮。
首先,您可以使用列表理解功能来创建列表,因为它更短且易于阅读。
import random
WORDS_LIST = ["I do not know"]
# A list of characters
answer = list(random.choice(WORDS_LIST))
# A set of all the letters (converted to lowercase) that are contained
# in the answer. sets are significantly faster to search through.
letters = {char.lower() for char in answer if char.isalpha()}
guessed_letters = set()
# Note the syntax used above and here. This is called list
# comprehension.
# This is the same as:
# guess_box = []
# for char in answer:
# if char.isalpha():
# guess_box.append("_")
# else:
# guess_box.append(char) # Just use the space.
guess_box = ["_" if char.isalpha() else char for char in answer]
然后您可以处理输入逻辑:
print(' '.join(guess_box))
player_choice = input("\nguess a letter: ")
while player_choice:
print(f"You chose: {player_choice}")
# Convert user input to lower case
player_choice = player_choice.lower()
# If this letter was guessed before:
if player_choice in guessed_letters:
print("You guessed this letter already.")
else:
guessed_letters.add(player_choice)
# Check if this choice is in our word
if player_choice in letters:
# If we have this letter then change
# the guess_box
for index, val in enumerate(answer):
# Of the user input
if val.lower() == player_choice:
guess_box[index] = val
else: # The letter is wrong
print("That letter didn't fit")
print(' '.join(guess_box))
player_choice = input("\nguess a letter: ")