Hypergardens
Hypergardens

Reputation: 151

How do I refer to nameless objects by their properties?

How can I refer to nameless objects? For a game, if I'm making a square grid and using something like

for (int X =0; X <= 10; X++)
{
    for(int Y =0; Y <= 10; Y++)
    {
        new Cell(X, Y);
    }
}

I'm going to have 100 cells with no name. How do I modify or check them afterwards, perhaps referring to them by their coords, such as

ThisCell.DoSomething();

referring to the cell by its coords or something

Halp. I can't just have 1000 or more cells each with their own little pet name to call on. There's got to be a way to check, for examples, the neighbors of something by something's coords WITHOUT MAKING NEW CELLS...

Basically the problem I'm having is that for each neighbor check, for example, I'm creating new, default cells which return the wrong values.

If any of you could, for example, give me a good function which checks the boolean IsWalkable of its upward neighbor... I would appreciate it tremendously

Upvotes: 0

Views: 314

Answers (2)

MikeH
MikeH

Reputation: 4395

You'll want to create an array of your type Cell:

Cell[,] myCells = new Cell[10,10]

change new Cell(X, Y); to myCells[X,Y] = new Cell();

From there you can always refer to any cell: myCells[1,2].DoSomething();

Upvotes: 2

Matt Burland
Matt Burland

Reputation: 45155

Create an array then store your cells in it

Cell[,] cells = new Cell[10,10];
for (int X =0; X <= 10; X++)
{
    for(int Y =0; Y <= 10; Y++)
    {
        cells[X,Y] = new Cell(X, Y);
    }
}

To retrieve a cell late, you just use it's x and y coordinates to index the array:

Cell someCell = cells[5,5];   // for example

It's easy to find neighbors by just manipulating the coordinates. For example, if each cell also has it's own X and Y coordinates (which your constructor parameters suggest) you could do something like:

Cell cellAboveMe = cells[someCell.X, someCell.Y - 1]; 

Although note that you'll want to include boundary checking (if Y==0 then there is no cell above this cell)

This is pretty fundamental stuff, so you'll want to read up on how arrays work. See here:

http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

For example.

Upvotes: 1

Related Questions