Answer the question
In order to leave comments, you need to log in
How to select adjacent tiles on a 5x5 board (6x6, doesn't matter)?
I am doing a task, the task is to select all neighboring cells for a 5 by 5 board
// Вертикальные соседи
$nord = $blockIdFromClick - $n;
$south = $blockIdFromClick + $n;
// Горизонтальные
$west = $blockIdFromClick - 1;
$east = $blockIdFromClick + 1;
// По диагонали (из правого верхнего угла)
$nordEast = $blockIdFromClick - ($n-1);
$southWest = $blockIdFromClick + ($n-1);
// По диагонали (из левого верхнего угла)
$nordWest = $blockIdFromClick - ($n+1);
$southEast = $blockIdFromClick + ($n+1)
Answer the question
In order to leave comments, you need to log in
Let's assume that the input is the coordinates of the central cell and the dimensions of the field, and the coordinates are counted from 0,0.
For the top and bottom lines, we check if it goes beyond the bounds. Inside the line, we check if there is a horizontal overflow.
Something like this:
/**
* @param int $x center
* @param int $y center
* @param int $width
* @param int $height
*/
function getNeighbours($x, $y, $width, $height) {
$result = [];
// 1st row
if ($y > 0) {
$rowY = $y - 1;
$result[0] = $x > 0 ? [$x - 1, $rowY] : null;
$result[1] = [$x, $rowY];
$result[2] = $x < $width - 1 ? [$x + 1, $rowY] : null;
} else {
$result[0] = $result[1] = $result[2] = null;
}
// 2nd row
$rowY = $y;
$result[3] = $x > 0 ? [$x - 1, $rowY] : null;
$result[4] = [$x, $rowY];
$result[5] = $x < $width - 1 ? [$x + 1, $rowY] : null;
// 3rd row
if ($y < $height) {
$rowY = $y + 1;
$result[6] = $x > 0 ? [$x - 1, $rowY] : null;
$result[7] = [$x, $rowY];
$result[8] = $x < $width - 1 ? [$x + 1, $rowY] : null;
} else {
$result[6] = $result[7] = $result[8] = null;
}
return $result;
}
getNeighbours(5, 7, 10, 10);
Array
(
[0] => Array
(
[0] => 4
[1] => 6
)
[1] => Array
(
[0] => 5
[1] => 6
)
[2] => Array
(
[0] => 6
[1] => 6
)
[3] => Array
(
[0] => 4
[1] => 7
)
[4] => Array
(
[0] => 5
[1] => 7
)
[5] => Array
(
[0] => 6
[1] => 7
)
[6] => Array
(
[0] => 4
[1] => 8
)
[7] => Array
(
[0] => 5
[1] => 8
)
[8] => Array
(
[0] => 6
[1] => 8
)
)
getNeighbours(5, 3, 5, 5);
Array
(
[0] => Array
(
[0] => 4
[1] => 2
)
[1] => Array
(
[0] => 5
[1] => 2
)
[2] =>
[3] => Array
(
[0] => 4
[1] => 3
)
[4] => Array
(
[0] => 5
[1] => 3
)
[5] =>
[6] => Array
(
[0] => 4
[1] => 4
)
[7] => Array
(
[0] => 5
[1] => 4
)
[8] =>
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question