Need help with a complex array idea.

So I’ve got these two arrays, shown here:

[php]// This is my world map, the numbers represent certain tiles, i.e 1=>“stone_floor” and 2=>“wood_floor”.
// The values in this array are preset, so there’s no problem here.
$world_map = Array(
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1);

// My problem is here. (continued below)
$tile_map = Array();
[/php]

I want $tile_map to only pull the 2s from $world_map, to become a 4x4 map, instead of the original 8x8.
However, my problem is that I want to sometimes move that 4x4 box to the right/left and up/down, to include some of the 1s.

I’ve tried for days to find a way to do this, and I just cant figure it out. Any and all help would be appreciated.

Interesting task. It would be easier if you use 2 dimensional array instead of 1, but I guess this is some kind of school task? :slight_smile: Anyway, here is a quick solution (maybe not most elegant - probably it was supposed that you use functions like array_chunk(), array_slice() etc. ):

[php]<?php

$world_map = Array(
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1);

$n = 8; // dimension of the source matrix
$m = 4; // dimension of the destination matrix

function clip_matrix($a,$n,$m,$shift_x=0,$shift_y=0){

$b = array(); // destination matrix, dimension $m x $m

for($i=0;$i<$m;$i++){
for($j=0;$j<$m;$j++) $b[$i*$m+$j]=$a[($i+$shift_y)*$n+$j+$shift_x];
}

return $b;
}

function show_matrix($a,$n){
echo ‘

’;
for($i=0;$i<$n;$i++){
for($j=0;$j<$n;$j++) echo $a[$i*$n+$j], ’ ';
echo “\n”;
}
echo ‘
’;
}

echo “

Source matrix:

”;
show_matrix($world_map,$n);

echo “

Default clip $m x $m

”;
$tile_map = clip_matrix($world_map,$n,$m);
show_matrix($tile_map,$m);

echo “

Clip $m x $m with shift by 2 in both directions

”;
$tile_map = clip_matrix($world_map,$n,$m,2,2);
show_matrix($tile_map,$m);

?>[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service