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.
How can I display the chess board content as strings in C language and store the strings in a table?
2k Views Asked by J.Doe At
2
There are 2 best solutions below
14
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]);
}
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:
Update due to comment
To place the 4 knights using loops, you can do something like:
p.s. I hope the locations are the correct once - I'm not a chess player...