PHP游戏的石头返回布尔而不是赢家

时间:2018-06-16 07:43:04

标签: php return-value game-loop

以下代码适用于游戏。它创建了一组N个连续的宝石,玩家Alice和Bob将每次选择两个连续的宝石(减去价值并留下一个“差距”),直到没有连续的宝石。这意味着数组没有值,两者之间没有间隙。

我认为游戏的代码已经完成。但是当我调用它时只显示一个布尔值(true)。而不是获胜者的名字。

这是我的代码:

<?php
class GameOfStones {

    // Define while the index contains a stone (O) or not.

    const STONE = 'O';
    const STONE_PAIR = 'OO';
    const GAP = '';

    // Save the random result in a open/public variable.

    public $line;
    public $winner;

    // Set the winning rules for the game.

    public function win($winner) {
        if (is_finished === true) {     
            if ($nStones % 2 == 1) {
                echo "Alice" . '<br>';
            } 
            else {
                echo "Bob" . '<br>';
            }
        }
    }

    // Create the indexed line of stones

    public function create_line($nStones){
        return array_fill(0, $nStones, 'O');
    }


    // Removes a pair of stones from the line at nth location.

    public function remove($n)
    {
        while($game->is_finished() !== true) {

            if(substr($this->line, $n-1, 2) == self::STONE)
                $this->line =
                    substr_replace($this->line, self::GAP , $n-1, 2);
            else
                throw new Exception('Invalid move.');
        }
    }


// Check if there are no further possible moves.

public function is_finished()
{
    return strpos($this->line, self::STONE_PAIR) === false;
}

};
$game = new GameOfStones(rand(1,10000000));

 var_dump($game->is_finished());
     $game->remove(rand($n));
     var_dump($game->is_finished());
    var_dump($game->win());
echo $nStones;
printf($winner);
?>

2 个答案:

答案 0 :(得分:1)

看起来您正在调用constant is_finished而不是您的方法is_finished()。尝试替换

public function win($winner) {
    if (is_finished === true) {     
        if ($nStones % 2 == 1) {
            echo "Alice" . '<br>';
        } 
        else {
            echo "Bob" . '<br>';
        }
    }
}

使用

public function win($winner) {
    if ($this->is_finished() === true) {     
        if ($nStones % 2 == 1) {
            echo "Alice" . '<br>';
        } 
        else {
            echo "Bob" . '<br>';
        }
    }
}

答案 1 :(得分:0)

boolean(true)是您从var_dump($game->is_finished());

中的第一个var_dump获得的返回值

remove()函数中,$game变量不存在。相反,您应检查$this,因为remove()已经是类函数

 while($this->is_finished() !== true)

此外,在win()函数中,您没有正确调用is_finished函数。

 if ($this->is_finished() === true)