开发者

PHP choose the side a die has?

The php section of my code is not doing the correct operations when the user submits his/her number, for example, if the user submits 5, I want the rand function to randomly output 5 as the number selected; however, my code sometimes works and at other times does not work.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">


<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>
choose a die number
</title>
</head>
<c开发者_运维知识库enter>
<body>
<h1>Choose a die number</h1>
<form method = "post" action="choosedie.php"/>
<!--If the user selects a number of sides the die is suppose to have
rand should go through and pick the number randomly, and echo out the 
number that was entered by the user-->

Please choose how many sides a die should have from 1 through 6:
<br/>
<input type = "text" name = "roll"/>
<?php


//Roll a random dice from 1 through 6:
$roll = rand(1,6);
// Add random variable to do comparison on.

Is there a way for me to just compare rand here, without having to create another variable?

$random  = rand(1,6);

// If $roll is equal to $random echo the output out to the user.
If ($roll == $random)
{
echo "<br/>Here is the random $roll with the appropriate maximum value $random\n";

If the user selects 5, I want this to echo out 5, but I am getting different values?

}


?>


</body>
</center>
</html>


Since rand(n,m) returns an integer value, you should be able to do thusly:

if(rand(1,6) == $guess){
    echo "Congratulations - your guess of $guess was right!";
}
else{
    echo "No dice - better luck next time.";
}


I think what you're trying to do here is ask the user to input how many sides the die has and then output what the value is? The question doesn't make a lot of sense... but if the above is what you're trying to do, this should work:

choosedie.php

<h1>Choose a die number</h1>
<form method = "post" action="choosedie.php"/> 
Please choose how many sides a die should have from 1 through 6:
<br/>
<input type="text" name="roll"/>
<input type="submit" value="Submit" />
</form>

<?php
if (isset($_POST["roll"])) {
  $roll = rand(1, $_POST["roll"]);
  printf("A %s was rolled, with a maximum roll of %s", $roll, $_POST["roll"]);
}
?>

This will allow the user to input the number of sides a die has, and then print out what was rolled along with the number of sides.


I'm not sure what you're trying to do. Each time this page is loaded, it will pick two random numbers, $random and $roll, and if they are equal, print them.

If you want to get the users input, you'll need to use $_POST.

$users_dice_roll = $_POST["roll"];
$random_dice_roll = rand(1,6);
if($random_dice_roll == $users_dice_roll){
    echo "You rolled: $users_guess";
}

Also, don't you need a submit button?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜