Dice Rolling Program in PHP

I made a simple program where the user has to guess the value loaded by virtual cubes.

Here's the HTML and PHP:

<body>
<h2 id="heading"> We're gonna roll a dice! <br><small>And you have to guess which number the dice will roll.</small></h2>
<form action="" method="post">
<div id="test-container">
    <p>Select your guess: </p>
    <select class="form-control" id="select" name="dice">
        <option value="">Select...</option>
        <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>
</div>
<button id="submit" type="submit" type="button" name="roll" class="btn btn-primary">Roll!</button>
<?php
if(isset($_POST['roll']))
{
$dice = $_POST['dice'];
$rand = rand(1,6);
if($dice == $rand)
{
    echo "<br>" . "your guess is correct! The number rolled by the dice was " . $rand . "!";
}
else{
    echo "<br>" . "your guess is wrong! The number rolled by the dice was " . $rand . " but the number you entered was " . $dice . "!";
}

}

?>
</form>
</body>
</html>

      

The code itself works, but that's not a problem When I click submit, I want the next GIF (located between the button and the reflected output) to appear, and only play once without looping

I want it to be in-between the button and the echoed output

I've tried many ways to do this, but none of them work!

I understand that I need an image editor so that it doesn't get stuck forever. As for the display, the syntax is echo "<img src='handroll.gif'>"

, as I just learned.

+3


source to share


1 answer


Have you tried setting $ _POST [roll] to null after rolling the dice. As I see it, the value stays true always after the button is pressed, and you don't "reinitialize" that by itself.

if(isset($_POST['roll'])) {
// all that you need to do

// as the last line or something like this
$_POST['roll'] = null;
}

      



Because usually when the form is submitted, the form data or the submit status is reset as well as the session value.

If the above doesn't work, you can also try creating a form / input type = submit setting. Easier to manage button clicks via jquery / js.

+2


source







All Articles