我在控制臺中列印 Tic tac Toe Board 時遇到問題,今天開始制作,(實際上我剛開始),我創建了一個顯示板的函式,drawBoard() 函式,但是當我使用 playerMove() 函式在板的單元格中實際列印 X 時,它會列印給我,但它會將其后的所有內容隔開,因此它基本上將該行中的每一列隔開,從而破壞了表格。例如,如果 a 將 x 放在第一個單元格中,則該行中的所有內容都會移動 1 個空格。
這是我現在寫的:
#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';
}
謝謝大家 :)
uj5u.com熱心網友回復:
用空格而不是空字符初始化板。
// char trisBoard[3][3];
char trisBoard[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
或者在 中start(),如果重新開始游戲,這會有所幫助。
memcpy(trisBoard, ' ', sizeof trisBoard);
您還需要更改您的drawBoard函式以適應trisBoard. printf是行緩沖的,所以一般來說,建議將新行放在字串的末尾而不是開頭。IMO,即使您使用每方格 3 個字符、之前的空格、x 或 o 以及之后的空格,事情也會更多:
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");
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/356309.html
上一篇:零大小陣列未在結構內對齊
