Как создать случайный массив для простой карты подземелий?

Я работал над очень простым создателем подземелий. Идея в том, что я предоставляю x_axis а также y_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

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector