fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. // prototype
  6. void print_board();
  7. int judge();
  8. void mark_board();
  9. void print_message(int result);
  10. int calc(int from, int step);
  11.  
  12. // global
  13. int board[3][3] = {};
  14. int turn = 1; /*1=maru,-1=batsu*/
  15. int result;
  16. int mode;
  17.  
  18. int main()
  19. {
  20. srand(time(NULL));
  21. printf("0:debug, 1:manual\n");
  22. scanf("%d", &mode);
  23.  
  24. print_board();
  25. while (1) {
  26. mark_board();
  27. print_board();
  28. if ((result = judge())) break;
  29. turn *= -1;
  30. }
  31. print_message(result);
  32.  
  33. return 0;
  34. }
  35.  
  36. void print_board()
  37. {
  38. /*引数で受け取った盤のデータ(board)を縦線(|)や○や×を使い画面に表示する*/
  39. int i, j;
  40. char s[] = {"X O"};
  41. for ( i = 0; i < 3; ++i) {
  42. for ( j = 0; j < 3; ++j) {
  43. printf("|%c", s[board[i][j] + 1]);
  44. }
  45. puts("|");
  46. }
  47. puts("");
  48. }
  49.  
  50. int judge()
  51. {
  52. int r, i, *p = *board;
  53. /*引数boardの内容をチェックし、○が勝ちなら1を、×が勝ちなら2を、
  54.      引き分けなら3を、まだ勝敗が決まっていないときは0を返す*/
  55. // printf("i am judge\n");
  56. while (1) {
  57. if ((r = calc(0, 3))) break;
  58. if ((r = calc(1, 3))) break;
  59. if ((r = calc(2, 3))) break;
  60. if ((r = calc(0, 1))) break;
  61. if ((r = calc(3, 1))) break;
  62. if ((r = calc(6, 1))) break;
  63. if ((r = calc(0, 4))) break;
  64. if ((r = calc(2, 2))) break;
  65.  
  66. r = 0;
  67. for ( i = 0; i < 9; ++i)
  68. r += (*p++ == 0);
  69.  
  70. return r ? 0 : 3;
  71. }
  72. return r == 1 ? 1 : 2;
  73. }
  74.  
  75. void mark_board()
  76. {
  77. /*盤の縦横の位置の入力を促すメッセージを表示し、キーボードから数値を読み込み,
  78.      board配列へturnの値を代入する*/
  79. int i, j;
  80. do {
  81. if (mode == 0) {
  82. i = rand() % 3;
  83. j = rand() % 3;
  84. } else {
  85. printf("i j = ");
  86. scanf("%d %d", &i, &j);
  87. }
  88. } while (i < 0 | i >= 3 | j < 0 | j >= 3 | board[i][j]);
  89. board[i][j] = turn;
  90. }
  91.  
  92. void print_message(int result)
  93. {
  94. char *s[] = {"", "Oの勝ち", "Xの勝ち", "引き分け"};
  95. /*resultの値に従って勝敗のメッセージを表示する*/
  96. printf("%s\n", s[result]);
  97.  
  98. }
  99.  
  100. int calc(int from, int step)
  101. {
  102. int *p = (*board) + from, r = 0, i;
  103. for ( i = 0; i < 3; ++i) {
  104. r += *p;
  105. p += step;
  106. }
  107. // printf("r = %d %d\n", r, r / 3);
  108. return r / 3;
  109. }
  110.  
Success #stdin #stdout 0.02s 1680KB
stdin
Standard input is empty
stdout
0:debug, 1:manual
| | | |
| | | |
| | | |

|O| | |
| | | |
| | | |

|O| | |
| | |X|
| | | |

|O| | |
| | |X|
|O| | |

|O| | |
| |X|X|
|O| | |

|O| | |
|O|X|X|
|O| | |

Oの勝ち