Sign in to follow this  
Welshy

Setting up a checkers board

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 this post


Link to post
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 this post


Link to post
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 );
...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this