Anthony Wu
Anthony Wu

Reputation: 41

Variable always resetting

I'm creating a game like mastermind using forms. My problem is that I have a variable $attempts, and I want it to increase every time the user guesses a number, but it seems to always reset to zero so my number of attempts will always be displayed as 1. If it helps here's the code I'm using:

$black = 0;
$white = 0;
$answer = array(1,2,3,4);
$tries = array();
$attempts = 0;
if ($process == true)
{
$guess = str_split($_POST['guess']);
if ($guess == $answer)
{
    $black = 4;
} else
{
    for ($i=0;$i<4;$i++)
    {
        if ($guess[$i] == $answer[$i])
        {
            $black = $black + 1;
            $white = $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);
$attempts += 1;
$try = $attempts.".".$chance.".".$white.".".$black;
array_push($tries, $try);

Upvotes: 0

Views: 121

Answers (2)

alanmanderson
alanmanderson

Reputation: 8200

Are you submitting the form on every guess? If so you need to set a session variable like:

$_SESSION['attempts'] += 1;

Just to clarify something that it seems you are missing. A php script is code that runs on the server producing a document (frequently html) to be sent to a client. Therefore it isn't very interactive accross requests. If you want code to be ran on the client side you need to use Javascript. Javascript has the benefit of not needed to pass information accross the internet between client and server.

Upvotes: 1

Andy
Andy

Reputation: 14575

$attempts is always equal to one because it is not inside a loop, it is declared at the end and you are just adding one to its existing value (0). You need to put it in the appropriate place (just above the last { I think) and it should work.

Also, you seem to use different methods for adding one, such as $black + 1 and $attempts += 1;. Use $variable++, it is much easier to understand and stops any errors arising of that.

Upvotes: 0

Related Questions