Hangman更新OO值数组

时间:2014-12-16 10:49:09

标签: javascript php arrays

我正在用PHP和JS编写一个刽子手游戏,我遇到了问题。我有两个数组, 一个具有正确字母的答案数组, 和一个用户回答数组,其中包含用户正确的猜测。

用户回答猜测数组以下划线开始,因为没有猜测是正确的_ _ _

我想更新此数组,并在用户正确猜测时将正确的字母放入正确的字段_ A _;

当我在updateAnswer()函数中使用var_dump时,用户应答数组已更改并添加了正确的字母,但是当我从returnUserAnswer拉出时,数组却没有。

PS。该库只被调用一次所以__construct不是问题。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Word {

private $answer;
public $usrAnswer;

function __construct(){
$this->answer = array('C','A','T');
$this->usrAnswer = array('_','_','_');
}
function returnUserAnswer(){
return $this->usrAnswer;
}

function updateAnswer($letter,$try){
    $change = array($try => $letter);
    $this->usrAnswer = array_replace($this->usrAnswer,$change);

}

function guess($letter){

    $try = array_search($letter,$this->answer);

    if($try === FALSE){ 
    return false;
    }else{ 
    $this->updateAnswer($letter,$try);return $try;      
    }

}

}

1 个答案:

答案 0 :(得分:0)

由于JavaScript标记,我假设你正在编写一个使用AJAX请求的hangman实现。如果这个假设是正确的,那么你的这个陈述就像以前一样错误:

  

PS。该库只被调用一次,因此__construct不是问题。

PHP无国籍。这意味着,对于服务器接收的每个请求,都会实例化您的类,并且在发送响应时,所有实例的所有更改都将丢失。因此,这就是ajax驱动流程的样子:

[request 1] => new Word --> constructor initialize $usrAnswer to ['_','_','_']
                                        initialize $answer to ['C', 'A', 'T']
            => destroy instances and resources
            => send response

[request 2] => guess a letter (send via AJAX)
            => new Word --> constructor is called, same as request 1
            => update $usrAnswer
            => destroy instance
            => send response

[request 3] => see [request 2]
[request N] => see [request 2]

然后,您需要做的是让JavaScript在每个请求上发送猜测答案的完整状态,而不仅仅是一个字母。类似下面的对象会做:

var requestData = {
    state: {
        validGuesses: ['A'],
        invalidGuesses: ['X', 'Q'] //<-- number of attempts, check if current guess is not a duplicate
    },
    guess: 'C'
};

然后,服务器端(在PHP中),更改构造函数以获取参数(在这种情况下,数组将执行此操作)。顺便说一句,下面的代码适用coding standards,我建议你也遵守它:

public function __construct(array $userState = array())
{
    $this->answer = ['C', 'A', 'T'];
    $this->usrAnswer = ['_','_','_'];
    foreach ($userState as $value) {
        $key = array_search($value, $this->answer);
        if ($key === false) {
            //handle invalid state, I'd suggest:
            throw new InvalidArgumentException(
                sprintf('%s is not a valid answer', $value)
            );
        }
        $this->usrAnswer[$key] = $value;
    }
}

现在,当您致电guess时,$usrAnswer的值将是正确的。

更新
为了澄清我的上一条评论(关于向构造函数添加$answer参数),这就是我要做的事情:

public function __construct($answer = 'CAT', array $state = [])
{
    $this->answer = str_split(strtoupper($answer));//ensure upper-case, create array
    //create array containing the correct amount of _ chars
    $this->usrAnswer = array_fill(0, strlen($answer), '_');
    foreach ($state as $value) {
        $key = array_search($value, $this->answer);
        if ($key === false) {
            throw new InvalidArgumentException(
                sprintf('%s is not a valid answer', $value)
            );
        }
        $this->usrAnswer[$key] = $value;
    }
    //replace _ with dash, if the answer contains dashes (eg ice-cream)
    $pos = -1;
    while (($pos = strpos($answer, '-', $pos +1)) !== false) {
        $this->usrAnswer[$pos] = '-';
    }
}

就使用该课程而言,没有任何改变:

$cat = new Word();

除了ajax请求需要处理时:

$cat = new Word('cat', $state);//where $state is the request data

另一个例子:

$iceCream = new Word('ice-cream', ['C', 'A']);
//sets usrAnswer to _C_-C__A_
$iceCream->guess('I');
//usrAnswer is now IC_-C__A_