PHP趣味小程序 – 猜数字小游戏

<body>
<div id=”header”>
<h1>猜数字小游戏</h1>
<h3>作者:Tonight</h3>
</div>
<div id=”mainbox”>
<?php
//通过step变量实现步骤控制
if(!$step)
{
  $step = 1;
}

if($step == 1)
{
  //随机生成正确答案
  $number_order = range(0,9);  //创建0-9数字的数组
  shuffle($number_order);      //随机打乱数组排序
  $number_order = array_slice($number_order, 0, 4);
  $number_answer = implode(”, $number_order);
  $n = 0;  //初始化猜的次数
}

if($step == 2)
{
  $number_order = str_split($_POST[‘number_answer’], 1);
  //echo $number_answer . “\n\t”;
  $input_num = $_POST[‘input_num’];
  $numlen = strlen($input_num);
  if($numlen != 4)
  {
   echo “请输入 4 位数字!”;
  }

  $input_nums = str_split($input_num, 1);
  $a = count( array_intersect_assoc($input_nums, $number_order));
  $b = count(  array_intersect($input_nums, $number_order));
  $b = $b-$a;
  $str = $a . “A” . $b . “B”;     //本次输入结果字符串
  $t = $n;
  $n++;

  //通过数组history记录并显示每一次输入的结果
  $history[$t] = “第 $n 次输入数字:” . $input_num . “\n\t结果为:” . $str;
  for($i=0; $i<$n; $i++)
  {
   echo $history[$i] . “<br />”;
  }

  //显示结果文字
  if($str == “4A0B”)
  {
   echo “恭喜!你猜对了!<br />” . $n . “次就猜出正确答案,你厉害啊!”;
  } else {
   echo “还不对哟,继续努力!”;
  }
}
?>
<form method=”post” action=””>
  <input type=”text” name=”input_num”>
  <input type=”submit” value=”我猜猜猜”>
  <input type=”hidden” name=”step” value=”2″>
  <input type=”hidden” name=”n” value=”<?=$n?>”>
  <input type=”hidden” name=”number_answer” value=”<?=$number_answer?>”>
  <?php

  //通过表单发送历史记录
  for($i=0; $i<$n; $i++)
  {
  ?>
  <input type=hidden name=”history[<?php $i;?>]” value=”<?php echo $history[$i]; ?>”>
  <?php
  }
  ?> 
</form>
<a href=”<?=$PHP_SELF?>?step=1″>重新开始</a>
</div>
</body>

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: