以下是使用C语言实现珠玑妙算小游戏的代码:
```c
#include
#include
#include
#define CODE_LENGTH 4
#define MAX_ATTEMPTS 10
void generateSecretCode(int* secretCode) {
srand(time(NULL));
for(int i = 0; i < CODE_LENGTH; i++) {
secretCode[i] = rand() % 6 + 1; // Generate a random number between 1 and 6
}
}
int* getUserGuess() {
static int userGuess[CODE_LENGTH];
printf("Enter your guess (4 digits between 1 and 6): ");
for(int i = 0; i < CODE_LENGTH; i++) {
scanf("%d", &userGuess[i]);
}
return userGuess;
}
void checkGuess(int* secretCode, int* userGuess, int* numCorrectPosition, int* numCorrectDigit) {
*numCorrectPosition = 0;
*numCorrectDigit = 0;
int secretCodeCopy[CODE_LENGTH];
int userGuessCopy[CODE_LENGTH];
for(int i = 0; i < CODE_LENGTH; i++) {
secretCodeCopy[i] = secretCode[i];
userGuessCopy[i] = userGuess[i];
}
// Check for correct digits in correct position
for(int i = 0; i < CODE_LENGTH; i++) {
if(userGuess[i] == secretCode[i]) {
(*numCorrectPosition)++;
secretCodeCopy[i] = -1;
userGuessCopy[i] = -1;
}
}
// Check for correct digits in wrong position
for(int i = 0; i < CODE_LENGTH; i++) {
for(int j = 0; j < CODE_LENGTH; j++) {
if(userGuessCopy[i] == secretCodeCopy[j] && userGuessCopy[i] != -1) {
(*numCorrectDigit)++;
secretCodeCopy[j] = -1;
userGuessCopy[i] = -1;
break;
}
}
}
}
int main() {
int secretCode[CODE_LENGTH];
int numAttempts = 0;
generateSecretCode(secretCode);
printf("*** Welcome to Mastermind! ***\n");
printf("Guess the 4-digit code. Each digit is between 1 and 6.\n");
while(numAttempts < MAX_ATTEMPTS) {
int numCorrectPosition, numCorrectDigit;
int* userGuess = getUserGuess();
checkGuess(secretCode, userGuess, &numCorrectPosition, &numCorrectDigit);
if(numCorrectPosition == CODE_LENGTH) {
printf("Congratulations! You guessed the code correctly.\n");
return 0;
} else {
printf("Incorrect. Number of correct digits in correct position: %d\n", numCorrectPosition);
printf("Number of correct digits in wrong position: %d\n", numCorrectDigit);
printf("Number of attempts remaining: %d\n\n", MAX_ATTEMPTS - numAttempts - 1);
}
numAttempts++;
}
printf("Game over! You ran out of attempts. The secret code was: ");
for(int i = 0; i < CODE_LENGTH; i++) {
printf("%d ", secretCode[i]);
}
printf("\n");
return 0;
}
```
这个代码实现了一个简单的珠玑妙算游戏,其中有一个4位数的秘密代码,玩家需要在限定次数内猜出正确的代码。代码中的`generateSecretCode`函数用于生成秘密代码,`getUserGuess`函数用于获取玩家的猜测,`checkGuess`函数用于检查猜测的正确性。游戏主循环在玩家猜测错误时进行迭代,直到玩家猜测正确或者次数用尽。