三子棋(电脑随机落子)
#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];
void Init();
void PrintfChessBoard();
void PlayerMove();
void ComputerMove();
char CheckWinner();//返回x表示玩家获胜,返回o表示电脑获胜,返回 (空格)表示胜负未分出,返回q表示和棋
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;
}
int main()
{
//1.初始化一个3*3的棋盘
Init();
char winner;
while (1)
{
//2.打印当前的棋盘
PrintfChessBoard();
//3.玩家落子,输入坐标
PlayerMove();
//4.判断胜负
winner = CheckWinner();
if (winner != ' ')
{
break;
}
//5.电脑落子,随机
ComputerMove();
//6.判断胜负
winner = CheckWinner();
if (winner != ' ')
{
break;
}
//7.回到第2步循环执行
}
PrintfChessBoard();
if (winner == 'x')
{
printf("你赢了\n");
}
else if (winner == 'o')
{
printf("你输了\n");
}
else
{
printf("和棋\n");
}
system("pause");
return 0;
}
void Init()
{
for (int i = 0; i < MAX_ROW; i++)
{
for (int j = 0; j < MAX_COL; j++)
{
chess_board[i][j] = ' ';
}
}
}
void PrintfChessBoard()
{
for (int i = 0; i < MAX_ROW; i++)
{
printf("+---+---+---+\n");
printf("| %c | %c | %c |\n",chess_board[i][0], chess_board[i][1], chess_board[i][2] );
}
printf("+---+---+---+\n");
}
void PlayerMove()
{
printf("玩家落子\n");
while (1)
{
printf("请输入落子的坐标:");
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(" ");
}
}
void ComputerMove()
{
printf("电脑落子\n");
while (1)
{
int row = rand() % MAX_ROW;
int col = rand() % MAX_COL;
if (chess_board[row][col] != ' ')
{
continue;
}
chess_board[row][col] = 'o';
break;
}
}
char CheckWinner()
{
//1.检测行
for (int row = 0; row < MAX_ROW; row++)
{
if (chess_board[row][0] != ' ' && chess_board[row][0] == chess_board[row][1] && chess_board[row][0] == chess_board[row][2])
{
return chess_board[row][0];
}
}
//2.检测所有列
for (int col = 0; col < MAX_COL; col++)
{
if (chess_board[0][col] != ' ' && chess_board[0][col] == chess_board[1][col] && chess_board[0][col] == chess_board[2][col])
{
return chess_board[0][col];
}
}
//3.检测对角线
if (chess_board[0][0] !=' '
&& 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[0][2] == chess_board[1][1] && chess_board[0][2] == chess_board[2][0])
{
return chess_board[2][0];
}
//4.和棋
if (IsFull())
{
return 'q';
}
return ' ';
}
电脑智能落子思路:如果最中间位置是空着的,电脑走最中间位置,接着走四角中的一个,然后电脑就可以判断那条线上若有两个相同的棋子,就走这条线上第三个位子,当有自己的棋子和对手的棋子都为两个的时候,先走自己的位子。