我是Python的初學者,我被困在練習中。在書中有一個叫做Word Jumple的遊戲。以下是我需要做的: 改善「Word Jumble」,使每個單詞與提示配對。 如果玩家卡住了,他應該能夠看到提示。 添加一個評分系統,可以獎勵解決雜亂問題的玩家而不要求提示。Python中的while循環需要說明
這裏是我做過什麼:
# 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.
爲什麼while循環丟失了所有當輸入爲「提示」,並直接進入else子句?
在此先感謝您的時間和幫助。
哦,上帝,我沒有意識到,當隨機字母從它實際上修改它取字...謝謝:) – Terrax
小心,小心,小心......以下任何一個語句都不會改變'word':'word [position]','word [:position]'或'word [(position + 1):]'的值。這三個返回從'word'的內容中提取的新字符串,但它們本身不影響'word'。不,改變'word'的是'word = word [:position] + word [(position + 1):''''中的'word ='。這取得右側的值,並將其分配到左側(在這種情況下恰好是「單詞」)。那有意義嗎? –
完美:)謝謝 – Terrax