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

C#文本洞穴游戏角色左右转向失效 向前移动正常问题排查求助

问题根因定位
  • 核心问题:自定义的Point属于引用类型,C#中引用类型默认的==运算符比较的是对象的内存地址,而非对象存储的属性值。你代码中定义的dirE/dirS/dirN/dirW都是独立的Point实例,哪怕两个Point的x、y坐标完全一致,==判断也会返回false,导致你写的转向分支永远无法触发,这也是你之前修改分支内代码毫无效果的原因。
  • 转向逻辑覆盖不全:目前仅写了面朝东时按R转向南的分支,其余朝向的转向逻辑完全缺失。
  • 转向后未同步状态:转向完成后没有更新nextRoom的值,即使转向生效,按前进仍然会按照转向之前计算的nextRoom移动。
修复方案

1. 修复Point的等值判断逻辑

两种方案二选一即可:

方案A:直接比较坐标属性(无需修改Point类)

把转向判断的条件从引用比较改为坐标值比较:

// 原代码:if (playerDir == dirE && cmd == "R")
// 修改为:
if (playerDir.x == dirE.x && playerDir.y == dirE.y && cmd == "R")

方案B:给Point类重载等值运算符(一劳永逸)

修改Point类,重写等值判断相关方法,让==按照坐标值比较:

class Point
{
    public int x;
    public int y;

    public Point(int tx, int ty)
    {
        x = tx;
        y = ty;
    }

    public Point add(Point other)
    {
        int newX = this.x + other.x;
        int newY = this.y + other.y;
        return new Point(newX, newY);
    }

    public override bool Equals(object obj)
    {
        return obj is Point point && x == point.x && y == point.y;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(x, y);
    }

    public static bool operator ==(Point left, Point right)
    {
        return EqualityComparer<Point>.Default.Equals(left, right);
    }

    public static bool operator !=(Point left, Point right)
    {
        return !(left == right);
    }
}

2. 补全转向逻辑,同步更新nextRoom

补全所有朝向的右转分支,转向后立刻更新下一个房间的坐标:

if (cmd == "R")
{
    if (playerDir == dirE) playerDir = dirS;
    else if (playerDir == dirS) playerDir = dirW;
    else if (playerDir == dirW) playerDir = dirN;
    else if (playerDir == dirN) playerDir = dirE;
    // 转向后更新下一个房间的坐标
    nextRoom = pos.add(playerDir);
}

如果需要支持左转功能,也可以按照上述逻辑补充对应分支即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:51:02