Python じゃんけんゲーム

Python でじゃんけんゲームを作成します。ランダムな選択、ユーザー入力の検証、リレーショナル ルール マッピングをマスターします。

エディターで試してみる

概要

じゃんけんは、標準的なゲーム ロジックの課題です。特定のゲーム ルールに照らして入力を検証し、勝者を決定する必要があります。

面倒な多層の if/else ラダーを記述する代わりに、マッピング ディクショナリを使用してルールを実装できます。これは拡張性が高く、ルールを簡単に拡張できます (Lizard や Spock の追加など)。

スクリプトは標準的な選択肢からランダムに選択し、それをプレイヤーの選択と比較し、スコアの更新を含む結果を出力します。

コードと実行の出力

辞書ルールのマッチングとランダム モジュールを示すジャンケン スクリプト。

import random

def get_winner(player, computer):
    if player == computer:
        return "tie"
        
    # Dictionary mapping choice -> what it beats
    winning_rules = {
        "rock": "scissors",
        "paper": "rock",
        "scissors": "paper"
    }
    
    if winning_rules[player] == computer:
        return "player"
    return "computer"

def play_game():
    choices = ["rock", "paper", "scissors"]
    # Mocking player selections
    player_moves = ["rock", "paper", "scissors"]
    
    print("Rock, Paper, Scissors Game!")
    
    # Seed generator for deterministic outputs
    random.seed(11)
    
    for player_move in player_moves:
        computer_move = random.choice(choices)
        winner = get_winner(player_move, computer_move)
        
        print(f"\nPlayer chose:   {player_move.capitalize()}")
        print(f"Computer chose: {computer_move.capitalize()}")
        
        if winner == "tie":
            print("Result: It is a Tie!")
        elif winner == "player":
            print("Result: Player Wins!")
        else:
            print("Result: Computer Wins!")

play_game()
端子出力
Rock, Paper, Scissors Game!

Player chose:   Rock
Computer chose: Scissors
Result: Player Wins!

Player chose:   Paper
Computer chose: Paper
Result: It is a Tie!

Player chose:   Scissors
Computer chose: Rock
Result: Computer Wins!

段階的な実装

  • 決定的なルール検証マトリックス
  • 乱数セレクター エンジン
  • 教育制御フローロジックプロジェクト

よくある質問

これをジャンケン、トカゲ、スポックに拡張するにはどうすればよいでしょうか?

単純に「wining_rules」辞書マッピングを拡張して、各キーがそれが打ち負かす要素のリストを指すようにします。たとえば、「岩」: [「はさみ」、「トカゲ」]`。

ユーザーが終了するまでゲームを無限に実行するにはどうすればよいですか?

インタラクション ロジックを `while True:` ループ内にラップし、プレーヤーが 'quit' を入力すると実行を中止します。

関連トピック