编写程序,计算机猜测用户选择的数字-PHP

时间:2014-03-17 22:20:23

标签: php hiddenfield

用户不需要提交号码等等。只要想一想。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>guess_game</title>
</head>

<body>

>if guess is too low, user presses 'low button' (same with high button)

<p>think of a number, 1-100.</p>
<form method="post">
<button type="submit" name="low">too low</button>
<button type="submit" name="high">too high</button>
<button type="submit" name="match">it's a match</button>
</form> 

<?php 

if (isset($_POST['low'])) 
{
>store $guess to be lowest number range of guess
 $low = $guess; 
}
else{$low=1;}

if (isset($_POST['high'])) 
{
$high = $guess; 
}
else{$high=100;}

if (isset($_POST['match'])) 
{
print "thank you for playing";
}
?>

<form method="post">
<input type="hidden" name="hLow" id="hLow" value="<?php $low ?>">

>store $low,High vars to hidden field

<input type="hidden" name="hHigh" id="hHigh" value="<?php $high ?>">
</form>

<?php

>place values stored in hidden back to php var.

$hlow=$_POST['hLow'];   
$hhigh=$_POST['hHigh'];

$guess=rand($hlow,$hhigh);
print "is the number $guess"; 
?>
</body>
</html> 

到目前为止,此代码不会将任何值传递给隐藏字段。($ guess始终为0)   我希望$ guess是$ low和$ high之间的随机数(存储在隐藏中)

2 个答案:

答案 0 :(得分:0)

您不能将$guess放入表单中。在计算$guess后将其放入。

<input type="hidden" name="hGuess" id="hGuess" value="<?php $guess ?>">

答案 1 :(得分:0)

尝试:

<?php
$guess = 'Think of a number between 1 and 100.';
if(isset($_POST['low']) || isset($_POST['high'])){
  $guess = 'The Computer will have to guess again.'
}
elseif(isset($_POST['match'])){
  $guess = 'The Computer just read your mind....Not.';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>GUESSING GAME</title>
    <style type='text/css'>
      @import 'common.css'; @import 'game.css';
    </style>
  </head>
<body class='njs'>
  <p><?php echo $guess;?></p>
  <form method='post' action='<?php echo $_SERVER['PHP_SELF'];?>'>
    <input type='submit' name='low' value='too low' />
    <input type='submit' name='high' value='too high' />
    <input type='submit' name='match' value='it&#039;s a match' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>