中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

使用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
洞口县| 盐津县| 常熟市| 东莞市| 土默特左旗| 开阳县| 吴桥县| 汽车| 禄丰县| 新乡县| 且末县| 彭州市| 仪征市| 五莲县| 蒙自县| 米林县| 临西县| 保德县| 郯城县| 安庆市| 京山县| 平原县| 福清市| 霞浦县| 湖州市| 巴林右旗| 海门市| 安国市| 香格里拉县| 陵川县| 静宁县| 清远市| 固安县| 广汉市| 广宁县| 剑阁县| 湘潭县| 外汇| 凭祥市| 沙河市| 石棉县|