Search code examples
cc-stringschessstring-table

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


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.


Solution

  • 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...