You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#开发文本冒险游戏如何实现输入go back返回上一区域重复执行代码

实现方案

方案1:新手快速实现(封装可复用场景方法)

这个方案逻辑简单,最适配你当前的需求:

  • 把需要重复执行的「选择路径」部分代码单独封装为一个方法,需要返回的时候直接调用该方法即可
  • 方法可以设置返回值,直接接收玩家的选择结果
    示例代码如下:
// 把选择路径的逻辑封装成独立方法,返回玩家选的路径编号
static string ChoosePath()
{
    Console.WriteLine("in front of you there are three paths, which path do you take? \n 1 \n 2 \n 3 ");
    return Console.ReadLine().Trim();
}

// 主逻辑部分
string decision2 = ChoosePath();

// 修复原有代码的逻辑漏洞:第三个路径判断要加else,否则无论选1/2都会触发第三段路径的输出
if (decision2 == "1")
{
    Console.WriteLine("You have chosen the first path.");
}
else if (decision2 == "2")
{
    Console.WriteLine("You have chosen the second path ");  
}
else
{
    Console.WriteLine("you have chosen the third  path ");
}
     
// Decision 3
if (decision2 == "1")
{
    Console.WriteLine("At the end of the first path there is a chest, do you want to open it? \n yes\n no");
    string decision3 = Console.ReadLine().Trim();

    if (decision3 == "yes")
    {
        Console.WriteLine("You open the chest and see a bomb, you take the bomb and put it in your inventory, what do you do next? \n check the room \n check inventory \n or go back ");
        string decision4 = Console.ReadLine().Trim();
        // 处理go back输入的逻辑
        if(decision4 == "go back")
        {
            // 调用路径选择方法,重新执行选路径的流程
            decision2 = ChoosePath();
            // 后续可以直接根据新的decision2的值继续走对应分支逻辑
        }
    }
}

方案2:扩展性更强的实现(历史场景栈)

如果后续你需要支持多层返回(比如从更深的场景逐级退回到上一级,而非直接跳回选路径节点),可以用栈存储玩家的场景访问历史:

  • 每个场景对应一个唯一标识或者专属的执行方法
  • 玩家进入新场景时把当前场景压入栈
  • 玩家输入go back时弹出栈顶的上一个场景,执行对应逻辑即可

内容的提问来源于stack exchange,提问作者AcatFanatic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:36:04