溫馨提示×

如何使用C語言實現(xiàn)珠璣妙算小游戲

小億
101
2023-07-28 23:42:45
欄目: 編程語言

珠璣妙算是一種猜數(shù)字的游戲,玩家需要猜出由電腦隨機生成的一個數(shù)字序列。下面是使用 C 語言實現(xiàn)珠璣妙算小游戲的基本步驟:

  1. 導(dǎo)入所需的頭文件:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
  1. 定義全局常量:
#define DIGITS 4
#define MAX_GUESSES 10
  1. 編寫生成隨機數(shù)字的函數(shù):
void generateRandomNumber(int *number) {
srand(time(NULL));
for (int i = 0; i < DIGITS; i++) {
number[i] = rand() % 10;
}
}
  1. 編寫比較數(shù)字序列的函數(shù),判斷玩家猜測的數(shù)字與答案的匹配情況:
void compareNumbers(int *guess, int *answer, int *correct, int *misplaced) {
*correct = 0;
*misplaced = 0;
bool answerUsed[DIGITS] = { false };
bool guessUsed[DIGITS] = { false };
// 檢查位置正確的數(shù)字
for (int i = 0; i < DIGITS; i++) {
if (guess[i] == answer[i]) {
(*correct)++;
guessUsed[i] = true;
answerUsed[i] = true;
}
}
// 檢查位置不正確但數(shù)字正確的數(shù)字
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;
}
}
}
}
}
  1. 編寫主函數(shù),實現(xiàn)游戲的邏輯:
int main() {
int answer[DIGITS];
int guess[DIGITS];
int correct;
int misplaced;
// 生成隨機數(shù)字序列
generateRandomNumber(answer);
printf("Welcome to Zhuji Miao Suan!\n");
printf("Try to guess a %d-digit number within %d tries.\n", DIGITS, MAX_GUESSES);
// 游戲循環(huán)
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]);
// 比較數(shù)字序列
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 語言實現(xiàn)珠璣妙算小游戲的基本步驟。通過運行主函數(shù),玩家可以開始猜數(shù)字并得到反饋,直到猜中正確的數(shù)字或猜測次數(shù)用盡。

0