#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//3x3棋盘
//'x'表示玩家棋子 'o'表示电脑棋子 ' ' 未落子
//1.游戏开始时,初始化棋盘,把所有元素设为 ' '.
//2.提示玩家落子,输入一个坐标.
//3.判断胜负.
//4.电脑落子.(基于随机数的方式)
//5.判定胜负
int Menu() {
printf("========================\n");
printf("1.开始游戏\n");
printf("0.结束游戏\n");
printf("========================\n");
int choice = 0;
scanf("%d", &choice);
return choice;
}
#define MAX_ROW 3
#define MAX_COL 3
char chess_board[MAX_ROW][MAX_COL];
void Init() {
//初始化棋盘
for (int row = 0; row < MAX_ROW; ++row) {
for (int col = 0; col < MAX_COL; ++col) {
chess_board[row][col] = ' ';
}
}
srand((unsigned int)time(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]);
printf(" ---|---|---|\n");
}
}
void PlayerMove() {
printf("玩家请落子\n");
while (1) {
printf("请输入落子坐标(row,col):\n");
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");
}
void 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");
}
//棋盘满返回1,否则返回0
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;
}
//返回值 ‘x’表示玩家胜
//返回值 ‘o’表示电脑胜
//返回值 ‘q’表示和棋
//返回值 ‘ ’表示胜负未分
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];
}
//和棋 棋盘满但未分胜负
if (IsFull()) {
return 'q';
}
return ' ';
}
void Game() {
//1.初始化棋盘
Init();
char winner = ' ';
while (1){
//2.打印棋盘
Print();
//3.玩家落子
PlayerMove();
//4.判断胜负
winner=CheckWinner();
if (winner != ' ') {
break;
}
//5.电脑落子
ComputerMove();
//6.判断胜负
winner = CheckWinner();
if (winner != ' ') {
break;
}
}
if (winner == 'x') {
printf("您赢了\n");
Print();
}
else if (winner == 'o') {
printf("电脑赢了\n");
Print();
}
else if (winner == 'q') {
printf("您和棋了\n");
}
else{
printf("出bug了");
}
}
int main() {
while (1) {
int choice = Menu();
if (choice == 1) {
Game();
}
else if (choice == 0) {
printf("游戏结束\n");
break;
}
else {
printf("您的输入有误\n");
}
}
system("pause");
return 0;
}