0

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.