deleting items from 2d arrays

Daniel Keep daniel.keep.lists at gmail.com
Thu Aug 13 20:55:18 PDT 2009



Michael P. wrote:
> Okay, so I'm making a breakout type game in D. Using Derelict.
> I have a 2d array of Block type variables(not important what's in them) declared like this:
> Block[][] level;
> and later load into like this:
> level = loadLevel( "levels.txt", levelNumber );
> Anyways, what I want to do is that when the ball hits one of the blocks in the array, I remove it. When a line no longer has any blocks in it, I remove that line/row. When there are no more lines, I load the next level.
> Any ideas on how I could achieve this?
> 
> foreach( Block[] ba; level )
> {
> 	foreach( Block b; ba )
> 	{
> 		if( checkCollision( ball, b.p ) )
> 		{
> 			//remove the block??
> 		}
> 	}
> }
> 
> The level array has 12 lines of 'x' amount of bricks. x can be as great as 10.
> -Michael P.

That depends on what you mean by "remove" and what Block is.

If Block is a class, you can remove instances from the array simply by
setting that slot to null.

foreach( row ; level )
{
  foreach( ref block ; row )
  {
    if( checkCollision( ball, block.p ) )
        block = null;
  }
}

If you want to actually remove the Block from the array, and their
relative ordering isn't important, you can do this:

void dropElement(T)(ref T[] arr, size_t i)
{
    assert( i < arr.length );
    arr[i] = arr[$-1];
    arr = arr[0..$-1];
}

That moves the last element into the place of the one you don't want,
then drops the last element of the array.

If the relative ordering DOES matter, then you have to copy the later
elements down the array and drop the last element.


More information about the Digitalmars-d-learn mailing list