我是Python的初学者,我正忙于一项练习。书中有一个游戏叫做单词跳跃。我需要做的是: 改进“单词混乱”,使每个单词都有一个提示。 玩家应该能够看到提示,如果他或她卡住了。 增加一个计分系统,奖励那些不需要提示就解决混乱的玩家。在
下面是我所做的:
# 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", "difficult", "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 =""
hint = "False"
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 != "":
if guess == "hint" and word == "python":
hint = "True"
print("It's a snake")
guess = input("Your guess: ")
elif guess == "hint" and word == "jumble":
hint = "True"
print("It's a game")
guess = input("Your guess: ")
elif guess == "hint" and word == "easy":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and word == "difficulty":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and word == "answer":
hint = "True"
print("It's the opposite of question")
guess = input("Your guess: ")
elif guess == "hint" and word == "xylophone":
hint = "True"
print("Don't know WTF is that")
guess = input("Your guess: ")
else:
print("Sorry, that's not it.")
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
if hint == "False":
print("Great! You did it without a hint")
else:
print("Dat hint, man")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
因此,我有了这个:
Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) The jumble is: jbelum Your guess: hint Sorry, that's not it. Your guess: jumble That's it! You guessed it! Great! You did it without a hint Thanks for playing. Press the enter key to exit.
为什么当输入是“hint”并直接指向else子句时while循环会丢失所有内容?在
提前感谢您的时间和帮助。在
有一种方法可以简化程序:
问题是,当您进入
while guess != correct and guess != "":
循环时,word
已经完全混乱了。因此,在该循环中的所有if
和elif
语句中,word
永远不会等于列表中的六个单词中的一个。在要解决此问题,请在以下语句中用
correct
替换word
:音乐编码器是对的,解决了你的问题。为了使代码变得更好,您还需要对代码进行一些更改:
不要将字符串用于提示变量,请使用布尔值:
取而代之的是:
使用:
^{pr2}$也可以重写while循环一点点
只有一次,不是每一次。在
另外,改变结果打印一点,因为这样它会打印提示信息,即使你输入空字符串退出游戏。在
所以它看起来像这样:
相关问题 更多 >
编程相关推荐