Skip to content

tarou0919/python-janken-game

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

python-janken-game

Pythonで作ったジャンケンゲームです。 import random import time

グラフ描画には「matplotlib」という外部ライブラリが必要ですが、

環境によってはインストールされていないため、今回は簡単なテキストグラフで表示します。

グラフコードは下に解説として記載します。

選択肢に対応する辞書を定義 (v5.0と同じ)

input_map = { "グー": "グー", "ぐー": "グー", "チョキ": "チョキ", "ちょき": "チョキ", "パー": "パー", "ぱー": "パー", "g": "グー", "c": "チョキ", "p": "パー", "0": "グー", "1": "チョキ", "2": "パー", "ぐ": "グー", "ち": "チョキ", "ぱ": "パー", } choices = ["グー", "チョキ", "パー"] WINNING_MOVES = {"グー": "パー", "チョキ": "グー", "パー": "チョキ"} LOSING_MOVES = {"グー": "チョキ", "チョキ": "パー", "パー": "グー"}

--- 【改良ポイント1】テキストベースのスコアグラフ表示関数 ---

def draw_text_chart(win, lose, draw): """勝敗数に基づき、コンソールに簡易的な棒グラフを表示する""" total = win + lose + draw if total == 0: print("まだゲームが行われていません。") return

# バーの最大長を決定(今回は20文字)
BAR_MAX_LEN = 20

# 比率を計算
win_ratio = win / total
lose_ratio = lose / total
draw_ratio = draw / total

# グラフの長さを計算
win_bar = int(win_ratio * BAR_MAX_LEN)
lose_bar = int(lose_ratio * BAR_MAX_LEN)
draw_bar = int(draw_ratio * BAR_MAX_LEN)

print("\n--- 視覚化された結果 ---")
print(f"勝率: {win_ratio:.1%} | {'█' * win_bar}{' ' * (BAR_MAX_LEN - win_bar)}")
print(f"敗率: {lose_ratio:.1%} | {'█' * lose_bar}{' ' * (BAR_MAX_LEN - lose_bar)}")
print(f"分率: {draw_ratio:.1%} | {'█' * draw_bar}{' ' * (BAR_MAX_LEN - draw_bar)}")
print("----------------------")

--- (get_computer_choice 関数はv5.0と同じため省略) ---

※ v5.0のget_computer_choice関数をここに含めてください

def get_computer_choice(difficulty, last_moves): """難易度、前回の手に基いてコンピューターの手を決定する"""

if difficulty == "ノーマル" or len(last_moves) < 3:
    return random.choice(choices)

if difficulty == "ハード":
    if len(last_moves) >= 3:
        m3, m2, m1 = last_moves[-3], last_moves[-2], last_moves[-1]
        predicted_next_move = None
        
        # 繰り返しパターン (3回連続同じ手)
        if m3 == m2 == m1:
            predicted_next_move = m1
        # 単純な交代パターン (例: グー → チョキ → グー)
        elif m3 == m1 and m3 != m2:
            predicted_next_move = m2
            
        if predicted_next_move:
            winning_move = WINNING_MOVES[predicted_next_move]
            draw_move = predicted_next_move
            losing_move = LOSING_MOVES[predicted_next_move]
            
            if random.random() < 0.85:
                return random.choices([winning_move, draw_move], weights=[6, 2.5], k=1)[0]
            else:
                return losing_move

if difficulty == "イージー":
    last_player_choice = last_moves[-1]
    losing_move = LOSING_MOVES[last_player_choice]
    draw_move = last_player_choice
    
    if random.random() < 0.8:
        return random.choices([losing_move, draw_move], weights=[5, 3], k=1)[0]
    else:
        return WINNING_MOVES[last_player_choice]

return random.choice(choices)

------------------------------------------------------------------

def janken_game(): win_comments = ["ナイス勝利!この調子!", "お見事!天才か!", "強すぎる!まさに神業!"] lose_comments = ["ドンマイ!次は勝てる!", "次こそリベンジだ!", "運が悪かっただけだよ!"] draw_comments = ["再戦だ!勝負はこれから!", "接戦だね!"]

# 難易度設定 (v5.0と同じため省略)
difficulty_choices = ["イージー", "ノーマル", "ハード"]
difficulty = None
while difficulty not in difficulty_choices:
    print("難易度を選んでください: イージー / ノーマル / ハード")
    choice = input(">> ").lower()
    for d in difficulty_choices:
        if choice == d.lower() or choice == d.lower()[0]:
            difficulty = d
            break
    if difficulty is None:
        print("❌ 不正な入力です。")
        
print(f"\n✅ 難易度: {difficulty} でゲームを開始します。")
print("----------------------------------------")

# 得点カウンターと履歴
win_count = 0
lose_count = 0
draw_count = 0
consecutive_wins = 0
last_moves = []

while True:
    # スコア表示
    print(f"📊 現在のスコア: {win_count}勝 {lose_count}敗 {draw_count}分 | {consecutive_wins}連勝中")
    
    player_input = input("じゃんけんの手を入力してください (終了する場合は「やめる」): ").lower()
    
    if player_input == "やめる":
        break
    
    if player_input in input_map:
        player_choice = input_map[player_input]
    else:
        print("❌ 入力が正しくありません。再度入力してください。")
        continue

    computer_choice = get_computer_choice(difficulty, last_moves)
    
    # 履歴を更新
    last_moves.append(player_choice)
    if len(last_moves) > 3:
        last_moves.pop(0)

    # 時間差演出 (省略)
    print("\n\tジャン...")
    time.sleep(0.5)
    print("\tケン...")
    time.sleep(0.5)
    print("\tポン!")
    time.sleep(0.2)
    
    # 勝敗判定と得点加算 (省略)
    result_message = ""
    comment = ""
    
    if player_choice == computer_choice:
        result_message = "結果: 引き分けです!"
        draw_count += 1
        consecutive_wins = 0
        comment = random.choice(draw_comments)
    elif (player_choice == "グー" and computer_choice == "チョキ") or \
         (player_choice == "チョキ" and computer_choice == "パー") or \
         (player_choice == "パー" and computer_choice == "グー"):
        result_message = "結果: あなたの勝ちです!🎉"
        win_count += 1
        consecutive_wins += 1
        comment = random.choice(win_comments)
    else:
        result_message = "結果: コンピューターの勝ちです!😭"
        lose_count += 1
        consecutive_wins = 0
        comment = random.choice(lose_comments)

    print(result_message)
    
    # 連続勝利による表彰メッセージ (省略)
    if consecutive_wins >= 3:
        print(f"👑✨ **{consecutive_wins}連勝中!** あなたはじゃんけんマスターです! ✨👑")
    else:
         print(f"💬 {comment}")
         
    print("-" * 40)
    
# ゲーム終了時の結果表示
print("\n--- ゲーム終了 ---")
print(f"最終結果: {win_count}勝 {lose_count}敗 {draw_count}引き分け")

# 【NEW】グラフの描画
draw_text_chart(win_count, lose_count, draw_count)

print("また遊んでね!")

if name == "main": janken_game()

About

Pythonで作ったジャンケンゲームです。

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors