今日の目的
今日は Pythonでコマンドライン版のじゃんけんアプリ を作ることを目標にしました。
- 動くアプリを作る体験
- 勝敗判定のロジックを理解
- 今後のバージョンアップやGUI化に備えた基礎コードの作成
今日の到達点
ユーザーが数字で手を入力できる
コンピュータの手をランダムで生成できる
勝敗を判定して表示できる
コマンドラインで動作するシンプルなじゃんけんアプリ完成
import random
# 手のリスト
hands = ["グー", "チョキ", "パー"]
# ユーザー入力
user_input = input("手を選んでください (1:グー, 2:チョキ, 3:パー) >>> ")
if user_input not in ["1", "2", "3"]:
print("無効な入力です。1〜3を入力してください。")
exit()
user_hand = hands[int(user_input) - 1]
# コンピュータの手
computer_hand = random.choice(hands)
# 勝敗判定
if user_hand == computer_hand:
result = "引き分け"
elif (user_hand == "グー" and computer_hand == "チョキ") or \
(user_hand == "チョキ" and computer_hand == "パー") or \
(user_hand == "パー" and computer_hand == "グー"):
result = "あなたの勝ち!"
else:
result = "あなたの負け…"
# 結果表示
print(f"あなた: {user_hand} コンピュータ: {computer_hand}")
print(result)