PHP选择侧面有一个模具?

时间:2009-10-10 01:30:34

标签: php dice

我的代码的php部分没有做正确的操作 当用户提交他/她的号码时,例如,如果用户提交5,我希望rand功能随机输出5作为选择的号码;但是,我的代码有时会起作用,而在其他时候则不起作用。

<!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>
<center>
<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.

我有没有办法在这里比较兰德,而不必创建另一个变量?

$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";

如果用户选择5,我希望这个回显5,但我得到不同的值?

}


?>


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

3 个答案:

答案 0 :(得分:6)

由于rand(n,m)返回一个整数值,你应该可以这样做:

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

答案 1 :(得分:1)

我不确定你要做什么。每次加载此页面时,它将选择两个随机数,$ random和$ roll,如果它们相等,则打印它们。

如果您想获得用户输入,则需要使用$ _POST。

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

另外,你不需要提交按钮吗?

答案 2 :(得分:1)

想想你在这里要做的是要求用户输入骰子有多少边然后输出值是什么?这个问题没有多大意义......但如果以上是你要做的事情,这应该有用:

<强> 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"]);
}
?>

这将允许用户输入骰子所具有的边数,然后打印出与边数一起滚动的内容。