fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <stdbool.h>
  7.  
  8. void generateAnswer(int answer[])
  9. {
  10. bool used[10] = {false};
  11. int count = 0;
  12. while (count < 4)
  13. {
  14. int digit = rand() % 10;
  15. if (!used[digit])
  16. {
  17. used[digit] = true;
  18. answer[count++] = digit;
  19. }
  20. }
  21. }
  22.  
  23. bool isValidInput(char input[])
  24. {
  25. if (strlen(input) != 4) return false;
  26.  
  27. bool used[10] = {false};
  28. for (int i = 0; i < 4; i++)
  29. {
  30. if (!isdigit(input[i])) return false;
  31. int digit = input[i] - '0';
  32. if (used[digit]) return false;
  33. used[digit] = true;
  34. }
  35. return true;
  36. }
  37.  
  38. bool getGuess(int guess[])
  39. {
  40. char input[100];
  41.  
  42. if (scanf("%s", input) == EOF)
  43. {
  44. return false;
  45. }
  46.  
  47. if (!isValidInput(input))
  48. {
  49. return false;
  50. }
  51.  
  52. for (int i = 0; i < 4; i++)
  53. {
  54. guess[i] = input[i] - '0';
  55. }
  56.  
  57. return true;
  58. }
  59.  
  60. void checkAB(int answer[], int guess[], int* A, int* B)
  61. {
  62. *A = 0;
  63. *B = 0;
  64.  
  65. for (int i = 0; i < 4; i++)
  66. {
  67. if (guess[i] == answer[i])
  68. {
  69. (*A)++;
  70. } else
  71. {
  72. for (int j = 0; j < 4; j++)
  73. {
  74. if (guess[i] == answer[j] && i != j)
  75. {
  76. (*B)++;
  77. break;
  78. }
  79. }
  80. }
  81. }
  82. }
  83.  
  84. bool playAgain()
  85. {
  86. char choice;
  87. printf("是否再玩一次遊戲?(y/n): ");
  88. scanf(" %c", &choice);
  89. return (choice == 'y' || choice == 'Y');
  90. }
  91.  
  92. int main()
  93. {
  94. int answer[4], guess[4];
  95. int A = 0, B = 0;
  96. int attempts = 0;
  97.  
  98. srand(time(NULL));
  99.  
  100. do
  101. {
  102. generateAnswer(answer);
  103. A = 0; B = 0; attempts = 0;
  104.  
  105. while (A != 4)
  106. {
  107. if (!getGuess(guess))
  108. {
  109. printf("輸入錯誤或輸入結束。\n");
  110. break;
  111. }
  112. checkAB(answer, guess, &A, &B);
  113. printf("%dA%dB\n", A, B);
  114. attempts++;
  115. }
  116.  
  117. if (A == 4)
  118. {
  119. printf("你猜對了!總共猜了 %d 次~\n", attempts);
  120. }
  121.  
  122. } while (playAgain());
  123.  
  124. printf("感謝遊玩!\n");
  125.  
  126. return 0;
  127. }
Success #stdin #stdout 0s 5288KB
stdin
1234
stdout
1A0B
輸入錯誤或輸入結束。
是否再玩一次遊戲?(y/n): 感謝遊玩!