我已经制作了这个刽子手游戏,但唯一的问题是我无法弄清楚哪些简单的循环(For,While或Do While)我应该使用该程序为用户提供三次机会如果答案正确,请正确回答或继续重复。我想知道是否有人能引导我朝着正确的方向前进?
Console.WriteLine("Do you want to play a game?");
string answer = Console.ReadLine();
if (answer == "no")
{
Console.WriteLine("Please Exit Program");
}
System.Threading.Thread.Sleep(1000);
if (answer == "yes")
{
Console.WriteLine(" ");
Console.WriteLine("Welcome to Hangman");
string[] array1 = new string[10];
array1[0] = "hello";
array1[1] = "swami";
array1[2] = "zebra";
array1[3] = "rainbow";
array1[4] = "camp";
array1[5] = "unicycle";
array1[6] = "trivia";
array1[7] = "hockey";
array1[8] = "charlie";
array1[9] = "canada";
Random word = new Random();
int mynumber = word.Next(0, 10);
char[] array2 = array1[mynumber].ToCharArray();
char[] array3 = new char[array2.Length];
Console.WriteLine(array2);
for (int i = 0; i < array2.Length; i++)
{
array3[i] = '*';
}
Console.WriteLine(" ");
Console.WriteLine(array3);
System.Threading.Thread.Sleep(1500);
Console.WriteLine(" ");
int number = 1;
number = number + 1;
Console.WriteLine(" Guess a letter");
char letter = Char.Parse(Console.ReadLine());
Console.WriteLine(" ");
for (int i = 0; i < array2.Length; i++)
{
if (letter == array2[i])
{
Console.Write(letter);
}
else
{
Console.Write("*");
}
}
Console.WriteLine(" ");
}
}
}
答案 0 :(得分:3)
暂时退出代码的细节,考虑游戏的逻辑以及如何用人类语言表达循环。
你基本上有两个循环:
如果我们将这些循环嵌套在人类语言伪代码中,它可能看起来像这样:
while (player wishes to play again)
playGame()
并在playGame()
内:
while (game isn't over)
playTurn()
如果您已经拥有进行游戏“转弯”的代码(玩家猜测,猜测是正确的或不正确的等等),那么您真正需要做的就是定义这些条件。
game isn't over
您可以为此维护一个简单的布尔标志。类似的东西:
bool gameIsOver = false;
在任何给定的回合中,检查游戏的逻辑。玩家赢了吗?显示消息并将标志设置为true
。玩家输了吗?相同的响应,只是一个不同的消息。所以循环最终会像:
bool gameIsOver = false;
while (!gameIsOver)
{
// perform turn logic
// when a turn ends the game, set gameIsOver to true
}
然后可以将相同的概念应用于外循环。那个人需要定义:
player wished to play again
所以你可能会把它结构如下:
bool continueWithAnotherGame = true;
while (continueWithAnotherGame)
{
// play a game
// ask the user if they would like to play again
// set continueWithAnotherGame based on the user's reply
}
一旦定义了循环的语义结构,用于构造循环的物理关键字变得更加直接。从那里你可以更专注于细节。例如,你说游戏有3次“罢工”。这不需要在for
循环内使用计数器,您可以使用单独的计数器。类似的东西:
bool gameIsOver = false;
int strikes = 0;
while (!gameIsOver)
{
// perform turn logic
// if the turn is a fail, increment strikes
// if strikes is greater than or equal to 3, set gameIsOver to true
// else if the turn is a pass, continue
// if the game is solved, set gameIsOver to true
}