我目前正在阅读一本初学者 php 书籍,并正在尝试做一个练习,希望我做一个猜数字游戏。在我自己尝试失败后,我查看了附录中的答案。我已经多次输入此代码,我相信答案键所具有的字符是字符的,但是当我运行脚本时,脚本的一部分仍然出现在浏览器中。我错过了什么?谢谢!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<?php
if ( isset($_POST["submitButton"] ) and isset( $_POST["guess"] ) ) {
processForm();
} else {
displayForm( rand( 1, 100 ) );
}
function processForm() {
$randNum = (int)$_POST["randNum"];
$guessLeft = (int)$_POST["guessLeft"];
$guess = (int)$_POST["guess"];
if ( $guess == $randNum ) {
displaySuccess( $randNum );
} elseif ( $guess == 0 ) {
displayFail( $randNum );
} elseif ( $guess < $randNum ) {
displayForm( $randNum, $guessLeft, "Too low, try again.");
} else ( $guess > $randNum ) {
displayForm( $randNum, $guessLeft, "Too high, try again.");
}
}
function displayForm( $randNum, $guessLeft=5, $message="") {
?>
<form action="" method="post">
<div>
<input type="hidden" name="randNum" value="<?php echo $randNum?>" />
<input type="hidden" name="guessLeft" value="<?php echo $guessLeft?>" />
<?php if ( $message ) echo "<p>$message</p>" ?>
<p>Guess my number. You have <?php echo $guessLeft?> <?php echo ( $guessLeft == 1 ) ? "try" : "tries"?> left to guess correctly.</p>
<p>What's your guess? <input type="text" name="guess" value="" style="float: none; width: 3em;" />
<input type="submit" name="submitButton" value="Guess" style="float: none;" /></p>
</div>
</form>
<?php
}
function displaySuccess( $randNum ) {
?>
<p>You guess it! <?php echo $randNum?> is correct!</p>
<form action="" method="post">
<p><input type="submit" name="tryAgain" value="Try Again" style="float: none;" /></p>
</form>
<?php
}
function displayFail( $randNum ) {
?>
<p>You ran out of guesses! My number was <?php echo $randNum?></P>
<form action="" method="post">
<p><input type="submit" name="tryAgain" value="Try Again" style="float: none;" /></p>
</form>
<?php
}
?>
</body>
</html>