#include <iostream>
#include <random>
#include <Windows.h>
int digit = 4;
int main() {
//随机数
std::default_random_engine seed;
std::uniform_int_distribution<int> random(0, 9);//0-9闭区间的随机数
seed.seed(time(nullptr));
//猜数字
while (true) {
//输入位数
while (true) {
std::cout << "How many digits would you like to guess?" << std::endl
<< "Please enter a number greater than 0 and less than 1000." << std::endl;
std::cin >> digit;
if (digit >= 0 && digit <= 5) {
break;
} else if (digit >= 0 && digit <= 1000) {
std::cout << "Are you sure?" << std::endl
<< "If you are sure, enter 1, otherwise enter 0." << std::endl;
std::string sure;
std::cin >> sure;
if (sure == "1") {
break;
}
} else {
std::cout << "Input error, please re-enter." << std::endl;
}
}
system("cls");
std::cout << "If you want to quit the game, type -1." << std::endl
<< "If you want to regenerate, enter -2." << std::endl;
bool visNum[10] = {false, false, false, false, false, false, false, false, false, false};
//生成digit位随机数
int randomNum[1005] = {0};
for (int i = 0; i < digit; i++) {
randomNum[i] = random(seed);
visNum[randomNum[i]] = true;
}
bool finish = false;
//猜数字
while (true) {
std::string input;
std::cin >> input;
if (input == "-1") {
goto GAME_OVER;
} else if (input == "-2") {
break;
} else if (input.length() != digit) {
std::cout << "Your input is wrong, please re-enter." << std::endl;
} else {
int guessNum[1005] = {0};
for (int i = 0; i < digit; i++) {
guessNum[i] = input[i] - '0';
}
int hasNumCnt = 0;
int rightNumCnt = 0;
for (int i = 0; i < digit; i++) {
if (visNum[guessNum[i]]) {
if (guessNum[i] == randomNum[i]) {
rightNumCnt += 1;
} else {
hasNumCnt += 1;
}
}
}
if (rightNumCnt == digit) {
finish = true;
break;
} else {
std::cout << "The number of correct numbers but incorrect positions is " << hasNumCnt << " ."
<< std::endl;
std::cout << "The exact number is " << rightNumCnt << " ." << std::endl;
}
}
}
if (finish) {
std::cout << "Congratulations, you got it right!" << std::endl;
//按下空格键退出
std::cout << "Press Space to continue the game." << std::endl;
while (!(GetAsyncKeyState(32) & 0x8000)) {}
}
system("cls");
}
GAME_OVER:
return 0;
}
标签:std,digit,cout,int,20230729,摸鱼,input,seed,产物
From: https://www.cnblogs.com/Eutopiax7/p/17589804.html