#include <stdio.h>
#include <string.h>
#define SIZE 3
// 函数声明
void printBoard(char board[SIZE][SIZE]);
int checkWin(char board[SIZE][SIZE], char player);
int isBoardFull(char board[SIZE][SIZE]);
void getUserInput(char board[SIZE][SIZE], char player);
int main() {
char board[SIZE][SIZE];
int gameover = 0;
char currentPlayer = 'X';
// 初始化棋盘
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = '-';
}
}
while (!gameover) {
printBoard(board);
getUserInput(board, currentPlayer);
if (checkWin(board, currentPlayer)) {
printf("Player %c wins!\n", currentPlayer);
gameover = 1;
}
else if (isBoardFull(board)) {
printf("It's a draw!\n");
gameover = 1;
}
else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
return 0;
}
void printBoard(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int checkWin(char board[SIZE][SIZE], char player) {
// 检查行、列和对角线
for (int i = 0; i < SIZE; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return 1;
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return 1;
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) return 1;
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) return 1;
return 0;
}
int isBoardFull(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == '-') return 0;
}
}
return 1;
}
void getUserInput(char board[SIZE][SIZE], char player) {
int row, col;
do {
printf("Player %c, enter your move (row and column): ", player);
scanf("%d %d", &row, &col);
if (board[row][col] != '-') {
printf("Invalid move, try again.\n");
}
} while (board[row][col] != '-');
board[row][col] = player;
}
标签:return,int,三子,char,player,board,人人,SIZE
From: https://blog.csdn.net/2301_80359017/article/details/139902587