How can I display the chess board content as strings in C language and store the strings in a table?

2k Views Asked by At

How can I display the chess board content as strings in C language (the chess pieces and dots or spaces for the empty spots) and store the strings in a table ? I can show what I have already done.

2

There are 2 best solutions below

3
Support Ukraine On BEST ANSWER

In general what you need is an 8x8 array of strings. Since C strings are them selves zero-terminated char arrays, it ends up as a 3D char array.

Something like:

#define MAX_TEXT 30
char board[8][8][MAX_TEXT];

int i, j;
for (i=0; i<8; ++i)
{
    for (j=0; j<8; ++j)
    {
        strcpy(board[i][j], ".");  // Make all spots empty
    }
}

strcpy(board[0][1], "knight"); // Put a knight at location (0, 1)

// and so on ...

Update due to comment

To place the 4 knights using loops, you can do something like:

for (i=0; i<8; i = i + 7)  // i will be 0 and 7
{
    for (j=1; j<8; j = j + 5)  // j will be 1 and 6
    {
        strcpy(board[i][j], "knight"); // Put a knight at location (0, 1)
                                       //                          (0, 6)
                                       //                          (7, 1)
                                       //                          (7, 6)
    }
}

p.s. I hope the locations are the correct once - I'm not a chess player...

14
David Ranieri On
char board[][sizeof("♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜")] = {
    {"♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜"},
    {"♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟"},
    {"… … … … … … … …"},
    {"… … … … … … … …"},
    {"… … … … … … … …"},
    {"… … … … … … … …"},
    {"♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙"},
    {"♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖"}
};

Each piece of the board and the dots are multibyte characters

strlen("♜") == 3

strlen("…") == 3

An example moving the horse:

♜ … ♝ ♛ ♚ ♝ ♞ ♜
♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟
… … ♞ … … … … …

#define ROWS 8
#define DOT "…"
#define MBSZ sizeof(DOT)
#define CELLS (MBSZ + 1)

char *pt1 = board[0] + (CELLS * 1); /* 1 cell */
char *pt2 = board[2] + (CELLS * 2); /* 2 cells */

memmove(pt2, pt1, MBSZ);
memmove(pt1, DOT, MBSZ);

for (int i = 0; i < ROWS; i++) {
    printf("%s\n", board[i]);
}