这是我一直在研究和尝试改进的一本书中的代码块,但是我很难找到一种方法,让玩家在输入默认选项后又有机会选择难度。这是一个非常简单的基于文本的控制台游戏,当玩家选择了错误的选择时,该游戏将不允许玩家重新选择。
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
int choice;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy\n";
break;
case 2:
cout << "You picked Normal\n";
break;
case 3:
cout << "You picked Hard\n";
break;
default:
cout << "Your choice is invalid.\n";
}
system("pause");
return 0;
}
最佳答案
您可以将开关重构为一个函数,只要玩家想更改其难度选择,就可以调用该函数。
int choose()
{
int choice;
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy\n";
break;
case 2:
cout << "You picked Normal\n";
break;
case 3:
cout << "You picked Hard\n";
break;
default:
cout << "Your choice is invalid.\n";
choice = 0; //this will signal error
}
return choice;
}
int _tmain(int argc, _TCHAR* argv[])
{
int choice = 0;
while(choice == 0){choice = choose();};
system("pause");
return 0;
}
现在,只要玩家决定更改难度(也许他们输入了特殊字母),就可以使用choice = choice()来更改难度。
关于c++ - C++转换语句-给玩家另一个选择的机会,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20894986/