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

JavaScript俄罗斯方块:解决I型方块旋转越界问题

解决俄罗斯方块rotateRight()旋转时边缘拉扯问题

核心问题分析

你的代码存在两个关键问题:

  1. 两个独立的if (checkEdgeL)和if (checkEdgeR)判断块,当方块同时触发左右边缘越界时,会先后执行两次位置修正,导致I型方块被来回拉扯。
  2. 直接通过current === tetraminosArray[6][currentRotation]比较对象的方式不够可靠,容易因为引用变化出现判断错误。

重构后的边缘修正逻辑

// 先处理同时触发左右边缘越界的特殊情况
if (checkEdgeL && checkEdgeR) {
  const isIPiece = (random === 6);
  if (isIPiece) {
    if (currentRotation === 2) {
      currentPosition += 2;
    } else if (currentRotation === 0) {
      currentPosition += 1;
    }
  } else {
    if (currentRotation === 2) {
      currentPosition += 1;
    } else if (currentRotation === 0) {
      currentPosition -= 1;
    }
  }
} 
// 仅左边缘越界时修正
else if (checkEdgeL) {
  const isIPiece = (random === 6);
  if (isIPiece) {
    if (currentRotation === 2) {
      currentPosition += 2;
    } else if (currentRotation === 0) {
      currentPosition += 1;
    }
  } else {
    if (currentRotation === 2) {
      currentPosition += 1;
    }
  }
} 
// 仅右边缘越界时修正
else if (checkEdgeR) {
  const isIPiece = (random === 6);
  if (isIPiece) {
    if (currentRotation === 2) {
      currentPosition -= 1;
    } else if (currentRotation === 0) {
      currentPosition -= 2;
    }
  } else {
    if (currentRotation === 0) {
      currentPosition -= 1;
    }
  }
}

draw();
console.log(currentRotation);

关键修改说明

  • 互斥逻辑拆分:用else if将「同时越界、仅左越界、仅右越界」三种情况互斥开,确保同一时间只执行一种位置修正,避免重复修改导致拉扯。
  • 简化方块类型判断:用isIPiece = (random === 6)替代对象引用比较,代码更清晰且避免引用变化带来的判断错误。
  • 合并特殊场景处理:将同时越界的情况单独前置处理,避免左右两个逻辑互相覆盖位置值。

调试建议

  • 在位置修正前后打印currentPosition、checkEdgeL、checkEdgeR的值,确认每次修正的逻辑是否符合预期。
  • 针对I型方块的不同旋转状态单独打日志,跟踪旋转前后的位置变化是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:42:55