一个没有正确回声的小骰子游戏

时间:2016-04-13 13:31:18

标签: php echo dice

这是一个骰子游戏,当用户选择一个号码并点击提交时,页面随机显示骰子上的数字,如果用户猜对了,应该说是,你说得对,否则会说对不起你是错误。但它不会回应“你猜对了!”当数字匹配时。问题出在哪儿?它说对不起是不对的。非常感谢你!

<html>
<body>
<h1>Dice Game!</h1>

<h1>"Please guess a number on the dice!"</h1>


<?php
if ($_POST['subBtn']) {
    $num = $_POST['number'];

    if ($num == "$roll") {
        $comment = "you guessed right!";
    } else if ($num != "$roll") {
        $comment = "sorry it's wrong!";
    } 
}
?>

<p>     
<form name="number" action="activity-dice-game.php" method="post">
<select name="number">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>
<input type="submit"name="subBtn" value="submit"/></input>
</form>
</p>

<?php
$roll = rand(1,6); 
echo "<p>You rolled a " . $roll . ". </p>";
echo "<img src=\"images/die" . $roll . ".gif\" alt=\"die image\">";
?>

</b> <? echo $comment; ?><br />

</body>
</html>

2 个答案:

答案 0 :(得分:0)

问题是当您加载表单$roll时,如果您检查用户提交的$num是否等于它,则设置为空!这意味着无论什么

if($num == $roll)

相当于:

if($num == null)

永远不会是真的!

只需将$roll = rand(1,6)放在脚本的顶部即可。

答案 1 :(得分:0)

这应该有效:

<html>
<body>
<h1>Dice Game!</h1>

<h1>"Please guess a number on the dice!"</h1>


<?php
if ($_POST['subBtn']) {
    $num = $_POST['number'];
    $roll = rand(1,6); 

    if ($num == "$roll") {
        $comment = "you guessed right!";
    } else if ($num != "$roll") {
        $comment = "sorry it's wrong!";
    } 
}
?>

<p>     
<form name="number" action="activity-dice-game.php" method="post">
<select name="number">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>
<input type="submit"name="subBtn" value="submit"/></input>
</form>
</p>

<?php
echo "<p>You rolled a " . $roll . ". </p>";
echo "<img src=\"images/die" . $roll . ".gif\" alt=\"die image\">";
?>

</b> <? echo $comment; ?><br />

</body>
</html>