基于 C 控制台的 Tic Tac Toc 游戏中的间距问题

Spacing problem in a C console based Tic Tac Toc game

我在控制台打印 Tic tac Toe Board 时遇到问题,今天开始制作,(实际上我才开始),我创建了一个显示棋盘的功能, drawBoard() 函数,但是当我使用 playerMove() 函数时,要在板的一个单元格中实际打印 X,它会打印它,但它 space 后面的所有内容,所以它基本上 space 该行的每一列,破坏 table。因此,例如,如果将 x 放在第一个单元格中,则该行中的所有内容都会移动 1 space.

这是我现在写的:

#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';
    
}

感谢大家:)

用 space 初始化棋盘而不是 空字符

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

或在 start() 中,如果重新开始游戏,这会有所帮助。

memcpy(trisBoard, ' ', sizeof trisBoard);

您还需要更改 drawBoard 函数以适应 trisBoard 中的初始化更改。 printf 是行缓冲的,所以一般来说,建议将新行放在字符串的末尾而不是开头。 IMO,即使你每个方块使用 3 个字符,事情也会更多,一个 space 之前,x 或 o,以及一个 space 之后:

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