c# - 如果其他语句不起作用

下面的代码是适用于C#中的城堡迷宫游戏的工作代码段。
if else结构只能正确打印dun.roomend == true)。现在,应在显示tre.isExit时显示tow.roomEnd。 tre.isExit根本不显示。
我将当前变量声明为:

public bool isExit;
public bool deadEnd;
public bool roomEnd;

tre.isExit = true;
dun.deadEnd = true;
tow.roomEnd = true;

if (dun.roomEnd == true)
{
    Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
    return;
}

if (tow.roomEnd == true)
{
    Console.WriteLine("You been caught by the Kings guard and have been placed in the tower for life.Try again");
    return;
}
else if (tre.isExit == true)
{
    Console.WriteLine("You have found the treaure... now run!!");
    return;
}
else
{
    Console.WriteLine("Too scared.....");
}

最佳答案

那是因为当您的条件之一为真时,您会立即返回。

// Don't explicitly compare to true - just write if (dun.roomEnd)
if (dun.roomEnd == true)
{
    Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
    // You end the method here, so none of the rest of the code after this will execute
    return;
}

还有,你做的事实
else if (tre.isExit == true)

表示如果
tow.roomEnd == true

也是如此。 “否则,如果”则表示“如果当前条件为真而先前条件为假”,那么
if (A) {
   // do work
}
else if (B) {
   // Do work
}

在语义上等同于
if (A) {
  // Do work
}

if (!A && B) {
   // Do work
}

最后,我顺便提到了这一点,但我想重申一下,没有必要显式比较truefalse,因此
if (tow.roomEnd == true)

应该只是
if (tow.roomEnd)

另外,我认为所有这些条件一下子都成立是没有道理的。难道实际上可以同时出现一个房间末端,一个死角和一个导出吗?至少,似乎特定位置不能既是导出又是死胡同。如果数据一次表明其中有几项是正确的,则使用needs to be corrected以便程序正常运行。

https://stackoverflow.com/questions/41106268/

相关文章:

java - 我的method.add(int)不会将用户输入添加到我的数组中

c# - 无法将类型int隐式转换为int数组

java - 为什么此代码段显示编译错误?

c++ - 长双二维动态数组C++

c++ - 编译器错误: not declared in the scope

c# - 为什么编译器认为Environment.Exit可以返回?

objective-c - ARC 不允许将 'int' 隐式转换为 'id _Nonnull'

c++ - 以下代码段出了什么问题?

ruby-on-rails-3 - 在命名空间模型上使用 factory_girl_rails 和

swift - 类型 'Category'(aka 'OpaquePointer')的值没有成员 '