变量始终重置 [英] Variable always resetting

查看:71
本文介绍了变量始终重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用表单创建一个类似mastermind的游戏。我的问题是,我有一个变量$的尝试,我希望它增加每次用户猜数字,但它似乎总是重置为零,所以我的尝试次数将始终显示为1.如果它有帮助这里是我正在使用的代码:

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);


推荐答案

您是否每次猜测都提交表单?如果是这样,你需要设置一个会话变量,如:

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

$_SESSION['attempts'] += 1;

只是澄清一下它 你错过了。 PHP脚本是在服务器上运行的代码,用于生成文档(通常为html)以发送给客户端。因此,它不是非常互动的请求。如果你想让代码在客户端运行,你需要使用Javascript。 Javascript具有无需通过客户端和服务器之间的互联网传递信息的好处。

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.

这篇关于变量始终重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆