以下是使用C語言實現珠璣妙算小游戲的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#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
函數用于檢查猜測的正確性。游戲主循環在玩家猜測錯誤時進行迭代,直到玩家猜測正確或者次數用盡。