我有5个变量生成一个随机数,第六个变量是用户输入。 然后我检查用户输入$ userNum是否匹配任何随机数。我知道这是一个愚蠢的游戏,但我只是搞乱了解更多PHP
必须有一种更简单的方法来做到这一点。
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
if($userNum == $spot1)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot2)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot3)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot4)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot5)
{
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
}
答案 0 :(得分:1)
我会制作一系列斑点
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
// Make an array of the spots.
$spots = array($spot1, $spot2, $spot3, $spot4, $spot5);
if(in_array($userNum, $spots)) {
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
对于50个或更多点,您可以动态地在数组中插入值,假设您在真正的php代码中使用rand()函数:
$spots = Array();
for ($i = 0; $i < 50; $i ++) {
array_push($spots, rand(1,100));
}
或:
for ($i = 0; $i < 50; $i ++) {
$spots[$i] = rand(1,100);
}
答案 1 :(得分:1)
您不需要将数据存储在数组中,也不需要使用简单的循环。
<?php
if(isset($_POST['submit'])){
$userNum = (int) $_POST['userNum'];
$hitMine = false;
for($i = 1; $i <= 5; $i++){
$randNum = rand(1, 100);
echo $randNum . '<br />';
if($randNum == $userNum){
$hitMine = true;
}
}
if($hitMine == true){
echo "you hit a mine!";
}
}
?>
答案 2 :(得分:0)
您可以使用Switch Case代替if else,以使其更好更快。
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
Switch($userNum)
{
Case $spot1:
Case $spot2:
Case $spot3:
Case $spot4:
Case $spot5:
echo "you hit a mine!";
break;
default: echo "you lived!";
break;
}
}
答案 3 :(得分:0)
只需将有效位置存储在数组中即可。
$myhashmap = array();
$myhashmap['spot1'] = true;
$myhashmap['spot2'] = true;
if(isset($myhashmap[$userNum] ) )
{
echo "you hit a mine!";
exit();
}
以下是有关PHP数组的更多信息的链接:http://www.tutorialspoint.com/php/php_arrays.htm