在PHP猜数游戏中,尝试次数不会增加

时间:2013-04-02 02:48:18

标签: php html

下面的PHP脚本适用于数字猜谜游戏。隐藏字段用于存储猜测的数量,由变量$ tries表示。无论我如何尝试,猜测($尝试)的数量永远不会增加。有人能告诉我代码有什么问题吗? 玛利亚

<?php
$num=21;
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
if (!isset($_POST['guess'])) {
    $message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
    $message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
    $message="You WON 1 million point!";
} elseif ($_POST['guess']>$num) {
    $message="Try a smaller number";
} else {
    $message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/></p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

变化:

$tries=(isset($_POST['guess'])) ? $tries+1: 0;

要:

$tries=(isset($_POST['tries'])) ? $_POST['tries']+1: 0;

或者,根据条件,仅在猜测存在时递增,然后:

$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;

但是基于guess进行此操作将允许此人通过不输入数字来重置计数器;)

答案 1 :(得分:0)

当您尝试递增时,未定义

$tries。但是它可以在$_POST

中使用
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
// Change to
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;