//猜数字 #include <iostream> #include <cstdlib> #include <ctime> #include <limits> #include <string> using std::cout; using std::cin; using std::endl; using std::string; using std::numeric_limits; using std::streamsize; int generateSecretNumber(int min, int max); void displayGameIntro(); int selectDifficulty(); bool playGame(int min, int max); bool askPlayAgain(); void clearInputBuffer(); int main() { srand(static_cast<unsigned int>(time(NULL))); displayGameIntro(); do { int difficulty = selectDifficulty(); int minNum = 1; int maxNum = 100; switch(difficulty) { case 1: maxNum = 50; break; case 2: maxNum = 100; break; case 3: maxNum = 200; break; } bool isWin = playGame(minNum, maxNum); if (isWin) { cout << "\n?? 太棒了!你成功猜出了数字!" << endl; } } while (askPlayAgain()); cout << "\n?? 感谢游玩,下次再见!" << endl; return 0; } int generateSecretNumber(int min, int max) { return rand() % (max - min + 1) + min; } void displayGameIntro() { cout << "=====================================" << endl; cout << " C++ 升级版猜数字游戏 " << endl; cout << "=====================================" << endl; cout << "游戏规则:" << endl; cout << "1. 系统会生成指定范围的随机数" << endl; cout << "2. 你需要不断猜测,直到猜对为止" << endl; cout << "3. 系统会提示你猜的数字是大了还是小了" << endl; cout << "=====================================\n" << endl; } int selectDifficulty() { int choice = 0; cout << "请选择游戏难度:" << endl; cout << "1 - 简单 (1-50)" << endl; cout << "2 - 中等 (1-100)" << endl; cout << "3 - 困难 (1-200)" << endl; cout << "输入难度编号:"; while (!(cin >> choice) || choice < 1 || choice > 3) { clearInputBuffer(); cout << "输入无效!请输入1、2或3选择难度:"; } clearInputBuffer(); return choice; } bool playGame(int min, int max) { int secretNumber = generateSecretNumber(min, max); int guess = 0; int guessCount = 0; cout << "\n? 已生成 " << min << "-" << max << " 之间的随机数,开始猜测吧!" << endl; while (true) { cout << "\n请输入你的猜测:"; while (!(cin >> guess)) { clearInputBuffer(); cout << "输入错误!请输入一个整数:"; } clearInputBuffer(); guessCount++; if (guess < min || guess > max) { cout << "? 超出范围!请输入 " << min << "-" << max << " 之间的数字!"; continue; } if (guess < secretNumber) { cout << "?? 猜小了!再往大猜猜~"; } else if (guess > secretNumber) { cout << "?? 猜大了!再往小猜猜~"; } else { cout << "\n?? 恭喜猜对了!你一共猜了 " << guessCount << " 次!" << endl; cout << "本次的神秘数字是:" << secretNumber << endl; return true; } } } bool askPlayAgain() { string choice; cout << "\n是否要重新开始游戏?(y/n):"; cin >> choice; clearInputBuffer(); return (choice == "y" || choice == "Y"); } void clearInputBuffer() { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
Note.ms
/niys