views:

450

answers:

4

Hello! I'm trying to make a Tetris-like game in XNA, and currently I'm thinking of what way would be the best to handle it.

This is what I have so far: I have a class called Block, which has for example texture and color tint.

Then I was planning on having everything in a double array, like:

Block[,] blocks = new Block[10,20];

which would then be the full grid.

And then when the blocks move downwards, I was thinking of doing like this:

blocks[x,y+1] = blocks[x,y];

blocks[x,y] = null;

At first I thought this was a good idea, but now when I've been thinking I'm not so sure. How does it work with the memory and such? Does it create a new object every time I do that or what? Could someone please explain how it actually works when I move an object inside an array?

I'm not really looking for a Tetris-specific answer, I'm just interested in how it actually works.

Thanks.

+2  A: 

No, you're just moving pointers around. When you say:

blocks[x,y+1] = blocks[x,y];

what you're essentially doing is swapping the pointer. The object will stay exactly where it is, but now instead of it being at index x,y it'll be at index of x , y+1. When you say

blocks[x,y] = null;

there you're removing the reference to the object x,y and if nothing else is holding a reference, the Garbage Collecter will clean it up.

BFree
A: 

If you were storing value types (such as int, string) inside your array, you would indeed be creating a copy of the data each time you copied a value over, because value types are immutable in C#. Since you're storing a class (which is a reference type) in your array, your code is really just making a copy of the pointer, not the whole object.

davogones
A: 

How about something a bit more clever. Your Tetris board is basically a queue right? List<T> may help:

/* assumes blocks[0] is the bottom row and you build upwards
   towards blocks.Count */
List<Block[]> blocks = new List<Block[]>();

void EatBottomRow()
{
    blocks.RemoveAt(0);
}

Simple? Still usable from an indexing perspective too!

sixlettervariables
A: 

The first answer above is almost correct, but the assignment is not swapping the pointer, it is duplicating it. After the first line of code there are two references to the object originally referenced at blocks[x,y]. The null assignment removes the original reference, but you still have the new reference living at blocks[x,y+1]. Null that one and the heap object will be fair game for the GC.

bojolais