可能重复:
变量总是重置
所以我对 html 或 php 不太熟悉,但是我一直在开发像 mastermind 这样的游戏,我的代码一直存在的一个问题是变量 $attempts 似乎总是重置,所以它的价值总是1。有没有办法解决这个问题?我的大部分代码都在这里:
<?php
$showtable = false;
$showform = false;
$showstart= true;
$process = false;
$black = 0;
$white = 0;
$answer = array(1,2,3,4);
$tries = array();
$attempts = 0;
if (isset($_POST['started']))
{
$showform = true;
$showstart = false;
}
if (isset($_POST['guessed']))
{
$process = true;
}
if ($showstart == true)
{
echo"
<form action='' method='post'>
<input type='submit' value='Start' name='start' />
<input type='hidden' value='started' name='started'/>
</form><Br /><br />
";
}
if ($showform == true)
{
echo"
<h3>Your guess:</h3>
<form action='gogo.php' method='post'>
<input type='text' placeholder='Your guess' maxlength='4' value='' name='guess' />
<input type='submit' value='guess' name='submitt' />
<input type='hidden' value='started' name='started' />
<input type='hidden' value='guessed' name='guessed' />
</form><Br /><br />
";
}
if ($process == true)
{
$attempts += 1;
$guess = str_split($_POST['guess']);
if ($guess == $answer)
{
$black = 4;
} else
{
for ($i=0;$i<4;$i++)
{
if ($guess[$i] == $answer[$i])
{
$black += 1;
$white -= 1;
}
}
$result = array();
foreach ($guess as $val)
{
if (($key = array_search($val, $answer))!==false)
{
$result[] = $val;
unset($answer[$key]);
}
}
$count = count($result);
$white = $white + $count;
}
}
$chance = implode(" ",$guess);
$try = $attempts.".".$chance.".".$white.".".$black;
array_push($tries, $try);
$showtable = true;
if ($showtable == true)
{
echo"
<table border='2' cellpadding='10'>
<Tr><Td>Attempt:</td><td>Number guessed:</td><td>White:</td><Td>Black:</td></tr>
";
for ($i=0;$i<$attempts;$i++)
{
$split = explode(".",$tries[$i]);
echo"
<tr><td>".$split[0]."</td><td>".$split[1]."</td><td>".$split[2]."</td> <td>".$split[3]."</td></tr>
";
}
echo"
</table>
";
}
?>