Home > Software design >  Spacing problem in a C console based Tic Tac Toc game
Spacing problem in a C console based Tic Tac Toc game

Time:11-12

I've a problem in printing the Tic tac Toe Board in the console, began to make it today, (in fact i'm at the beginning),i've created a function that display the board, the drawBoard() function, but when i use the playerMove() function, to actually print the X in a cell of the board, it print me it, but it space everything after it, so it basically space every column in that row, destroying the table. so for example if a put the x in the first cell, everything in that row move of 1 space.

here what i wrote for now :

#include <stdio.h>

void drawBoard();
void start();
void playerMove();
void computerMove();


char trisBoard[3][3];
short computerPoint;
short playerPoint;
short playerRow;
short playerColumn;


int main() {
start();
return 0;
}

void drawBoard() 
{
   printf("\n");
   printf("   Tris Game\n");
   printf("\n");
   printf(" %c   | %c   | %c", trisBoard[0][0], trisBoard[0][1], trisBoard[0][2]);
   printf("\n----|----|----      \n");
   printf(" %c   | %c   | %c",  trisBoard[1][0], trisBoard[1][1], trisBoard[1][2]);
   printf("\n----|----|----");
   printf("\n %c   | %c   | %c \n",  trisBoard[2][0], trisBoard[2][1], trisBoard[2][2]);
   printf("\n");
}

void start() 
{
    for(int x = 0; x < 9; x  ) {
        drawBoard();
        playerMove();
}   
}

void playerMove() 
{
    printf("It's your turn, where do you wanna instert the X ? \n");

    printf("Insert the row (first number is 0) \n");
    scanf("%d", &playerRow);

    printf("Insert a column (first number is 0) \n");
    scanf("%d", &playerColumn);

    trisBoard[playerRow][playerColumn] = 'x';
    
}

thanks to everyone :)

CodePudding user response:

Initialize the board with spaces rather than the null character.

// char trisBoard[3][3];
char trisBoard[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};

Or in start(), which helps if the game is re-started.

memcpy(trisBoard, ' ', sizeof trisBoard);

You also need to change up your drawBoard function to accommodate the initialization change in trisBoard. printf is line-buffered, so in general, recommend putting new lines at the end of the string rather than the beginning. IMO, things will be more even if you use 3 characters per square, a space before, the x or o, and a space after:

void drawBoard() 
{
   printf("\n");
   printf("   Tris Game\n");
   printf("\n");
   // the vertical bars don't line up now, but they will when the board
   // prints because %c will be replaced by one char.
   printf(" %c | %c | %c\n", trisBoard[0][0], trisBoard[0][1], trisBoard[0][2]);
   printf("---|---|---\n");
   printf(" %c | %c | %c\n",  trisBoard[1][0], trisBoard[1][1], trisBoard[1][2]);
   printf("---|---|---\n");
   printf(" %c | %c | %c\n",  trisBoard[2][0], trisBoard[2][1], trisBoard[2][2]);
   printf("\n");
}

Demo

  • Related