Java贪吃蛇游戏开发:蛇身闭合矩形/正方形环检测实现方法
贪吃蛇蛇身闭合环检测实现问题
- 身份:Java开发新手
- 开发中项目:基于基础坐标系逻辑的贪吃蛇游戏
- 计划新增机制:当蛇身移动形成矩形/正方形闭合环时,游戏可自动识别该状态
- 已有尝试:曾编写检测方法,思路是先定位蛇身最靠左上角的身体块,再以此为起点校验矩形闭合特征,但实际运行效果始终不理想。
- 目前使用的检测方法代码如下:
public boolean checkRing() { int topLeftX = 5000; int topLeftY = 5000; for(int i = bodyParts;i>0;i--) { // 查找最左上角方块的坐标 if(x[i] < topLeftX) { topLeftX = x[i]; } if(y[i] < topLeftY) { topLeftY = y[i]; } } // 借助尚未经过bug测试的isBody()方法校验矩形特征 boolean lineFoundVert = false; int checkingX = topLeftX; int checkingY = topLeftY; int vertCounter = 1; while(!lineFoundVert) { if(isBody(checkingX, checkingY)) { vertCounter++; checkingX++; } else lineFoundVert = true; } boolean lineFoundHori = false; checkingX = topLeftX; checkingY = topLeftY; int horiCounter = 1; while(!lineFoundHori) { if(isBody(checkingX, checkingY)) { horiCounter++; checkingY++; } else lineFoundHori = true; } debug1X = topLeftX + 1; debug1Y = topLeftY + vertCounter; debug2X = topLeftX + horiCounter; debug2Y = topLeftY + 1; if(isBody(topLeftX + 1, topLeftY + vertCounter) && isBody(topLeftX + horiCounter, topLeftY + 1)) { return true; } return false; }
- 诉求:恳请社区提供可行的解决思路,优化闭合环检测的实现效果。
内容的提问来源于stack exchange,提问作者Charlie Wheeler
相关产品推荐
相关产品推荐

