如何为简单的地下城地图生成随机数组?

时间:2018-03-01 23:14:42

标签: php arrays json dictionary coordinates

我一直在研究一个非常简单的地下城创作者。我的想法是,我提供x_axisy_axis长度来确定地图的大小,然后随机生成一个包含0的数组,什么都不包含,2为一个房间。

根据地图的大小,这将决定房间的数量floor((x * y) / 2),但有时会创建更少的房间,我似乎无法找出原因。

<?php
// Check if this was a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Set variables
    $x_axis = $_POST['x_axis'];
    $y_axis = $_POST['y_axis'];

    // Build the arrays
    $x_array = array_fill(0, $x_axis, 0);
    $y_array = array_fill(0, $y_axis, 0);
    $coordinates = [];

    // Loop through the x array
    foreach($x_array as $x => $v)
    {
        // Add the y_array at position x in the coordinates
        $coordinates[$x] = $y_array;
    }

    // Set variables
    $x_max = $x_axis - 1;
    $y_max = $y_axis - 1;
    $rooms_max = floor(($x_axis * $y_axis) / 2);

    // Pick a random starting point along the x axis
    $start = mt_rand(0, $x_max);

    // Generate the map
    $map = _generate_room($coordinates, $start, 0, 1, $rooms_max, $x_max, $y_max);

    // Return the map
    echo json_encode($map);
}

function _generate_room($c, $x, $y, $r, $rm, $xm, $ym)
{
    // Set this value to a room (2)
    $c[$y][$x] = 2;

    // Have we reached the max number of rooms?
    if($r != $rm)
    {
        // Increase the room
        $r = $r + 1;

        // Generate the next coordinate
        $next_coord = _generate_coord($c, $x, $y, $xm, $ym);

        // Create a new room
        $c = _generate_room($c, $next_coord[0], $next_coord[1], $r, $rm, $xm, $ym);
    }

    // Return the coordinates
    return $c;
}

function _generate_coord($c, $x, $y, $xm, $ym)
{
    // Are we changing the x (0) or y(1)
    $change = mt_rand(0, 1);

    // Changing the x
    if($change === 0)
    {
        // Set the new_x variable
        if($x === 0)
        {
            $x = 1;
        } elseif($x === $xm)
        {
            $x = $xm - 1;
        } else {
            // Choose 0 or 1
            $res = mt_rand(0, 1);

            // Decrease
            if($res === 0)
            {
                $x = $x - 1;
            // Increase
            } else
            {
                $x = $x + 1;
            }
        }
    } else
    {
        // Set the new_y variable
        if($y === 0)
        {
            $y = 1;
        } elseif($y === $ym)
        {
            $y = $ym - 1;
        } else {
            // Choose 0 or 1
            $res = mt_rand(0, 1);

            // Decrease
            if($res === 0)
            {
                $y = $y - 1;
            // Increase
            } else
            {
                $y = $y + 1;
            }
        }
    }

    // Fetch the room
    $room = $c[$x][$y];

    // Does the room already contain a 2?
    if($room === 2)
    {
        return _generate_coord($c, $x, $y, $xm, $ym);
    }

    return [$x, $y];
}

0 个答案:

没有答案