好吧,我创建了一个简单的上/下游戏脚本。它的工作正常,但我想将用户操作限制为3。这意味着用户将不得不猜测3次移动的次数。在第三个动作中,我将执行查询并将用户保存到mysql。如何限制动作/动作?
<?php
session_start();
function Start_Again() {
$number = rand(1,100);
$_SESSION['higherlower'] = $number;
echo "Select a Number below.";
Display_Form();
}
function Display_Form() {
echo "<table>";
for ($num=1;$num < 101;$num++) {
if (!preg_match("/(.*?)0/", $num)) { echo "<td><a href=\"?number=".$num."\">".$num."</td>"; }
else { echo "<td><a href=\"?number=".$num."\">".$num."</td></tr><tr>"; }
}
echo "</table>";
}
if (isset($_GET['number'])) {
$User_Number = $_GET['number'];
$Actual_Number = $_SESSION['higherlower'];
$count = 0;
if ($User_Number < $Actual_Number) { echo "Higher"; $count + 1; Display_Form(); }
elseif ($User_Number > $Actual_Number) { echo "Lower"; $count + 1; Display_Form(); }
elseif ($User_Number == $Actual_Number) { echo "Bingo, Correct Guess!<br>"; Start_Again(); }
echo $count;
}elseif (!isset($_POST['higherlower'])) { Start_Again(); }
?>
答案 0 :(得分:1)
初始化游戏时,只需在会话中存储尝试次数即可。
$_SESSION['tries'] = 3;
然后,当用户选择一个数字时,降低尝试次数并检查它是否为0。
$_SESSION['tries']--;
if ($_SESSION['tries'] <= 0) {
die("Enough! You've been clicking numbers all afternoon.");
}
<?php
/**
* Higher-lower game
*/
if (!isset($_SESSION)) {
session_start();
}
function Start_Again() {
$number = rand(1,100);
$_SESSION['higherlower'] = $number;
$_SESSION['tries'] = 3;
echo "Select a Number below.";
Display_Form();
}
function Display_Form() {
echo "<table>";
$chunks = array_chunc(range(1, 100), 10);
foreach ($chunks as $chunk) {
echo "<tr>";
foreach ($chunk as $num) {
echo "<td><a href=\"?number=".$num."\">".$num."</td>";
}
echo "</tr>";
}
echo "</table>";
}
if (isset($_GET['number'])) {
$User_Number = $_GET['number'];
$Actual_Number = $_SESSION['higherlower'];
if ($_SESSION['tries'] <= 0) {
die("Oops! You're bad at this!");
}
if ($User_Number < $Actual_Number) { echo "Higher"; $count + 1; Display_Form(); }
elseif ($User_Number > $Actual_Number) { echo "Lower"; $count + 1; Display_Form(); }
elseif ($User_Number == $Actual_Number) { echo "Bingo, Correct Guess!<br>"; Start_Again(); }
$_SESSION['tries']--;
echo $_SESSION['tries'] . 'chances left';
} elseif (!isset($_POST['higherlower'])) {
Start_Again();
}
答案 1 :(得分:0)
您已经开始会话,因此可以将值存储在会话变量中,即$ _SESSION ['count'];
session_start();
if( !isset( $_SESSION['count] ) ) $_SESSION['count'] = 1;
稍后在代码中,您将需要更新计数器$_SESSION['count']++;
并检查此人是否已用完所有猜测
if( $_SESSION['count'] > 3 ) { ..... }