Daniel Keep Wrote:

> 
> 
> 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.

This function worked quite well.
I ended up just using a normal array, because it made things easier than having 
a 2D array. The order of where the Blocks were in the array didn't matter.
I ended up doing this:
//Check for collision between blocks
for( int i = 0; i < level.length; i++ )
{
        if( checkCollision( ball, level[i].p ) )
        {
                //remove the block
                ballyVel = -ballyVel;
                dropElement( level, i );
                i--;
        }
}
.....
//remove element from arrray
void dropElement(T)(ref T[] arr, size_t i)
{
    assert( i < arr.length );
    arr[i] = arr[$-1];
    arr = arr[0..$-1];
}

Reply via email to