【问题标题】:Random path between two coordinates (x, y)两个坐标 (x, y) 之间的随机路径
【发布时间】:2013-03-28 16:33:45
【问题描述】:

我正在为游戏工作,我需要一种算法。

我有一个网格图,每个单元格有 2 个坐标:X 和 Y。

所以,对于开始,我有一个起始单元格(例如 X=8:Y=10)和一个结束单元格(X=18:Y=15)。

我需要一种算法,它可以找到这两个点之间每个单元格的坐标(X:Y),但路径是随机的,而不是直线。如果可能的话,这些坐标之间的最大单元数。

你有什么想法吗?

编辑:你可以检查http://alex.moutonking.com/wordpress/?p=44,这是我的两个坐标之间的直线算法,我需要添加一个随机效果..

【问题讨论】:

  • 到目前为止您尝试了哪些方法?
  • 尝试写一个算法,然后向社区寻求帮助。
  • 这都是关于数学和算法的,所以我猜你是在错误的地方......
  • 我有这个:alex.moutonking.com/wordpress/?p=44,这是我的算法,但只适用于直线,我需要添加随机效果。
  • 如何允许你从一个单元格移动到另一个单元格?水平/垂直/对角只有一个正方形?首先,尝试基于当前 delta x 和 delta y 进行随机游走。不过,这不会给出“最大单元数”。

标签: php algorithm


【解决方案1】:

您可以获取所有点,然后从该点返回一个随机值

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多