0

私はゲームのために働いており、アルゴリズムが必要です。

グリッドマップがあり、各セルには X と Y の 2 つの座標があります。

したがって、begin には、開始セル (X=8:Y=10 など) と終了セル (X=18:Y=15) があります。

これらの 2 点間の各セルの座標 (X:Y) を見つけることができるアルゴリズムが必要ですが、直線ではなくランダムなパスを使用します。可能であれば、これらの座標間のセルの最大数。

あなたはなにか考えはありますか?

編集: http://alex.moutonking.com/wordpress/?p=44を確認できます。これは、2 つの座標間の直線のアルゴリズムです。ランダム効果を追加する必要があります。

4

1 に答える 1

0

すべてのポイントを取得して、ポイントからランダムな値を返すことができます

$pt1 = array(
        8,
        10
);
$pt2 = array(
        18,
        15
);

$sl = new StraightLine($pt1, $pt2);
echo $sl->rand(true);   // return random points

出力

{
    "x": 16,
    "y": 14
}

すべてのポイントを取得するには

echo $sl;

出力

[
    {
        "x": 8,
        "y": 10
    },
    {
        "x": 9,
        "y": 10.5
    },
    {
        "x": 10,
        "y": 11
    },
    {
        "x": 11,
        "y": 11.5
    },
    {
        "x": 12,
        "y": 12
    },
    {
        "x": 13,
        "y": 12.5
    },
    {
        "x": 14,
        "y": 13
    },
    {
        "x": 15,
        "y": 13.5
    },
    {
        "x": 16,
        "y": 14
    },
    {
        "x": 17,
        "y": 14.5
    },
    {
        "x": 18,
        "y": 15
    }
]

使用クラス

class StraightLine implements IteratorAggregate, JsonSerializable {
    private $pt1 = 0, $pt2 = 0;
    private $points = array();

    function __construct($pt1, $pt2) {
        if (count($pt1) !== 2 || count($pt2) !== 2)
            throw new InvalidArgumentException("Expexting only 2 values each");

        $this->pt1 = array_values($pt1);
        $this->pt2 = array_values($pt2);

        $this->parse();
    }

    public function getIterator() {
        return new ArrayIterator($this->points);
    }

    public function jsonSerialize() {
        return json_encode($this->points, 128);
    }

    public function __toString() {
        return $this->jsonSerialize();
    }

    public function rand($encode = false) {
        $k = array_rand($this->points);
        return $encode ? json_encode($this->points[$k], 128) : $this->points[$k];
    }

    private function parse() {
        $m = ($this->pt1[1] - $this->pt2[1]) / ($this->pt1[0] - $this->pt2[0]);
        $b = $this->pt1[1] - $m * $this->pt1[0];
        for($i = $this->pt1[0]; $i <= $this->pt2[0]; $i ++)
            $this->points[] = array(
                    "x" => $i,
                    "y" => $m * $i + $b
            );
    }
}
于 2013-03-28T16:43:16.300 に答える