井字棋
前些天学了一个用c语言写的井字棋(或者说是三子棋)的代码,敲了一下午给你们look look,记得从下往上look
(我的很长,你要忍一下)
#include<stdio.h> #include<stdlib.h> #include<time.h> #define ROW 3 #define COL 3
char IsFull(char borad[ROW][COL],int row,int col) { int i=0,j=0; for (i=0;i<row;i++) { for (j=0;j<col;j++) { if (borad[i][j]==’ ') return 0; } } return 1; }
char IsWin(char borad[ROW][COL],int row,int col) { int i=0,j=0; for (i=0;i<row;i++) { if (borad[i][0]==borad[i][1]&&borad[i][1]==borad[i][2]&&borad[i][1]!=’ ‘) return borad[i][1]; } for (i=0;i<col;i++) { if (borad[0][i]==borad[1][i]&&borad[1][i]==borad[2][i]&&borad[1][i]!=’ ‘) return borad[1][i]; } if (borad[0][0]==borad[1][1]&&borad[1][1]==borad[2][2]&&borad[1][1]!=’ ') return borad[1][1]; if (borad[0][2]==borad[1][1]&&borad[1][1]borad[2][0]&&borad[1][1]!=’ ') return borad[1][1]; if (1IsFull(borad,ROW,COL)) { return ‘Q’; } return ‘C’; }
void ComputerMove(char borad[ROW][COL],int row,int col) { int x=0,y=0,z=100; printf(“电脑走\n”); while(z) { x=rand()%row; y=rand()%col; if (borad[x][y]==’ ‘) { borad[x][y]=’#’; break; } z–; } }
void PlayerMove(char borad[ROW][COL],int row,int col) { int x=0,y=0; printf(“玩家走\n”);
while (1)
{
printf("请输入坐标: (用逗号隔开)");
scanf("%d,%d",&x,&y);
if (x>=1&&x<=row&&y>=1&&y<=col)
{
if(borad[x-1][y-1]==' ')
{
borad[x-1][y-1]='*';
break;
}
else
{
printf("该坐标已被占用,请重新输入!\n");
}
}
if (x==0||x>row||y==0||y>col)
{
printf("输入错误,请重新输入!\n");
}
}
}
void InitBorad(char borad[ROW][COL],int row,int col) { int i=0; int j=0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { borad[i][j]=’ '; } } }
void DisplayBorad(char borad[ROW][COL],int row,int col) { int i=0,j=0; for (i=0;i<row;i++) { for(j=0;j<col;j++) { printf(" %c “,borad[i][j]); if (j<col-1) printf(”|"); } printf("\n"); if (i<col-1) { for(j=0;j<col;j++) { printf("—"); if(j<col-1) printf("|"); } printf("\n"); } } }
void game() { char ret=0; char borad[ROW][COL]={0}; InitBorad(borad,ROW,COL); DisplayBorad(borad,ROW,COL); while(1) { PlayerMove(borad,ROW,COL); DisplayBorad(borad,ROW,COL); ret=IsWin(borad,ROW,COL);
ComputerMove(borad,ROW,COL);
DisplayBorad(borad,ROW,COL);
ret=IsWin(borad,ROW,COL);
if (ret=='#')
{
printf("电脑赢\n");
break;
}
if (ret=='*')
{
printf("玩家赢\n");
break;
}
if (ret=='Q')
{
printf("平局\n");
break;
}
}
}
void menu() { printf("***************\n"); printf(" 1.play 0.exit\n"); printf("***************************\n"); }
void text() { srand((unsigned int)time(NULL)); int input=0; menu(); printf(“请选择:”); do { scanf("%d",&input); switch(input) { case 1: printf(“三子棋\n”); printf("\n"); game(); break; case 0: printf(“游戏结束\n”); break; default: printf(“输入错误,请重新输入!\n”); break; } }while(input); }
int main() { text(); return 0; }
到底了 别看花眼喔
|