编辑代码

#include <stdio.h>

char board[3][3]; // The tic-tac-toe board

void initialize_board() 
{
    // Initialize the board with empty spaces
    for (int row = 0; row < 3; row++)
    {
        for (int col = 0; col < 3; col++)
        {
            board[row][col] = ' ';
        }
    }
}

void print_board()
{
    // Print the current state of the board
    printf(" %c | %c | %c \n", board[0][0], board[0][1], board[0][2]);
    printf("---+---+---\n");
    printf(" %c | %c | %c \n", board[1][0], board[1][1], board[1][2]);
    printf("---+---+---\n");
    printf(" %c | %c | %c \n", board[2][0], board[2][1], board[2][2]);
}

int check_win(char player)
{
    // Check if the specified player has won
    for (int i = 0; i < 3; i++)
    {
        if (board[i][0] == player &&
            board[i][1] == player &&
            board[i][2] == player)
        {
            return 1; // Horizontal win
        }
        if (board[0][i] == player &&
            board[1][i] == player &&
            board[2][i] == player)
        {
            return 1; // Vertical win
        }
    }
        if (board[0][0] == player &&
            board[1][1] == player &&
            board[2][2] == player)
        {
            return 1; // Diagonal win(top-left to bottom-right)
        }
        if (board[0][2] == player &&
            board[1][1] == player &&
            board[2][0] == player)
        {
            return 1; // Horizontal win(top-right to bottom-left)
        }
        return 0; // No win
    
}

int main()
{
    int row, col;
    char player = 'X';

    initialize_board();
    while (1)
    {
        printf("Player %c's turn.\n", player);
        printf("Enter row (0-2): ");
        scanf("%d", &row);
        printf("Enter column (0-2): ");
        scanf("%d", &col);

        if (row < 0 || row > 2 || col < 0 || col > 2)
        {
            printf("Invalid input. Try again.\n");
            continue;
        }

        if (board[row][col] != ' ')
        {
            printf("That space is already occupied. Try again.\n");
            continue;
        }

        board[row][col] = player;
        print_board();

        if (check_win(player))
        {
            printf("Player %c wins!\n", player);
            break;
        }

        if (player == 'X')
        {
            player = 'O';
        }
        else
        {
            player = 'X';
        }
    }
    return 0;
}