珠玑妙算是一种猜数字的游戏,玩家需要猜出由电脑随机生成的一个数字序列。下面是使用 C 语言实现珠玑妙算小游戏的基本步骤:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define DIGITS 4
#define MAX_GUESSES 10
void generateRandomNumber(int *number) {
srand(time(NULL));
for (int i = 0; i < DIGITS; i++) {
number[i] = rand() % 10;
}
}
void compareNumbers(int *guess, int *answer, int *correct, int *misplaced) {
*correct = 0;
*misplaced = 0;
bool answerUsed[DIGITS] = { false };
bool guessUsed[DIGITS] = { false };
// 检查位置正确的数字
for (int i = 0; i < DIGITS; i++) {
if (guess[i] == answer[i]) {
(*correct)++;
guessUsed[i] = true;
answerUsed[i] = true;
}
}
// 检查位置不正确但数字正确的数字
for (int i = 0; i < DIGITS; i++) {
if (!guessUsed[i]) {
for (int j = 0; j < DIGITS; j++) {
if (!answerUsed[j] && guess[i] == answer[j]) {
(*misplaced)++;
guessUsed[i] = true;
answerUsed[j] = true;
break;
}
}
}
}
}
int main() {
int answer[DIGITS];
int guess[DIGITS];
int correct;
int misplaced;
// 生成随机数字序列
generateRandomNumber(answer);
printf("Welcome to Zhuji Miao Suan!\n");
printf("Try to guess a %d-digit number within %d tries.\n", DIGITS, MAX_GUESSES);
// 游戏循环
for (int i = 0; i < MAX_GUESSES; i++) {
printf("Guess #%d: ", i + 1);
scanf("%1d%1d%1d%1d", &guess[0], &guess[1], &guess[2], &guess[3]);
// 比较数字序列
compareNumbers(guess, answer, &correct, &misplaced);
printf("Correct: %d, Misplaced: %d\n", correct, misplaced);
// 判断是否猜中
if (correct == DIGITS) {
printf("Congratulations! You guessed the number correctly!\n");
return 0;
}
}
printf("Sorry, you ran out of guesses. The correct number was: %d%d%d%d\n", answer[0], answer[1], answer[2], answer[3]);
return 0;
}
以上就是使用 C 语言实现珠玑妙算小游戏的基本步骤。通过运行主函数,玩家可以开始猜数字并得到反馈,直到猜中正确的数字或猜测次数用尽。