#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MAX_ROW 3
#define MAX_COL 3
char chess_board[MAX_ROW][MAX_COL];
int Init(){
for (int row = 0; row < MAX_COL; row++){
for (int col = 0; col < MAX_COL; col++){
chess_board[row][col] = ' ';
}
}
srand(0);
}
void Print(){
for (int row = 0; row < MAX_COL; row++){
printf("| %c | %c | %c | \n", chess_board[row][0], chess_board[row][1], chess_board[row][2]);
if (row != MAX_ROW - 1){
printf("|---|---|---|\n");
}
}
}
void PlayerMove(){
printf("玩家落子!\n");
while (1){
printf("请输入落子位置坐标(row col):");
int row = 0;
int col = 0;
scanf("%d %d", &row, &col);
if (row < 0 || row >= MAX_ROW || col < 0 || col >= MAX_COL){
printf("坐标错误。请重新输入!\n");
continue;
}
if (chess_board[row][col] != ' '){
printf("该位置已有落子!\n");
continue;
}
chess_board[row][col] = 'x';
break;
}
printf("玩家落子完毕!\n");
}
int ComputerMove(){
printf("电脑落子!\n");
while (1){
int row = rand() % 3;
int col = rand() % 3;
if (chess_board[row][col] != ' '){
continue;
}
chess_board[row][col] = 'o';
break;
}
printf("落子完毕!\n");
}
char CheckWinner(){
for (int row = 0; row < MAX_ROW; row++){
if (chess_board[row][0] == chess_board[row][1] && chess_board[row][0] == chess_board[row][2]){
return chess_board[row][0];
}
}
for (int col = 0; col < MAX_COL; col++){
if (chess_board[0][col] == chess_board[1][col] && chess_board[0][col] == chess_board[2][col]){
return chess_board[0][col];
}
}
if (chess_board[0][0] == chess_board[1][1] && chess_board[0][0] == chess_board[2][2]){
return chess_board[0][0];
}
if (chess_board[0][2] == chess_board[1][1] && chess_board[0][2] == chess_board[2][0]){
return chess_board[0][2];
}
char q;
if (IsFull()){
return q;
}
return ' ';
}
int IsFull(){
for (int row = 0; row < MAX_ROW; row++){
for (int col = 0; col < MAX_COL; col++){
if (chess_board[row][col] == ' '){
return 0;
}
}
return 1;
}
}
void Game(){
Init();
char winner = ' ';
while (1){
Print();
PlayerMove();
winner = CheckWinner();
if (winner != ' '){
break;
}
ComputerMove();
winner = CheckWinner();
if (winner != ' '){
break;
}
}
if (winner == 'x'){
printf("您赢了!\n");
Print();
}
else if(winner=='o'){
printf("您输了!\n");
Print();
}
else if(winner=='q'){
printf("和棋!\n");
Print();
}
else{
printf("代码出错!\n");
}
}
void main(){
int choice=Menu();
if (choice == 1){
Game();
}
else if (choice == 0){
printf(" Game Over !\n");
}
else{
printf("您的输入有误!\n");
}
}