Public Group

Setting up a checkers board

This topic is 4880 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

So im making a console checkers game, as my minesweeper code was a bit of a mess i intend to learn from it. Anyway! In my board constructor im setting up the board, putting the right pieces in the right squares, and i was wondering if there was a way i could do it without needing to use so much code. At the moment im doing it as:
	int x = 1;
int y = 1;

board[x][y].setPiece = true;
board[x][y].setColour = 2;
board[x][y].setRank = 1;

y = 3;

board[x][y].setPiece = true;
board[x][y].setColour = 2;
board[x][y].setRank = 1;
...
There must be an easier, quicker and simpler way, because i feel stupid doing it this way. I thought i could use a for loop, and increment the variable by 2, which would halve my code at least, any ideas? Thanks

Share on other sites
A couple of ways:

for (x=1; x<=8; x++ ) {    for (y=1; y<=3; y++ ) {        if ( ((x + y) % 2) == 0 ) {	    board[x][y].setPiece = true;	    board[x][y].setColour = 2;	    board[x][y].setRank = 1;        }    }}

or even

for (x=1; x<=7; x += 2) {    for (y=1; y<=3; y += 2) {	board[x][y].setPiece = true;	board[x][y].setColour = 2;	board[x][y].setRank = 1;    }}for (x=2; x<=8; x += 2) {    board[x][2].setPiece = true;    board[x][2].setColour = 2;    board[x][2].setRank = 1;}

The sum of the x and y positions is always even, so you use the mod test in the first example. Two things:

1. Although the first code example is the most compact, this is actually slower than your method, since all 24 squares in the first 3 ranks are tested instead of just the twelve squares that need the piece.

2. This part of the code won't be a bottleneck, since it is quick and only done once per game. Shouldn't spend much time with this.

Share on other sites
ah thanks for the help :)

Share on other sites
You could use a for-loop, but here are some additional improvements:
    struct Piece    {        enum Colour { COLOUR_NONE, COLOUR_RED, COLOUR_BLACK };                Piece()            : setColour( COLOUR_NONE ), setRank( 0 ), setPiece( false )        {        }        Piece( Colour colour )            : setColour( colour ), setRank( 1 ), setPiece( true )        {        }                Colour setColour;        int setRank;        bool setPiece;    };        ...            board[0][0] = Piece( COLOUR_RED );        board[0][2] = Piece( COLOUR_RED );        board[0][4] = Piece( COLOUR_RED );        board[0][6] = Piece( COLOUR_RED );        ...

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• Forum Statistics

• Total Topics
633388
• Total Posts
3011614
• Who's Online (See full list)

There are no registered users currently online

×