TicTacToe打印赢家

时间:2014-06-26 02:32:48

标签: c arrays string printf tic-tac-toe

我正在尝试与两名玩家进行一次tic tac toe游戏。我很远,它在大多数情况下都有效。我无法弄清楚如何打印出存储在数组中的字符串。我看过很多循环作为例子。请让我知道最新消息。

在这里输入代码

    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);}

}

2 个答案:

答案 0 :(得分: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]和所有可能的组合很快就会成为人类编码的代价。另一方面,计算机喜欢重复执行相同(或类似)的任务。这取决于人(你)确保能量用在有用的东西上。

答案 1 :(得分:0)

我认为你在printf有问题,因为player1和player2是char **但是printf需要char *。