Search code examples
phpechodice

A little dice game that does not echo properly


This is a dice game, when the user chooses a number and hit submit, the page randomly shows a number on the dice and if the user guessed right it should say yes you got it right, otherwise it will say sorry you are wrong. But it would not echo "you guessed right!" when the number matches. Where is the problem? It says sorry it's wrong no matter what. Thank you so much!

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

Solution

  • The issue is that when you load the form $roll is set to nothing when you check to see if the $num the user submitted is equal to it! That means that no matter what

    if($num == $roll)
    

    Is equivalent to:

    if($num == null)
    

    Which will never be true!

    Just put $roll = rand(1,6) at the top of the script.