(PHP)在随机数游戏中添加“猜测计数器”

时间:2014-09-26 22:13:45

标签: php html

我需要修改一段代码并添加一个计数器,说明用户猜错正确数字的次数。

我想知道如何在我的代码中正确实现它。

这是我到目前为止所做的。

<?php

if (!isset($_POST["guess"])) {
     $message = "Welcome to the guessing machine!";
     $count++; //Declare the variable $count to increment by 1.
     $_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";

} else { // must be equivalent
    $message = "Well done! You guessed the right number in ".$count." attempt(s)!"; 
        //Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

3 个答案:

答案 0 :(得分:3)

您必须使用PHP会话来跟踪计数。 您所要做的就是将计数器初始化为0,并在用户猜出数字时将其递增

<?php
session_start();

if (!isset($_POST["guess"])) {
     $_SESSION["count"] = 0; //Initialize count
     $message = "Welcome to the guessing machine!";
     $_POST["numtobeguessed"] = rand(0,1000);
     echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";
    $_SESSION["count"]++; //Declare the variable $count to increment by 1.

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";
    $_SESSION["count"]++; //Declare the variable $count to increment by 1.

} else { // must be equivalent
    $_SESSION["count"]++;
    $message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!"; 
    unset($_SESSION["count"]);
        //Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>

    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

答案 1 :(得分:1)

这应该适合你。

$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
     $message = "Welcome to the guessing machine!";
     $_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";

} else { // must be equivalent
    $message = "Well done! You guessed the right number in ".$count." attempt(s)!"; 
        //Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
            <input type="hidden" name="count" 
                   value="<?php echo $count; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

答案 2 :(得分:0)

在 2021 年 6 月 22 日,我使用 PHP 编写了一个范围内的猜数 [0 .. aMaxIntValue] 示例 Web 应用程序。我认为以下代码可能对您有所帮助。代码保存在单个 PHP 文件中。它生成 #4 HTML 页面 ...

  • 第一个初始页面用于收集应用程序参数(例如要猜测的最大整数数)

  • 第二页是主游戏页面,要求用户猜测密码或重置游戏。此页面显示了之前的用户猜测以及一些给用户的猜测提示

  • 第三页用于通知用户输掉比赛(即他没有更多的尝试机会了)

  • 第4页用于通知用户赢得游戏(即猜对了)

留给用户的尝试次数是使用值范围 [0 .. max] 计算的

要猜的秘密数字是一个随机生成的整数

这是 PHP + HTML 代码...

<?php

    session_start();

    error_reporting (E_PARSE | E_COMPILE_ERROR);

    function ResetGame()
    {
        unset ( $_SESSION['theMaxNumber'] );
    }

    function InitGame()
    {
        $_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);

        $_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;

        $_SESSION['theUserTriesCount'] = 0;

        $_SESSION['thePrevGuessesString'] = '';

        $_SESSION['theUserGuess'] = 0;
    }

    function ComputeNumberOfTriesLeft()
    {
        return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
    }

    function IsNoMoreTriesLeft()
    {
        return ComputeNumberOfTriesLeft() <= 0;
    }

    $aCanPlayGame = false;

    $aUserSubmittedGuess = false;

    $aIsNoMoreTriesLeft = false;

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        if ( isset ($_REQUEST['playgame']) ) {

            $_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);

            // init game ...
            InitGame();

            $aCanPlayGame = true;

        }
        elseif ( isset ($_REQUEST['submituserguess']) ) {

            $aCanPlayGame = true;

            $aUserSubmittedGuess = true;

            $_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);

        }
        elseif ( isset ($_REQUEST['resetgame']) ) {

            ResetGame();

        }
        else {
            ResetGame();
        }

    }
    else {
        ResetGame();
    }

    // check a play

    $aUserShouldTryLower = false;
    $aUserShouldTryHigher = false;

    $aUserWins = false;

    $aUserLooses = false;

    if ($aCanPlayGame) {

        $aIsNoMoreTriesLeft = IsNoMoreTriesLeft();

        if ( ! $aIsNoMoreTriesLeft ) {

            // user have tries left

            if ($aUserSubmittedGuess) {

                // check user guess ...
                $aUserGuess = intval($_SESSION['theUserGuess']);

                if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {

                    $aUserShouldTryLower = true;

                }
                elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {

                    $aUserShouldTryHigher = true;

                }
                else {

                    $aUserWins = true;

                    // also reset game
                    ResetGame();

                }

                // add the current guess to the prev guesses string
                $_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';

                // increase the user tries count
                ++ $_SESSION['theUserTriesCount'];

                // check tries count
                if ( ! $aUserWins ) {

                    $aIsNoMoreTriesLeft = IsNoMoreTriesLeft();

                    if ($aIsNoMoreTriesLeft) {
                        // this was the last try

                        // no more tries left
                        $aUserLooses = true;

                        // also reset game
                        ResetGame();
                    }

                }
            }

        }
        else {
            // no more tries left
            $aUserLooses = true;

            // also reset game
            ResetGame();
        }

    }

?>

<?php if ($aUserLooses): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>
    <p>Sorry, you loose the game</p>
    <p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <form method="post">
        <input type="submit" name="resetgame" value="reset game">
    </form>
</body>
</html>

<?php elseif ($aUserWins): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>
    <p>Congrats, you Win the Game</p>
    <p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <form method="post">
        <input type="submit" name="resetgame" value="reset game">
    </form>
</body>
</html>

<?php elseif ($aCanPlayGame): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>

    <p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
    <p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
    <p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
    <form method="post">
        <label for="theUserGuess">Enter your Guess: </label>
        <input type="text" id="theUserGuess" name="theUserGuess">
        <input type="submit" name="submituserguess" value="Guess">
        <input type="submit" name="resetgame" value="reset game">
    </form>
    <p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
    <p>
        <?php
            if ($aUserShouldTryLower) {
                echo 'you should try a lower < guess';
            }
            elseif ($aUserShouldTryHigher) {
                echo 'you should try a higher > guess';
            }
            else {
                echo 'no guess';
            }
        ?>
    </p>

</body>
</html>

<?php else: ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>

    <p>Guess a Number from (0) to ... </p>
    <form method="post">
        <input id="theMaxNumber" name="theMaxNumber">
        <input type="submit" name="playgame" value="play game">
    </form>

</body>
</html>

<?php endif; ?>

就是这样……