簡體   English   中英

如何在井字游戲中預測玩家 X 或 O 的獲勝位置並告訴用戶該位置?

[英]How can I predict the winning position for player X or O in a tic tac toe game and tell the user the position?

所以我編寫了一個函數,允許用戶查找輪到任何玩家 X 或 O 的任何下一步行動或下一步行動是否是獲勝行動。 該函數將打印單元號或 ID,如果玩家在其中放置 X 或 O,他/她將贏得游戲。 如果玩家可以在多個單元格中放置他的符號並贏得游戲,則該函數應打印該玩家的所有獲勝單元格。

I made a simple implementation of the code but it seems to work but not print right position. Any help would be great. Thanks.

void ListWinningCells(int m, int n, char board[][n])
{
    int check = IsValidBoard(m, n, board);
    if(check == 1){
        // for row:
        if((board[0][0] == 'X' || board[0][0] == 'O') && (board[0][2] == 'X' || board[0][2] == 'O')){
            printf("Winning cell is 2 for player %c\n", board[0][0]);
        }
        if((board[1][0] == 'X' || board[1][0] == 'O') && (board[1][2] == 'X' || board[1][2] == 'O')){
           printf("Winning cell is 5 for player %c\n", board[0][0]);
        }
        if((board[2][0] == 'X' || board[2][0] == 'O') && (board[2][2] == 'X' || board[2][2] == 'O')){
            printf("Winning cell is 8 for player %c\n", board[0][0]);
        }

        // for column
        if((board[0][0] == 'X' || board[0][0] == 'O') && (board[2][0] == 'X' || board[2][0] == 'O')){
            printf("Winning cell is 4 for player %c\n", board[0][0]);
        }
        if((board[0][1] == 'X' || board[0][1] == 'O') && (board[2][1] == 'X' || board[2][1] == 'O')){
            printf("Winning cell is 5 for player %c\n", board[0][0]);
        }
        if((board[0][2] == 'X' || board[0][2] == 'O') && (board[2][2] == 'X' || board[2][2] == 'O')){
            printf("Winning cell is 6 for player %c\n", board[0][0]);
        }

        // for diagonal
        if((board[0][0] == 'X' || board[0][0] == 'O') && (board[2][2] == 'X' || board[2][2] == 'O')){
            printf("Winning cell is 5 for player %c\n", board[0][0]);
        }
        if((board[0][2] == 'X' || board[0][2] == 'O') && (board[2][0] == 'X' || board[2][0] == 'O')){
            printf("Winning cell is 5 for player %c\n", board[0][0]);
        }
    }
    else{
       IsValidBoard(m, n, board); 
    }
}

讓我們來看看你的第一個 if 語句:

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

如果 'X' 在 board[0][0] 上,而 'O' 在 board[0][2] 上,則該語句為真,但這是不正確的。 它應該是:

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

所以它會返回獲勝單元格為2。您還應該考慮某些情況沒有被考慮在內,因為單元格1和單元格3是獲勝單元格,我不知道這是不是故意的。

您還應該考慮使用 for 循環來檢查位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM