实战五子棋:
思路:
1. 棋盘由边缘数字和横竖线及棋子构成;
2. 先init初始化,画出棋盘的数字边缘,为了第一次下棋的时候能看见棋盘样子,其实可以封装起来用;
3. 落子之后调用draw_cross画出整个棋盘,依旧是先画边缘数字,再画棋子,一行一行画;
4. 判断输赢。
#include<stdio.h>
#include<stdlib.h>
#defineNUM 10
#defineBLACK 1
#defineWHITE 2
intcross[NUM][NUM];//存入白棋和黑棋的坐标
intdraw_num[NUM]={1,2,3,4,5,6,7,8,9,0};//边际
int X,Y;
voidinit_draw(){
system("clear");
int i;
for(i=0;i<NUM;i++){
printf("%2d",draw_num[i]);
}
printf("\n");
for(i=0;i<NUM;i++){
printf("%d\n",draw_num[i]);
}
}
voiddraw_cross(){
system("clear");
int i;
for(i=0;i<NUM;i++){
printf("%2d",draw_num[i]);
}
printf("\n");
int j;
for(i=0;i<NUM;i++){
printf("%d",draw_num[i]);
for(j=0;j<NUM;j++){
if(cross[i][j]==WHITE){
printf("〇");
}elseif(cross[i][j]==BLACK){
printf("●");
}else{
printf(" ");
}
}
printf("\n");
}
}
intjudge(int x,int y){
if(x<0||y<0||x>=NUM||y>=NUM){
return -1;
}elseif(cross[x][y]==WHITE||cross[x][y]==BLACK){
return -2;
}else{
return 0;
}
}
voidwho_can_start(int num){
int x,y;
int realX,realY;
int r;
if(num==1){
printf("白方落棋(输入坐标x,y):");
scanf("%d%d",&x,&y);
realX=x-1;
realY=y-1;
r = judge(realX,realY);
if(!r){
X=realX;
Y=realY;
//printf("%d,%d\n",X,Y);
cross[X][Y]=WHITE;
draw_cross();
return;
}else if(r==-1){
printf("超出范围!");
}else if(r==-2){
printf("已经存在棋子!");
}
}else{
printf("黑方落棋:(输入坐标x,y):");
scanf("%d%d",&x,&y);
realX = x-1;
realY = y-1;
r = judge(realX,realY);
if(!r){
X=realX;
Y=realY;
cross[X][Y]=BLACK;
draw_cross();
return;
}else if(r==-1){
printf("超出范围!");
}else if(r==-2){
printf("已经存在棋子!");
}
}
}
intwho_can_win(int color,int x,int y){
int count = 1;
int i,j;
for(i=x,j=y-1;color==cross[i][j]&&j>=0;j--)
count++;
for(i=x,j=y+1;color==cross[i][j]&&j<NUM;j++)
count++;
if(count==5)
return 1;
count = 1;
for(i=x-1,j=y;color==cross[i][j]&&i>=0;i--)
count++;
for(i=x+1,j=y;color==cross[i][j]&&i<NUM;i++)
count++;
if(count==5)
return 1;
count = 1;
for(i=x-1,j=y-1;color==cross[i][j]&&i>=0;i--,j--)
count++;
for(i=x+1,j=y+1;color==cross[i][j]&&i<NUM;i++,j++)
count++;
if(count==5)
return 1;
count = 1;
for(i=x-1,j=y+1;color==cross[i][j]&&i>=0;i--,j++)
count++;
for(i=x+1,j=y-1;color==cross[i][j]&&i<NUM;i++,j--)
count++;
if(count==5)
return 1;
return 0;
}
intmain(){
init_draw();
while(1){
who_can_start(1);
if(who_can_win(WHITE,X,Y)){
printf("白方获取胜利!\n");
return 0;
}
who_can_start(2);
if(who_can_win(BLACK,X,Y)){
printf("黑方获取胜利!\n");
return 0;
}
}
return 0;
}