# Using data structures to build chess

Page 1 of 1

## 13 Replies - 13596 Views - Last Post: 22 January 2011 - 05:56 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=211397&amp;s=7315acf62724ecad0184be36175ca839&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 elcarn_23

Reputation: 0
• Posts: 6
• Joined: 21-January 10

# Using data structures to build chess

Posted 22 January 2011 - 09:59 AM

Hi I have been trying to figure out how to use data structures to build a simple chess game. What I'm trying to do is create a 2 dimensional array the board with each square a piece each with a name and color associated with it. When I try to build the board I'm trying to dynamically allocate each space to hold a piece value and for the life of me I can't get it to work. I'm just wondering if someone can point me in the right direction to find the information I need. I've tried a number of methods and this is what I have right now.

```#include <iostream>
using namespace std;

struct Piece
{
//Name will be a single char value ex. R, K, Q, p
char name;

//Color will be a single char value ex. b, w
char color;

//Position will contain two coordinate points row first and column second
int row;
int col;

};

const Piece Rook   = {'R'};
const Piece Knight = {'N'};
const Piece Bishop = {'B'};
const Piece King   = {'K'};
const Piece Queen  = {'Q'};
const Piece Pawn   = {'p'};
const Piece Empty  = {' '};

void drawBoard(Piece pieces[][8]);

int main (int argc, char * const argv[])
{
Piece pieces[8][8];

drawBoard(pieces);

return 0;
}

void drawBoard(Piece pieces[][8])
{
//Black pieces are going to be all lower case and white pieces are going to be upper case

//array location new type  name  color
pieces[7][0] = new Rook   ('R', 'b');
pieces[7][1] = new Knight ('N', 'b');
pieces[7][2] = new Bishop ('B', 'b');
pieces[7][3] = new King   ('K', 'b');
pieces[7][4] = new Queen  ('Q', 'b');
pieces[7][5] = new Bishop ('B', 'b');
pieces[7][6] = new Knight ('N', 'b');
pieces[7][7] = new Rook   ('R', 'b');

//set the blank pieces and pawns
for (int col = 0; col <= 7; col++)
pieces[6][col] = new Pawn('p', 'b');

for (int col = 0; col <= 7; col++)
pieces[5][col] = new Empty(' ', 'e');

for (int col = 0; col <= 7; col++)
pieces[4][col] = new Empty(' ', 'e');

for (int col = 0; col <= 7; col++)
pieces[3][col] = new Empty(' ', 'e');

for (int col = 0; col <= 7; col++)
pieces[2][col] = new Empty(' ', 'e');

for (int col = 0; col <= 7; col++)
pieces[1][col] = new Pawn('p', 'w');

//set the black pieces

pieces[0][0] = new Rook  ('R', 'w');
pieces[0][1] = new Knight('N', 'w');
pieces[0][2] = new Bishop('B', 'w');
pieces[0][3] = new King  ('K', 'w');
pieces[0][4] = new Queen ('Q', 'w');
pieces[0][5] = new Bishop('B', 'w');
pieces[0][6] = new Knight('N', 'w');
pieces[0][7] = new Rook  ('R', 'w');

cout << "   A  B  C  D  E  F  G  H \n";

//Use a standard for loop in order to set the board with row and column label
for (int row = 7; row >= 0; row--)
{
cout << row + 1 << " ";
for (int col = 0; col <= 7; col++)
{
cout << " " << pieces[row][col].name << " ";
}
cout << endl;
}

}

```

Is This A Good Question/Topic? 0

## Replies To: Using data structures to build chess

### #2 Oler1s

• D.I.C Lover

Reputation: 1397
• Posts: 3,884
• Joined: 04-June 09

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:09 AM

Quote

I'm trying to dynamically allocate
If this is the case, explain:

```Piece pieces[8][8];

```

That's within the main function. If you want to dynamically allocate pieces, why are you auto allocating an array?

This post has been edited by Oler1s: 22 January 2011 - 10:10 AM

### #3 elcarn_23

Reputation: 0
• Posts: 6
• Joined: 21-January 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:20 AM

Oler1s, on 22 January 2011 - 10:09 AM, said:

Quote

I'm trying to dynamically allocate
If this is the case, explain:

```Piece pieces[8][8];

```

That's within the main function. If you want to dynamically allocate pieces, why are you auto allocating an array?

I originally had it as Piece * pieces but I was getting all sorts of errors I then tried to do a typedef Piece * piecesPtr and then set that to an array called board making every spot a new character and still received errors I've been through my reference book trying to figure out how to do this but at this point I'm completely turned around to be honest.

This post has been edited by elcarn_23: 22 January 2011 - 10:22 AM

### #4 anonymous26

• D.I.C Lover

Reputation: 2
• Posts: 3,638
• Joined: 26-November 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:27 AM

I've noticed that you are passing in what is effectively the board by value with the function prototype

```void drawBoard(Piece pieces[][8])

```

You should really be passing this in by reference, so revise your function thus:

```void drawBoard(Piece (*board)[8])

```

elcarn_23, on 22 January 2011 - 05:20 PM, said:

Oler1s, on 22 January 2011 - 10:09 AM, said:

Quote

I'm trying to dynamically allocate
If this is the case, explain:

```Piece pieces[8][8];

```

That's within the main function. If you want to dynamically allocate pieces, why are you auto allocating an array?

I originally had it as Piece * pieces but I was getting all sorts of errors I then tried to do a typedef Piece * piecesPtr and then set that to an array called board making every spot a new character and still received errors I've been through my reference book trying to figure out how to do this but at this point I'm completely turned around to be honest.

No allocation should be happening in your drawBoard() function. You are creating all sorts of problems for yourself. Pass in the board as a complete object and change its state within the function, not the amount of memory it occupies.

This post has been edited by ButchDean: 22 January 2011 - 10:28 AM

### #5 Oler1s

• D.I.C Lover

Reputation: 1397
• Posts: 3,884
• Joined: 04-June 09

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:31 AM

ButchDean said:

You should really be passing this in by reference, so revise your function thus:
The two forms are equivalent. There's no such thing as an array without a size. void foo(int a[]) is syntactic sugar for void foo(int (*a)).

Quote

That will pass your board in by reference
No, it will not. Identifying pass by reference is easy. There's an &. Both forms you have indicated pass by value, where the value is a pointer (in particular, pointer to int [8]).

Quote

You are passing a pointer. You can change the dereferenced value in the function and the change will exist in the calling function.

elcarn_23, you are completely guessing. Please, do not do this again.

Your first objective is to decide whether you want to auto allocate or dynamically allocate. As I noted, Piece pieces[8][8]; auto allocates, so you don't need to dynamically allocate pieces, right?

### #6 elcarn_23

Reputation: 0
• Posts: 6
• Joined: 21-January 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:43 AM

Thank you both for your help. I'll re-evaluate my original design I can see what you are saying. I tried doing this one way and when it didn't work I've since made a mess of it. I appreciate you both for helping me to clarify.

### #7 anonymous26

• D.I.C Lover

Reputation: 2
• Posts: 3,638
• Joined: 26-November 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:51 AM

No problem, elcarn_23. Good luck.

### #8 anonymous26

• D.I.C Lover

Reputation: 2
• Posts: 3,638
• Joined: 26-November 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 10:59 AM

Oler1s, on 22 January 2011 - 05:31 PM, said:

ButchDean said:

You should really be passing this in by reference, so revise your function thus:
The two forms are equivalent. There's no such thing as an array without a size. void foo(int a[]) is syntactic sugar for void foo(int (*a)).

Quote

That will pass your board in by reference
No, it will not. Identifying pass by reference is easy. There's an &. Both forms you have indicated pass by value, where the value is a pointer (in particular, pointer to int [8]).

Quote

You are passing a pointer. You can change the dereferenced value in the function and the change will exist in the calling function.

elcarn_23, you are completely guessing. Please, do not do this again.

Your first objective is to decide whether you want to auto allocate or dynamically allocate. As I noted, Piece pieces[8][8]; auto allocates, so you don't need to dynamically allocate pieces, right?

Anyone would think you don't like me, Oler1s! Please run the following.

```#include <iostream>
using namespace std;

struct Piece
{
//Name will be a single char value ex. R, K, Q, p
char name;
//Color will be a single char value ex. b, w
char color;
//Position will contain two coordinate points row first and column second
int row;
int col;
};

void drawBoard(Piece (*board)[8])
{
board[0][0].name = 'a';
board[7][7].name = 'b';
}

int main()
{
Piece gameBoard[8][8] = {0};

cout << "Values before...\n";
cout << gameBoard[0][0].name << endl;
cout << gameBoard[7][7].name << endl;

drawBoard(gameBoard);

cout << "Values after...\n";
cout << gameBoard[0][0].name << endl;
cout << gameBoard[7][7].name << endl;

return 0;
}

```

Have I missed something?

### #9 Oler1s

• D.I.C Lover

Reputation: 1397
• Posts: 3,884
• Joined: 04-June 09

## Re: Using data structures to build chess

Posted 22 January 2011 - 11:25 AM

Quote

Anyone would think you don't like me, Oler1s!
On the contrary, you have been most civil in your discourse. Technical disagreements don't imply enmity.

Quote

Have I missed something?
Yes you have. You just supported what I said. To quote myself: "You are passing a pointer. You can change the dereferenced value in the function and the change will exist in the calling function."

But here is code for you to run instead.

```#include <iostream>
#include <typeinfo>

void passByVal(int arg[][8])
{
std::cout << "Typeof arg: " << typeid(arg).name() << '\n';
}

void passByRef(int (&rarg)[8][8])
{
std::cout << "Typeof rarg: " << typeid(rarg).name() << '\n';
}

int main()
{
int (*pA)[8];
int a[8][8];

std::cout << "Typeof pA: " << typeid(pA).name() << '\n';
std::cout << "Typeof a: " << typeid(a).name() << '\n';

passByVal(a);
passByRef(a);

passByVal(pA);
// passByRef(pA); Won't compile
}

```

### #10 anonymous26

• D.I.C Lover

Reputation: 2
• Posts: 3,638
• Joined: 26-November 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 12:02 PM

Passing by value and passing by reference are not terms unique to C/C++, so forgive me if I don't specify pointer vs. reference. Regardless, the code works as I implied and there is no need to be splitting hairs to make matters even more confusing.

### #11 Oler1s

• D.I.C Lover

Reputation: 1397
• Posts: 3,884
• Joined: 04-June 09

## Re: Using data structures to build chess

Posted 22 January 2011 - 01:00 PM

Quote

Regardless, the code works as I implied and there is no need to be splitting hairs to make matters even more confusing.
I'm not splitting hairs. You showed pass by value and called it pass by reference. As you noted, the semantics are not C++ specific, and you made a fundamental mistake that is replicated in e.g. Java discussions.

Let my counter argument lie or dispute it. Don't make assertions and then dismiss any counterarguments as semantical fussiness.

### #12 anonymous26

• D.I.C Lover

Reputation: 2
• Posts: 3,638
• Joined: 26-November 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 01:03 PM

Oler1s, on 22 January 2011 - 08:00 PM, said:

Quote

Regardless, the code works as I implied and there is no need to be splitting hairs to make matters even more confusing.
I'm not splitting hairs. You showed pass by value and called it pass by reference. As you noted, the semantics are not C++ specific, and you made a fundamental mistake that is replicated in e.g. Java discussions.

Let my counter argument lie or dispute it. Don't make assertions and then dismiss any counterarguments as semantical fussiness.

I still say you split hairs and that's it. The OP wasn't asking what you seem determined to make a point of, they were asking for help with their code and they got it. Give it a rest.

### #13 baavgai

• Dreaming Coder

Reputation: 7160
• Posts: 14,924
• Joined: 16-October 07

## Re: Using data structures to build chess

Posted 22 January 2011 - 03:31 PM

You can't really do this:
```const Piece Rook   = {'R'};
//...
pieces[7][0] = new Rook   ('R', 'b');

```

It's unclear what you're doing. One approach would be something like:

```#include <iostream>
using namespace std;

struct Piece {
char name, color;
// you really don't need this
// the board knows where it is
// int row, col;
Piece() : name(' '), color(' ') { }
Piece(char n, char c) : name(n), color(c) { }
};

struct Board {
static const int ROWS=8, COLS=8;
Piece pieces[ROWS][COLS];
Board();
void draw();
};

int main (int argc, char * const argv[]) {
Board board;
board.draw();

return 0;
}

Board::Board() {
pieces[7][0] = Piece('R', 'b');
pieces[7][1] = Piece('N', 'b');
pieces[7][2] = Piece('B', 'b');
pieces[7][3] = Piece('K', 'b');
pieces[7][4] = Piece('Q', 'b');
pieces[7][5] = Piece('B', 'b');
pieces[7][6] = Piece('N', 'b');
pieces[7][7] = Piece('R', 'b');
pieces[0][0] = Piece('R', 'w');
pieces[0][1] = Piece('N', 'w');
pieces[0][2] = Piece('B', 'w');
pieces[0][3] = Piece('K', 'w');
pieces[0][4] = Piece('Q', 'w');
pieces[0][5] = Piece('B', 'w');
pieces[0][6] = Piece('N', 'w');
pieces[0][7] = Piece('R', 'w');

for (int col = 0; col <= 7; col++) {
pieces[6][col] = Piece('P', 'b');
pieces[1][col] = Piece('P', 'w');
}
}

void Board::draw() {
cout << "   A  B  C  D  E  F  G  H \n";
for (int row = 7; row >= 0; row--) {
cout << row + 1 << " ";
for (int col = 0; col <= 7; col++) {
cout << " " << pieces[row][col].name << " ";
}
cout << endl;
}

}

```

Though this doesn't help differentiate the pieces. ( Neither did yours. )

If you really wanted a class for each piece, you could do something like:
```struct Piece {
Piece(char w, char b, bool _white) : nameWhite(w), nameBlack(B)/>, white(_white) { }
virtual char getName() const { return white ? nameWhite : nameBlack ; }
virtual bool isWhite() const { return white; }
protected:
char nameWhite, nameBlack;
bool white;
};

struct Rook : public Piece { Rook(bool white) : Piece('R', 'r', white) { } };

//...
Piece *pieces[8][8];
pieces[7][0] = new Rook(true);
pieces[7][7] = new Rook(false);

```

### #14 elcarn_23

Reputation: 0
• Posts: 6
• Joined: 21-January 10

## Re: Using data structures to build chess

Posted 22 January 2011 - 05:56 PM

I'm working primarily with emacs and I've only been programming for about 3 or 4 months so I know I'm making lots of mistakes but I'm trying to understand and learn. This is a snippet of the part of how I was going to differentiate between the two colors while displaying a two colored board this is what I had from the project I was doing with classes but I was trying to take a step back and just use structs to learn more about using them.
```  if (color == true)
{
system("clear");
cout << "   a  b  c  d  e  f  g  h \n";

for (int row = 7; row >= 0; row--)
{
cout << row + 1 << " ";

for (int col = 0; col <= 7; col++)
{

if (((row % 2 == 0) && (col % 2 != 0))
|| ((row % 2 == 1) && (col % 2 != 1)))
{
// White square black piece
if ((pieces[row][col]->color == 'b') || (pieces[row][col]->color == 'e'))
{
cout << "\E[30;47m " << pieces[row][col]->name
<< " \E[0m";
}

// White square white piece
else
{
cout << "\E[31;47m " << pieces[row][col]->name
<< " \E[0m";
}
}
else
{
// Black square black piece
if ((pieces[row][col]->color == 'b') || (pieces[row][col]->color == 'e'))
{
cout << "\E[30;41m " << pieces[row][col]->name
<< " \E[0m";
}

// Black square white piece

else
{
cout << "\E[37;41m " << pieces[row][col]->name
<< " \E[0m";
}
}
}

cout << endl;
}
}

```