代码拉取完成,页面将自动刷新
# define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#define max_row 3
#define max_col 3
//初始化
void init(char board[max_row][max_col]) {
for (int row = 0; row < max_row; row++) {
for (int col = 0; col < max_col; col++) {
board[row][col] = ' ';
}
}
//设置随机种子
srand((unsigned int)time(0));
}
//打印棋盘
void printBoard(char board[max_row][max_col]) {
system("cls");
for (int row = 0; row < max_row; row++) {
printf("+---+---+---+\n");
for (int col = 0; col < max_col; col++) {
printf("| %c ", board[row][col]);
}
printf("|");
printf("\n");
}
printf("+---+---+---+\n");
}
//玩家移动
void playerMove(char board[max_row][max_col]) {
printf("请玩家落子\n");
while (1) {
printf("请输入落子的位置(row,col)");
int row = 0, col = 0;
scanf("%d %d", &row, &col);
if (row < 0 || row >= max_row || col < 0 || col >= max_col) {
printf("输入有误,请重新输入\n");
continue;
}
if (board[row][col] != ' ') {
printf("当前位置已经有子了,无法落子\n");
continue;
}
board[row][col] = 'x';
break;
}
}
void computerMove(char board[max_row][max_col]) {
//轮到电脑落子
while (1) {
if (isFull(board)) {
break;
}
int row = rand() % max_row;
int col = rand() % max_col;
if (board[row][col] != ' ') {
//说明位置已经有子了
continue;
}
board[row][col] = 'o';
printBoard(board);
break;
}
}
int isFull(char board[max_row][max_col]) {
//棋盘里面有空格就是没满,没空格就是满了
for (int row = 0; row < max_row; row++) {
for (int col = 0; col < max_col; col++) {
if (board[row][col] == ' ') {
return 0;
}
}
}
return 1;
}
char checkWinner(char board[max_row][max_col]) {
//1.检测所有行
for (int row = 0; row < max_row; row++) {
if (board[row][0] != ' ' && board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
return board[row][0];
}
}
//2.检查所有列
for (int col = 0; col < max_col; col++) {
if (board[0][col] != ' ' && board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
return board[0][col];
}
}
//3.检查所有对角线
if (board[0][0] != ' ' && board[0][0] == board[1][1]
&& board[0][0] == board[2][2]
) {
return board[0][0];
}
if (board[2][0] != ' ' && board[2][0] == board[1][1]
&& board[2][0] == board[0][2]
) {
return board[2][0];
}
//4.检查是否和棋
if (isFull(board)) {
return 'q';
}
return ' ';
}
int main() {
//1.初始化棋盘
char board[max_row][max_col] = { 0 };
init(board);
char winner = ' ';
// 2.打印棋盘
printBoard(board);
while (1) {
//玩家落子
playerMove(board);
//电脑落子
computerMove(board);
//判定胜负 玩家胜返回x,电脑胜返回'o',和棋返回'q',胜负未分返回' '
winner = checkWinner(board);
if (winner == 'x') {
printf("玩家获胜");
}
if (winner == 'o') {
printf("电脑获胜");
}
if (winner == 'q') {
printf("和棋");
}
if (winner != ' ') {
//胜负已分 结束游戏
break;
}
}
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。