c语言程序三子棋,C语言实现简易三子棋 | 术与道的分享

#include

#include

#include

#define rows 3

#define lows 3 //定义二维数组的行和列

void display(char chessBoard[rows][lows]); //打印棋盘

void Peo_Play(char chessBoard[rows][lows]); //人下棋

void Com_Play(char chessBoard[rows][lows]); //电脑下棋

int winner(char chessBoard[rows][lows]); //胜利者

void init(char chessBoard[rows][lows]) //初始化

{

int i=0;

int j=0;

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

{

chessBoard[i][j]=' ';

}

}

display(chessBoard); //调用打印函数

for(i=0;i<3;i++)

{

Peo_Play(chessBoard); //打印人下的棋

Com_Play(chessBoard); //打印电脑下的题

}

winner(chessBoard); //调用胜利者的函数

}

void display(char chessBoard[rows][lows]) //打印棋盘

{

int i=0;

for(i=0;i<3;i++)

{

printf(" %c | %c | %c \n",chessBoard[i][0],chessBoard[i][1],chessBoard[i][2]);

if(i!=2)

printf("---|---|---\n");

}

}

void Peo_Play(char chessBoard[rows][lows]) //人下棋

{

int i=0;

int j=0;

printf("请输入你要下的位置->:");

scanf("%d,%d",&i,&j);

system("cls");

while(chessBoard[i][j]!=' ') //棋盘位置不为空

{

if((i<0)||(i>2)||(j<0)||(j>2)) //超出二维数组的范围

{

printf("ERROR:你输入的位置信息有误!");

}

}

chessBoard[i][j]='X'; //将人的下棋位置赋值为X

display(chessBoard); //在棋盘中打印

}

void Com_Play(char chessBoard[rows][lows]) //电脑下棋

{

int i=0;

int j=0;

printf("电脑下棋中...\n");

while(chessBoard[i][j]!=' ') //棋盘位置不为空

{

i=rand()%3;

j=rand()%3; //产生小于3的随机数

}

system("cls");

chessBoard[i][j]='Y';

display(chessBoard); //在棋盘中打印

}

int winner(char chessBoard[rows][lows]) //胜利者

{

int i=0;

if((chessBoard[0][0]==chessBoard[1][1])&&(chessBoard[1][1]==chessBoard[2][2]))//判断正对角线

{

if(chessBoard[1][1]=='X')

{

printf("祝贺你,你赢了!\n");

return 1;

}

if(chessBoard[1][1]=='Y')

{

printf("电脑赢了!\n");

return 1;

}

}

if((chessBoard[0][2]==chessBoard[1][1])&&(chessBoard[1][1]==chessBoard[2][0]))//判断反对角线

{

if(chessBoard[1][1]=='X')

{

printf("祝贺你,你赢了!\n");

return 1;

}

if(chessBoard[1][1]=='Y')

{

printf("电脑赢了!\n");

return 1;

}

}

for(i=0;i<3;i++)

{

if((chessBoard[i][0]==chessBoard[i][1])&&(chessBoard[i][1]==chessBoard[i][2]))//判断行

{

if(chessBoard[i][1]=='X')

{

printf("祝贺你,你赢了!\n");

return 1;

}

if(chessBoard[i][1]=='Y')

{

printf("电脑赢了!\n");

return 1;

}

}

}

for(i=0;i<3;i++)

{

if((chessBoard[0][i]==chessBoard[1][i])&&(chessBoard[1][1]==chessBoard[2][i]))//判断列

{

if(chessBoard[1][i]=='X')

{

printf("祝贺你,你赢了!\n");

return 1;

}

if(chessBoard[1][i]=='Y')

{

printf("电脑赢了!\n");

return 1;

}

}

}

printf("你们打成了平局!"); //否则输出平局

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值