我对PHP有点问题。我用PHP创建了一个小游戏,其中两个玩家必须选择一个数字,而最接近的玩家必须获胜。
以下是规则:
玩家1选择最小数字(生成要查找的随机数)检查
玩家2选择最大数量(生成要查找的随机数)检查
两名球员选择他们的数字(在最小值和最大值之间)
最接近随机生成的数字(最小值和最大值之间)的玩家赢得游戏
这是我的剧本
<form action="" method="post">
<input name="min" type="number" placeholder="Min" />
<input name="max" type="number" placeholder="Max" />
<input name="player1" type="number" placeholder="player1" />
<input name="player2" type="number" placeholder="player2" />
<input name="submit" type="submit" />
</form>
<?php
// Variables
$min = $_POST['min'];
$max = $_POST['max'];
$player1 = $_POST['player1'];
$player2 = $_POST['player2'];
// Get Random Number
function getRandomNumber($min, $max) {
return mt_rand($min, $max);
}
// Submit Form
if (isset($_POST['submit'])) {
echo "The random number is " . getRandomNumber($min, $max) . "<br />";
echo "Player 1: " . $player1 . "<br />";
echo "Player 2: " . $player2 . "<br />";
}
?>
提前感谢您的回复。
答案 0 :(得分:1)
毫无疑问,你已经找到了问题的答案,但如果没有,那么这可能会有所帮助。
$min = intval( $_POST['min'] );
$max = intval( $_POST['max'] );
$player1 = intval( $_POST['player1'] );
$player2 = intval( $_POST['player2'] );
function getRandomNumber( $min, $max ) {
return mt_rand($min, $max);
}
if ( isset( $_POST['submit'] ) ) {
$random=getRandomNumber( $min, $max );
$results=array();
$results['player1']=abs( $random-$player1 );
$results['player2']=abs( $random-$player2 );
$low=min( $results );
$high=max( $results );
$winner=array_search( $low, $results );
$loser=array_search( $high, $results );
if( $low!==$high ){
echo ucfirst( $winner ).' wins by guessing '.$_POST[ $winner ].' and being '.$low.' away from the random number of '.$random.'.
'.ucfirst( $loser ).' lost by guessing '.$_POST[ $loser ].' which was '.$high.' from the designated random number...';
} else {
echo 'It\'s a draw!!! Both players guessed '.$_POST[ $winner ].' which is '.$low.' away from the target of '.$random;
}
}
答案 1 :(得分:0)
如果没有某种持久性数据,这是行不通的。您有一台服务器,每个用户都有一个会话。但是,如果没有中间握手,你就无法与其他用户分享会话。
我建议将输入发布到数据库。数据库还必须保持每个玩家的状态(如果他们已经提交或未提交)。
我进一步建议您使用JavaScript和AJAX来控制每个客户端,并轮询服务器的状态。
答案 2 :(得分:0)
<?php
// Variables
$min = $_POST['min'];
$max = $_POST['max'];
$player1 = $_POST['player1'];
$player2 = $_POST['player2'];
// Get Random Number
function getRandomNumber($min, $max) {
return mt_rand($min, $max);
}
// Submit Form
if (isset($_POST['submit'])) {
$rd = getRandomNumber($min, $max);
$p1 = $player1 - $rd;
$p2 = $player2 - $rd;
echo "The random number is " . $rd . "<br />";
echo "Player 1: " . $player1 . "<br />";
echo "Player 2: " . $player2 . "<br />";
if($p1<$p2){
echo "Player 1 wins!";
}else{
echo "Player2 wins!";
}
}
?>