1
0

More than 3 years have passed since last update.

【PHP】課題14-15ジャンケンゲーム

Last updated at Posted at 2021-05-28

image.png

1・画面のレイアウトは画像の通り
2・ユーザーはグー・チョキ・パーのいずれかをラジオボタンで入力する
3・ユーザーの手がsubmitされたら、ユーザーの手を表示する
4・ユーザーの手がsubmitされたら、コンピュータの手をグー・チョキ・パーからランダムに選択し、表示する
5・ユーザーの手がsubmitされたら、じゃんけんの勝敗を判定し、出力する

<?php
// じゃんけんの手を配列に代入
$hands = ['グー', 'チョキ', 'パー'];

// プレイヤーの手がPOSTされたら
if (isset($_POST['hand'])) {
    // プレイヤーの手を代入
    $playerHand = $_POST['hand'];

    // PCの手をランダムで選択
    $key = array_rand($hands);
    $pcHand = $hands[$key];

    // 勝敗を判定
    if ($playerHand == $pcHand) {
        $result ='あいこ';
    } elseif ($playerHand == 'グー' && $pcHand == 'チョキ') {
        $result = '勝ち';
    } elseif ($playerHand == 'チョキ' && $pcHand == 'パー') {
        $result = '勝ち';
    } elseif ($playerHand == 'パー' && $pcHand == 'グー') {
        $result = '勝ち';
    } else {
        $result = '負け';
    }
}

?>

<!DOCTYPE html>
<html lang="ja">
<head>
    <title>じゃんけん</title>
</head>
<body>

  <h1>じゃんけん勝負</h1>

  <?php if($_SERVER['REQUEST_METHOD'] === 'POST'){ ?>   
  <dl>
    <dt>自分:<?php echo $playerHand;  ?> </dt>
    <dt>相手:<?php echo $pcHand;  ?></dt>
    <dt>結果:<?php echo $result;  ?></dt>
  </dl>

  <?php
  }

  ?>

  <form method="post">
      <label> グー <input type="radio" name="hand" value="グー" required ></label>
      <label>チョキ <input type="radio" name="hand" value="チョキ" required ></label>
      <label>パー <input type="radio" name="hand"  value="パー" required ></label>
      <input style="display:block;" type="submit"  value="勝負">

  </form>

  <?php if($_SERVER['REQUEST_METHOD'] === 'POST'){ ?>   

  <p><a href="rock_paper_scissors.php">初画面</a></p>
  <?php
  }

  ?>

</div>
</body>
</html>
1
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
1
0