On Thu, 22 Jul 2010 17:21:15 -0400, dcoder <[email protected]> wrote:

== Quote from Steven Schveighoffer ([email protected])'s article
This is what I think you should use:
string[int[2]]
Although, I'm not sure if you can then do something like:
chessboard[[0,1]] = "Rook";
as the [0, 1] is typed as a dynamic array.  If it does work, it may
actually create [0,1] on the heap and then pass it as an int[2], which
would suck.

board[[0,0]] = "Rook";

seems to work. thanks. But, the foreach loop looks strange. It looks like it
takes the hash value of the key:

 string[int[2]] board;

  board[[0,0]] = "Rook";
  board[[0,1]] = "Knight";

  foreach( pos, val; board) {
    writefln( "%s: %s", pos, val);
  }


Output:

2 9903680: Knight
2 9903696: Rook

It may be represented properly inside the AA. There are currently some bugs with AA's and using foreach.

Or, if you know how big your chessboard is (8x8 isn't a lot of memory),
then:
string[8][8] chessboard;
is pretty straightforward :)

Yes it is :)  Hehe....


Now, what if I wanted to do the following:


class Board {
  string[][] positions;

  this( int x, y) {
      // set the size of positions
  }
}

I want positions to internally represent a chess board, a tic tac toe board, or a
Connect Four board, etc...

But, I want to fix the dimensions of the board when the board gets instantiated, so that I can have the compiler do all the work of bounds checking for me. I can create class variables maxx, maxy and access functions that check against the variables, but I'm wondering if there's a way to make the compiler do it for you.

Is there a way?

If you want it to be "compile-time-decided" but not hard-coded to 8x8:

class Board(int width, int height)
{
   string[width][height] positions;
}

Then you do:

auto brd = new Board!(8, 8);

-Steve

Reply via email to