Problem description :
3*3 On the chessboard of , As long as three identical pieces appear on a line, you will win ( Players or computers ); If the chessboard is full and there are no three pieces, a line is drawn .
Specific details :
Initialize chessboard ( Initialize with spaces )
// Initialize chessboard
voidinitChess(charchessbox[ROW][COL]){ for(introw=0;row<ROW;row++){ for(intcol=0;col<COL;col++){ chessbox[row][col]=' ';}}}
Print chessboard
// Print chessboard
voidprintChess(charchessbox[ROW][COL]){ system("cls");printf("+---+---+---+\n");for(introw=0;row<ROW;row++){ printf("| %c | %c | %c |\n",chessbox[row][0],chessbox[row][1],chessbox[row][2]);printf("+---+---+---+\n");}}
Computer move later ( use o It means that the computer is down )
// Computer move later ( use o Express )
voidcomputerMove(charchessbox[ROW][COL]){ srand(time(0));while(1){ introw=rand()%3;intcol=rand()%3;if(chessbox[row][col]==' '){ chessbox[row][col]='o';break;}}}
The player is down
// The player is down ( use x Express )
voidplayerMove(charchessbox[ROW][COL]){ introw,col;while(1){ printf(" Please enter your location :");scanf("%d %d",&row,&col);if(row>=3||col>=3){ printf(" The position you entered is wrong , Please re-enter :");continue;}if(chessbox[row][col]==' '){ chessbox[row][col]='x';break;}printf(" There are already pieces in this position , Please re-enter :");}}
Three pieces, one line
In a row or column to achieve three pieces of a line
// That's ok
for(introw=0;row<ROW;row++){ if(chessbox[row][0]!=' '&&chessbox[row][0]==chessbox[row][1]&&chessbox[row][0]==chessbox[row][2]){ returnchessbox[row][0];}}// Column
for(intcol=0;col<COL;col++){ if(chessbox[0][col]!=' '&&chessbox[0][col]==chessbox[1][col]&&chessbox[0][col]==chessbox[2][col]){ returnchessbox[0][col];}}
Diagonal line to achieve three pieces of a line
if(chessbox[0][0]!=' '&&chessbox[0][0]==chessbox[1][1]&&chessbox[0][0]==chessbox[2][2]){ returnchessbox[0][0];}if(chessbox[2][0]!=' '&&chessbox[2][0]==chessbox[1][1]&&chessbox[2][0]==chessbox[0][2]){ returnchessbox[2][0];}
draw
The chessboard is full and has not won , It's a draw , It's a draw .
Insert a code chip here // draw if(isFull(checkbox)){ return'a';}
Win lose agreement :
return x Win on behalf of the player
if(isWinner(chessbox)=='x'){ printf(" Congratulations on winning !\n");break;}
return o For computers to win
if(isWinner(chessbox)=='o'){ printf(" unfortunately , You lost !\n");break;}
return a For a draw ( A draw )
if(isWinner(chessbox)=='a'){ printf(" You are on the same level as the computer !\n");break;}
Judge whether the chessboard is full :
return 1 The chessboard is full
return 0 The chessboard is not full
// Judge whether the chessboard is full //1 It means full ;0 Express dissatisfaction .
intisFullChess(charchessbox[ROW][COL]){ for(introw=0;row<ROW;row++){ for(intcol=0;col<COL;col++){ // Find the space , It's not full
if(chessbox[row][col]==' '){ return0;}}}return1;}
Source code :