私は現在「Python Programming for the Absolute Beginner ed 3」を読んでいて、課題の 1 つについて質問があります。
リストまたはタプルから単語を選択し、単語をごちゃまぜにして、ユーザーに単語を推測するように求める 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 タプルに対応する別のタプルを作成するというアイデアがあり、そこにヒントがあります。いいえ:
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)
いつものように、どんな助けも大歓迎です。