Search code examples
ccoordinates2d-gamescoordinate-systems

Drawing a game board in C


Well, as the title says, I'm trying to draw a game board. Well the board itself I did and it looks something like his:

4 |
3 |
2 |
1 |
0 |
   - - - - -
   0 1 2 3 4

but that's not the problem. The thing I find hard is the I wanna draw icons of star shape (*) on the board, and the coordinates are giving in an array like this

posX {2,4,2,1}
posY {2,3,4,4}

so in this case I should draw * in the coordinates (2,2) , (4,3) , (2,4) , (1,4) and so on. Any ideas?


Solution

  • This illustrates what I meant in my comment, perhaps it helps. It prepares an array of strings representing the game board, before printing them.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define BOARDX  5
    #define BOARDY  5
    #define BOARDW  (BOARDX*2)              // length of text line
    
    char board [BOARDY][BOARDW+1];          // allow for string terminator
    
    void print_board(void)
    {
        int y, x;
        for(y=BOARDY-1; y>=0; y--) {
            printf("%-2d|%s\n", y, board[y]);
        }
    
        printf("   ");
        for(x=0; x<BOARDX; x++)
            printf(" -");
        printf("\n");
    
        printf("   ");
        for(x=0; x<BOARDX; x++)
            printf("%2d", x);
        printf("\n");
    }
    
    void empty_board(void)
    {
        int y, x;
        for(y=0; y<BOARDY; y++) {
            for(x=0; x<BOARDW; x++) {
                board[y][x] = ' ';
            }
            board[y][x] = '\0';
        }
    }
    
    void poke_board(int x, int y, char c)
    {
        if (y >= 0 && y < BOARDY && x >= 0 && x < BOARDX)
           board[y][x*2+1] = c;               // correctly spaced
    }
    
    int main(void)
    {
        int posX[]= {2,4,2,1};
        int posY[]= {2,3,4,4};
        int len = sizeof(posX) / sizeof(posX[0]);
        int n;
        empty_board();
        for(n=0; n<len; n++) {
            poke_board(posX[n], posY[n], '*');
        }
        print_board();
        return 0;
    }
    

    Program output:

    4 |   * *
    3 |         *
    2 |     *
    1 |
    0 |
        - - - - -
        0 1 2 3 4