Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #define n 16
- static int board[n][n];
- int i, j, x, y;
- int choice;
- void main_menu(void)
- {
- printf("\n==========5 chess game==========\n");
- printf(" 1.Start a new game\n");
- printf(" 2.Continue\n");
- printf(" 3.Exit");
- printf("\n================================\n");
- printf("Enter : \n");
- }
- void initialize_board() /* reset a blank board */
- {
- for(i=0; i<16; i++)
- for(j=0; j<16; j++)
- board[i][j]=0;
- }
- void read_board(void)
- {
- FILE *file = fopen("board.txt" , "r");
- for(i=0; i<17; i++)
- for(j=0; j<17; j++)
- fscanf(file, "%d", &board[i][j]);
- fclose(file);
- }
- void write_board(void)
- {
- FILE *file = fopen("board.txt" , "w");
- for(i=0; i<16; i++)
- for(j=0; j<16; j++)
- fprintf(file, "%d", board[i][j]);
- fclose(file);
- }
- void output_board(void) /* print the chess board */
- {
- int a=0, b=0;
- for(i=0; i<16; i++) /* print the 5 chess x-coordinates */
- printf("%3d", a++);
- printf("\n");
- for(i=0; i<16; i++)
- {
- printf("%2d", b++); /* print the 5 chess y-coordinates */
- for(j=0; j<16; j++)
- {
- if(board[i][j]==0)
- printf("+ ");
- else if(board[i][j]==1)
- printf("o ");
- else if(board[i][j]==2)
- printf("x ");
- }
- printf("\n");
- }
- }
- void range_check(int p) /* check if the position is in the board range */
- {
- if(x>=0 && x<16 && y>=0 && y<16); //in the borad range, continue
- else if(x<0 || x>=16 || y<0 || y>=16) //not in the board range, run the following statements
- {
- printf("\nError.\n");
- printf("\n player%d--enter the position (y/x) : ", p);
- scanf("%d %d", &x, &y);
- range_check(p);
- }
- }
- void occupasion_check(int p) /* check if the position has already occupied */
- {
- if(board[x][y]==0); //not occupied, continue
- else if(board[x][y]==1 || board[x][y]==2) //occupied, run the following statements
- {
- printf("\nError.\n");
- printf("\n player%d--enter the position (y/x) : ", p);
- scanf("%d %d", &x, &y);
- occupasion_check(p);
- }
- }
- int main(void)
- {
- int p, k;
- main_menu();
- scanf("%d", &choice);
- switch(choice)
- {
- case 1: read_board();
- do
- {
- /* player1 playing */
- system("cls");
- p=1;
- output_board();
- printf("\n player%d--enter the position (y/x) : ", p);
- scanf("%d %d", &x, &y);
- range_check(p);
- occupasion_check(p);
- board[x][y]=1;
- write_board();
- /* player2 playing */
- system("cls");
- p=2;
- output_board();
- printf("\n player2--enter the position (y/x) : ", p);
- scanf("%d %d", &x, &y);
- range_check(p);
- occupasion_check(p);
- board[x][y]=2;
- write_board();
- k=1;
- //k=2;
- }while(k==1);
- break;
- case 2: read_board();
- output_board();
- break;
- case 0: break;
- }
- }
Add Comment
Please, Sign In to add comment