目的
PythonでHangmanゲームを実装できる
Hangmanとは
「ハングマン」とは、単語当てゲームの一種だよ。
プレイヤーはコンピューターが選んだ単語を当てることを目指しますが、当てに失敗すると、次第にマンが描かれていくんだ!
当てるのに失敗しすぎると、マンが完全に描かれたところでゲームは終了するよ。
ゲーム進行の例
- 単語リストを作成
- 単語リストからランダムに単語を選択
- 選択された単語を表示するための空の文字列リストを作成
- プレイヤーからの文字入力を受け付け
- 入力された文字が選択された単語に含まれているかどうかを確認
- 入力された文字が選択された単語に含まれている場合、文字列リストにその文字を追加
- 入力された文字が選択された単語に含まれていない場合、マンに一部を描く
- ゲームの終了条件を確認する。単語が完全に当てられたか、マンが完全に描かれたかを確認
🐰実装してみよう🐰
hangman.py
import random
word_list = ["python", "swift", "java", "kotlin", "javascript", "perl", "scala", "dart", "cobol", "fortran", "ruby"]
word = random.choice(word_list)
display = ["_"] * len(word)
used_letters = []
tries = 6
# while: display内に "_" があり、かつ triesが0より大きい間、ゲームを繰り返す
while "_" in display and tries > 0:
print(" ".join(display))
print("Tries left:", tries)
letter = input("Guess a letter: ").lower()
# if: 入力された文字が used_lettersに含まれているかどうか、
# またはwordに含まれているかどうかを判定
if letter in used_letters:
print("You already used that letter.")
elif letter in word:
# indices: word内に含まれている文字のインデックスを格納
indices = [i for i, ltr in enumerate(word) if ltr == letter]
# for: indices内のインデックスに対応する文字を displayに追加
for index in indices:
display[index] = letter
used_letters.append(letter)
else:
tries -= 1
used_letters.append(letter)
print("Incorrect.")
# if文: display内に "_" がないかどうかを判定し、ゲームの結果を表示します。
if "_" not in display:
print(" ".join(display))
print("You win! The word was", word)
else:
print("You lose! The word was", word)