91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

使用C語言實現珠璣妙算Mastermind小游戲

小云
106
2023-08-09 14:07:16
欄目: 編程語言

以下是使用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函數用于檢查猜測的正確性。游戲主循環在玩家猜測錯誤時進行迭代,直到玩家猜測正確或者次數用盡。

0
临沂市| 凤翔县| 金秀| 湾仔区| 思茅市| 洞口县| 耿马| 阳原县| 韶关市| 温宿县| 内乡县| 岑溪市| 资源县| 广宁县| 称多县| 都匀市| 安康市| 凭祥市| 新密市| 永春县| 赤峰市| 航空| 襄樊市| 太湖县| 梅河口市| 镇远县| 南昌市| 余庆县| 巍山| 岳阳市| 玛沁县| 宿松县| 壤塘县| 惠安县| 城固县| 井陉县| 桦川县| 连城县| 乐平市| 泰顺县| 吴江市|