亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

使用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
喀喇沁旗| 南昌县| 永城市| 大港区| 聂拉木县| 筠连县| 巩义市| 香港| 遂宁市| 温州市| 班戈县| 德清县| 彭阳县| 昌邑市| 牙克石市| 苍南县| 来凤县| 专栏| 南和县| 黎川县| 南丰县| 信阳市| 仙桃市| 红安县| 郓城县| 凤台县| 西峡县| 潍坊市| 南安市| 翁牛特旗| 凤山县| 鄢陵县| 都兰县| 武定县| 蓝山县| 阿尔山市| 商城县| 湘西| 平利县| 莆田市| 托克逊县|