LoginSignup
0
0

More than 1 year has passed since last update.

[Hangman] 単語当てゲームを実装してみよう(Python)

Posted at

目的

PythonでHangmanゲームを実装できる

Hangmanとは

「ハングマン」とは、単語当てゲームの一種だよ。
プレイヤーはコンピューターが選んだ単語を当てることを目指しますが、当てに失敗すると、次第にマンが描かれていくんだ!
当てるのに失敗しすぎると、マンが完全に描かれたところでゲームは終了するよ。

ゲーム進行の例

  1. 単語リストを作成
  2. 単語リストからランダムに単語を選択
  3. 選択された単語を表示するための空の文字列リストを作成
  4. プレイヤーからの文字入力を受け付け
  5. 入力された文字が選択された単語に含まれているかどうかを確認
  6. 入力された文字が選択された単語に含まれている場合、文字列リストにその文字を追加
  7. 入力された文字が選択された単語に含まれていない場合、マンに一部を描く
  8. ゲームの終了条件を確認する。単語が完全に当てられたか、マンが完全に描かれたかを確認

🐰実装してみよう🐰

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)

参考

Pythonを使用したハングマンゲーム

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0