2014-06-26 67 views
0

我想與兩名玩家進行一次tic tac toe遊戲。我很遠,它的大部分工作。我無法弄清楚如何打印出存儲在數組中的字符串。我看過很多循環作爲例子。請讓我知道最新消息。TicTacToe打印贏家

輸入代碼在這裏

int main() 
    { time_t t; 
char player1 [23]; 
char player2 [23]; 
int Let; 
int Turns = 0; 

printf("\n Welcome to Galactic Tic Tac Toe:\n"); 
    printf("\n Please enter player 1's name"); 
    fgets(player1, 22, stdin); 
    printf("\nPlayer 2's name?\n"); 
    fgets(player2, 22, stdin); 

void winner (char board [][9], char player1 [][23], char player2 [][23]){ 
if (board [0][0] && board [0][1] && board [0][2] == 'X'){printf("\nPlayer 1 has won\n Congratulations : %s ", player1);} 
if (board [0][3] && board [0][4] && board [0][5] == 'X'){printf("\nPlayer 1 has won\n Congratulations : %s ", player1);} 
if (board [0][6] && board [0][7] && board [0][8] == 'X'){printf("\nPlayer 1 has won\n Congratulations : %s ", player1);} 
if (board [0][0] && board [0][1] && board [0][2] == 'O'){printf("\nPlayer 2 has won\n Congratulations : %s ", player2);} 
if (board [0][3] && board [0][4] && board [0][5] == 'O'){printf("\nPlayer 2 has won\n Congratulations : %s ", player2);} 
if (board [0][6] && board [0][7] && board [0][8] == 'O'){printf("\nPlayer 2 has won\n Congratulations : %s ", player2);} 
if (board [0][0] && board [0][5] && board [0][8] == 'X'){printf("\nPlayer 1 has won\n Congratulations : %s ", player1);}  
if (board [0][2] && board [0][5] && board [0][7] == 'X'){printf("\nPlayer 1 has won\n Congratulations : %s ", player1);} 
if (board [0][0] && board [0][5] && board [0][8] == 'O'){printf("\nPlayer 1 has won\n Congratulations : %s ", player2);} 
if (board [0][2] && board [0][5] && board [0][7] == 'O'){printf("\nPlayer 1 has won\n Congratulations : %s ", player2);} 

} 
+0

我可以添加開始代碼以及幫助。老實說,我始終沒有真正理解打印循環以及爲什麼它們通常用於數組。 – user3769362

+0

對不起,就像我說的全新的,我剛剛發佈它,我想我搞砸了初始化...也許 – user3769362

回答

3

你最大的問題:

if (board [0][0] && board [0][1] && board [0][2] == 'X') 

做你認爲它。您可能認爲這會檢查是否所有這三個空間都標有'X'。這是不正確的。

&&是一個布爾AND運算符,這意味着左側和右側運算符被獨立評估爲布爾值。那麼,你已經寫手段:

if (     // if 
    board[0][0]   // board[0][0] is non-zero 
    &&     // and 
    board[0][1]   // board[0][1] is non-zero 
    &&     // and 
    board[0][2] == 'X' // board[0][2] is equal to 'X' 
) 

您還沒有表現出你如何(中間有空格' '大概)初始化你的董事會,但無論(打印)字符,你存儲在那裏將作爲一個布爾評價。

所以這個表達式應該是:

if ((board[0][0] == 'X') && (board[0][1] == 'X') && (board[0][2] == 'X')) 

下一個問題:

老實說,我一直都沒有真正瞭解打印循環,爲什麼他們通常用於陣列。

那麼有沒有這樣的事情作爲打印循環。只有迴路。如果你願意,你可以在循環中調用printf

爲了理解爲什麼我們需要循環,考慮一個不同版本的Tic-Tac-Toe,板子的尺寸是100 x 100.你的「有人贏了嗎?」邏輯看起來像嗎?

應該很容易看出編碼if(board[0][0] .... board[99][99]以及所有可能的組合將很快耗盡人類的代碼。另一方面,計算機喜歡重複地執行相同的(或類似的)任務。人類(你)需要確保能量花費在有用的東西上。

+0

是的,這絕對需要修復! +1 –

+0

好的,所以生病只是將它們分開, – user3769362

+0

這將是瘋了,感謝您的幫助。這裏是初始化。 – user3769362

0

我認爲你在printf有問題,因爲player1和player2是char **,但是printf需要char *。

+0

我將如何改變? – user3769362