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

C#实现随玩家探索更新的地图:寻求更优实现方案

优化非线性地图探索状态的记录方案

针对你目前用独立变量逐个记录房间探索状态的问题,这里提供几个更简洁高效的实现思路:

1. 用数组存储同楼层探索状态

把同一楼层的房间探索状态整合到一个数组中,通过房间号的偏移量作为索引访问,彻底告别零散的变量:

// 1楼共15个房间,索引0对应101号房,索引1对应102号房,以此类推
bool[] floor1Explored = new bool[15];
// 初始时101房间已探索
floor1Explored[0] = true;

// 玩家进入102房间时,更新探索状态
floor1Explored[1] = true;

// 显示地图逻辑
for (int i = 0; i < floor1Explored.Length; i++)
{
    if (floor1Explored[i])
    {
        Console.WriteLine("#####\n#   #\n#####");
    }
}

2. 用字典适配非连续房间号

如果非线性地图的房间号不连续,用字典关联房间ID和探索状态会更灵活:

Dictionary<string, bool> exploredRooms = new Dictionary<string, bool>();
// 初始化已探索的房间
exploredRooms["F101"] = true;

// 玩家进入F102房间时更新
exploredRooms["F102"] = true;

// 显示地图逻辑
foreach (var room in exploredRooms)
{
    if (room.Value)
    {
        Console.WriteLine("#####\n#   #\n#####");
    }
}

3. 面向对象封装房间属性

如果后续要给房间添加更多属性(比如相邻房间、道具、描述),直接封装成Room类可扩展性更强:

public class Room
{
    public string Id { get; set; } // 例如"F101"
    public bool IsExplored { get; set; }
    // 可扩展:List<Room> Neighbors(相邻房间)、string Description等
}

// 初始化1楼房间列表
List<Room> floor1Rooms = new List<Room>
{
    new Room { Id = "F101", IsExplored = true },
    new Room { Id = "F102", IsExplored = false },
    // 其他房间依次添加
};

// 玩家进入房间时更新探索状态
var targetRoom = floor1Rooms.First(r => r.Id == "F102");
targetRoom.IsExplored = true;

// 显示地图逻辑
foreach (var room in floor1Rooms)
{
    if (room.IsExplored)
    {
        Console.WriteLine("#####\n#   #\n#####");
    }
}

同步优化移动逻辑

原来的Forward命令判断也可以简化,用字典存储房间+方向对应的目标房间:

// 存储每个房间+方向对应的目标房间
Dictionary<(int room, int direction), int> roomTransitions = new Dictionary<(int, int), int>
{
    { (1, 1), 2 }, // 1号房间方向1可到达2号房间
    // 补充其他移动规则
};

if (command == "Forward")
{
    if (roomTransitions.TryGetValue((room, Direction), out int targetRoom))
    {
        room = targetRoom;
        // 根据楼层更新探索状态(以数组方案为例)
        if (floor == 1)
        {
            floor1Explored[room - 1] = true;
        }
    }
    else
    {
        Console.WriteLine("You ran into a wall");
    }
    goto wannado;
}

这些方案都能避免零散变量带来的冗余问题,后续新增房间或修改探索逻辑时,维护成本会大幅降低,更适配非线性地图的灵活特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:25:30