#include <stdio.h> #include <stdlib.h> #include <time.h>
int main() { srand(time(NULL)); int level;//游戏难度 int length ; // 随机生成4~6位数 int target = 0; int used[10] = { 0 }; int max_chance;//玩家最多可猜测次数 int now_chance = 0;//玩家已猜次数 printf("选择你的游戏难度(4~6)\n"); scanf("%d", &level); length = level; switch (level) { case 4: max_chance = 12; break; case 5: max_chance = 20; break; case 6: max_chance = 28; break; default: printf("这不是一个有效的游戏难度!\n"); return 1; }
for (int i = 0; i < length; ++i) {
int digit;
do {
digit = rand() % 10;
} while (used[digit]);
used[digit] = 1;
target = target * 10 + digit;
}
//printf("target is %d\n", target);
printf("游戏开始!本局游戏你共有%d次机会,祝你好运!\n", max_chance);
while (now_chance < max_chance) {
printf("你的猜测是:\n");
int guess;
scanf("%d", &guess);
if (guess == target) {
printf("你胜利了!\n");
return 0;
}
int correct_digits = 0;
int same_digits = 0;
int temp_guess = guess;
int temp_target = target;
for (int i = 0; i < length; ++i) {
int guess_digit = temp_guess % 10;
int target_digit = temp_target % 10;
if (guess_digit == target_digit) {
++correct_digits;
}
else if (used[guess_digit]) {
++same_digits;
}
temp_guess /= 10;
temp_target /= 10;
}
if (correct_digits > 0) {
printf("你的正确数位已达%d个,离胜利越来越近了\n", correct_digits);
}
else if (same_digits > 0) {
printf("虽然有相同数字,但数位完全乱了哦!\n");
}
else {
printf("你巧妙的避开了正确答案!\n");
}
now_chance++;
}
printf("游戏结束,很遗憾你失败了,正确答案应是:%d", target);
return 0;
}