刽子手游戏 - 如何在 c++ 中做"wrong guess"?



我的游戏成功了,但我猜错了!部分,那个"错误"意思是"即使我猜对了,它也会说我错了"或者"它多次说错了,而不是一次"。

所以,在我的初级程序中,这就是我卡住的地方。

char u_recherche;  
std::string mot_secret(choisi_ton_mot.length(), '-');  
std::string choisi_ton_mot;  
int faute = 0;
while (i < 999)                                       
{
//code
for (int i = 0; i < mot_secret.length(); i++) // to check each letter
{
if (choisi_ton_mot[i] == u_recherche) //guess right
{
mot_secret[i] = u_recherche; // if right change "-" to the right letter
std::cout << "lettre trouver ! " << std::endl;
}
}
if (choisi_ton_mot[i] != u_recherche) //guess wrong
{
std::cout << "rater !" << std::endl;
faute++;
}

除了代码不完整之外,实际的错误很容易发现:

  1. 你有两个循环。外部的"while";循环和内部的"for"循环。它们都使用&;i&;作为索引,所以内部"i"隐藏外部。这本身不是一个错误,但很容易导致其他错误,就像在您的程序中一样。

  2. 您的第二个"if",检查是否猜测错误,在"for"之外循环,这意味着"i"Used是外层的那个,而不是你想用的那个。

  3. 只有正确的猜测没有触发错误的猜测代码。一种方法是引入一个辅助变量

因此,考虑到这一点,它可以重写为:

int tries = 0;
while (tries < 999)                                       
{
//code

bool guess_wrong = true;
for (int i = 0; i < mot_secret.length(); i++) // to check each letter
{
if (choisi_ton_mot[i] == u_recherche) //guess right
{
guess_wrong = false
mot_secret[i] = u_recherche; // if right change "-" to the right letter
std::cout << "lettre trouver ! " << std::endl;
}
}
if (guess_wrong)
{
std::cout << "rater !" << std::endl;
faute++;
}
...

最新更新