LoginSignup
4
0

More than 1 year has passed since last update.

じゃんけんプログラムをJavaScriptで書く

Last updated at Posted at 2022-03-27

私が通っているスクールで、じゃんけんプログラム書いてこい!っていう課題が出たので、ついでに記事にします。もっとこうした方がきれいに書けるよ!記事として読みやすいよ!等ありましたら、是非コメントお願いします。
スクールHP↓
SUNABACO

じゃんけんプログラム

自分の手をエディターに入力すると、コンピュータの手に対し、勝ちか負けを判定し、コンソールに出力する。

条件整理

  1. 自分の手を決める
  2. 相手の手を決める
    等確率かつランダムでグー、チョキ、パーを出力する。
  3. 自分の手と相手の手を比べ、勝敗を決める
    勝ちのパターン、負けのパターン、引き分けのパターンで条件分岐。
  4. 1~3をまとめる

実際に解いてみる

  1. 自分の手を決める。

    とりあえず、、、

    const yourHand === "グー"
    
  2. 相手の手を決める

    Math.random()で0以上1未満の乱数を発生させることができるらしい。今回はこれを利用する。
    (https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
    出力された乱数のうち、

    • 1/3未満で"グー"
    • 1/3以上3/2未満で"チョキ"
    • 2/3以上1未満で"パー"

    で出力されるようにする。

    let oponentHand = Math.random();
    
    if (opponentHand < 1 / 3) {
      opponentHand = "グー";
    } else if (opponentHand < 3 / 2) {
      opponentHand = "チョキ";
    } else if (opponentHand < 1) {
      opponentHand = "パー";
    }
    
  3. 自分の手と相手の手を比べ、勝敗を決める
      if (yourHand === oponentHand) {
        console.log("引き分け");
      } else if (oponentHand === "グー") {
        if (yourHand === "パー") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け!");
        }
      } else if (oponentHand === "チョキ") {
        if (yourHand === "グー") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け!");
        }
      } else if (oponentHand === "パー") {
        if (yourHand === "チョキ") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け");
        }
      }
    };
    
  4. 1~3をまとめる

    最後に上記のコードを一つの関数にまとめて完成。1で定義した変数yourHandはjankenFunの引数として書き換えた。

    const jankenFun = (yourHand) => {
      let oponentHand = Math.random();
      if (oponentHand < 1/3) {
        oponentHand = "グー";
        console.log(oponentHand,"相手の手");
      } else if (oponentHand < 2/3) {
        oponentHand = "チョキ";
        console.log(oponentHand,"相手の手");
      } else if (oponentHand < 1) {
        oponentHand = "パー";
        console.log(oponentHand,"相手の手");
      }
      if (yourHand === oponentHand) {
        console.log("引き分け");
      } else if (oponentHand === "グー") {
        if (yourHand === "パー") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け!");
        }
      } else if (oponentHand === "チョキ") {
        if (yourHand === "グー") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け!");
        }
      } else if (oponentHand === "パー") {
        if (yourHand === "チョキ") {
          console.log("あなたの勝ち!");
        } else {
          console.log("あなたの負け");
        }
      }
    };
    // 引数に自分の手を入力
    
    jankenFun("グー");
    
4
0
4

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
4
0