我目前正在阅读“Python Programming for the Absolute Beginner ed 3”,我对其中一个挑战有疑问。
我正在创建一个 Word Jumble 游戏,该游戏将从列表或元组中选择一个单词,将单词混杂并要求用户猜测该单词。
# Word Jumble
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# Create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficulty", "answer", "xylophone")
# Pick one word randomly from the sequence
word = random.choice(WORDS)
# Create a variable to use later to see if the guess is correct
correct = word
# Create a jumbled version of the word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
# Start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
""")
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing!")
input("\n\nPress the enter key to exit.")
这是书中的原始代码。挑战在于在游戏中实施提示和评分系统。我有一个想法,即创建另一个与 WORDS 元组相对应的元组,并在那里有提示。IE:
hints = ("*insert hint for python*",
"*insert hint for jumble*",
"*insert hint for easy*",
"*insert hint for difficulty*",
"*insert hint for answer*",
"*insert hint for xylophone*")
我想做的是找到 random.choice 词的索引,所以这就是我尝试的。
index = word.index(WORDS)
print(index)
我在想这会返回 WORDS 元组的整数,并允许我使用以下方法打印提示:
print(hints[index])
然而,我错了。这可能吗?我让它工作了,但它是一个长长的 if、elif 语句列表,例如:
if guess == "hint" or guess == "Hint" or guess == "HINT":
if hint == "python":
print(HINTS[0])
我知道有些人可能会说,“既然它有效,你为什么不坚持下去呢?” 我知道我可以做到这一点,但我学习 python 或编程的目的通常是知道如何以各种方式完成设定的任务。
--这部分是次要的,不需要回复,除非你想——
另外我的评分系统如下,以防有人对如何改进或做得好有想法。
这个想法是您的分数从 100 开始,如果您使用提示,您将失去总分的 50%。每次猜测都会从总分中扣除 10 分。如果您的分数达到负数,它将被设置为 0。这就是我的做法。
score = 100
guesses = 1
这是在使用提示后添加的。
score //= 2
猜测出来之后。
guesses += 1
最后,如果猜对了。
if guess == correct:
print("That's it! You guessed it!\n")
score = score - (guesses - 1) * 10
if score <= 0:
score = 0
print("\nYour score is: ", score)
与往常一样,非常感谢任何帮助。