- basename: documentation ( source)
- mt_rand: documentation ( source)
- end: documentation ( source)
- session_start: documentation ( source)
- define: documentation ( source)
- printf: documentation ( source)
<?php
session_start();
define('ROCK' , 0);
define('SCISSORS', 1);
define('PAPER' , 2);
// セッション初期化
if (!isset($_SESSION['result'])) {
$_SESSION['result'] = array();
}
// 入力が渡されたとき
if (isset($_POST['you'])) {
// CPUの手を生成
$cpu = mt_rand(0, 2);
// 不正アクセスで変な値がPOSTされても絶対に0~2の整数になるようにする
$you = (int)$_POST['you'] % 3;
// 結果を判定
switch (true) {
case $you === $cpu :
$msg = 'あいこ';
$_SESSION['result'][] = 'あいこ';
break;
case $you === ROCK && $cpu === SCISSORS :
case $you === SCISSORS && $cpu === PAPER :
case $you === PAPER && $cpu === ROCK :
$msg = 'あなたの勝ちです';
$_SESSION['result'][] = '勝ち';
break;
default:
$msg = 'あなたの負けです';
$_SESSION['result'][] = '負け';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>じゃんけん</title>
</head>
<body>
<form method="post" action="<?php echo basename($_SERVER['SCRIPT_NAME']); ?>">
<fieldset>
<legend>PHPと勝負!</legend>
<div><input type="radio" name="you" value="0" />グー</div>
<div><input type="radio" name="you" value="1" />チョキ</div>
<div><input type="radio" name="you" value="2" />パー</div>
</fieldset>
</form>
<fieldset>
<legend>結果</legend>
<?php
if ($_SESSION['result']) {
$r_you = end($_SESSION['result']);
$r_cpu = $s_you === '勝ち' ? '負け' : '勝ち' ;
echo '<p>'.$msg.'</p>'.PHP_EOL;
echo '<table border="1">'.PHP_EOL;
echo '<tr><th>あなた</th><th>vs</th><th>PHP</th></tr>'.PHP_EOL;
foreach ($_SESSION['result'] as $result) {
printf('<tr><td>%s</td><td> </td><td>%s</td></tr>', $r_you, $r_cpu);
}
echo '</table>'.PHP_EOL;
} else {
echo '結果がまだありません。'.PHP_EOL;
}
?>
</fieldset>
</body>
</html>