我正在猜数字游戏,在结束时,我想告诉用户猜测正确答案需要多少次尝试。我还希望能够询问用户是否想再玩一次。我对此非常陌生,我只是在努力想弄清楚如何做到这一点。如果有人可以提供帮助,将不胜感激。
public void Play()
{
HiLow hi = new HiLow();
int number = hi.Number;
int guess;
for (guess = PromptForInt("\nEnter your guess! "); guess != number; guess = PromptForInt("\nEnter your guess! "))
{
if (guess < number)
{
Console.WriteLine("Higher");
}
else if (guess > number)
{
Console.WriteLine("Lower");
}
}
Console.WriteLine("You win! {0} was the correct number!", number);
}
答案 0 :(得分:1)
您只需要定义一个counter
来存储用户尝试,然后您可以将您的for循环放在while(true)
内,这样您就可以在for
之后询问用户是否要再次播放循环:
while(true)
{
int attempts = 0;
for(...)
{
if (guess < number)
{
Console.WriteLine("Higher");
attempts++;
}
else if (guess > number)
{
Console.WriteLine("Lower");
attempts++;
}
}
Console.WriteLine("You win! {0} was the correct number! your attempts: {1}", number, attempts);
Console.WriteLine("Would you like to try again ? (y / n)");
if(Console.ReadLine().ToLower() != "y") break;
}
答案 1 :(得分:0)
这个怎么样
public void Play()
{
HiLow hi = new HiLow();
int number = hi.Number;
int guess;
int attempts=0;
for (guess = PromptForInt("\nEnter your guess! "); guess != number; guess = PromptForInt("\nEnter your guess! "))
{
if (guess < number)
{
Console.WriteLine("Higher");
}
else if (guess > number)
{
Console.WriteLine("Lower");
}
attempts++;
}
Console.WriteLine("You win! {0} was the correct number!", number);
}
然后您可以输出&#39;尝试&#39;告诉他们尝试了多少次。
此时,为了给他们再次播放的选项,最好不要单独播放Play()并将重放的逻辑放入任何调用Play(因为Play是单个播放的一个很好的实现,不需要复杂化)
void PlayGame(){
while(UserNoWantToQuit()){
Play();
}
}