微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

寻找蛇游戏中蛇是否循环的方法

如何解决寻找蛇游戏中蛇是否循环的方法

我对 Java 比较陌生,我有一个关于我想在我的游戏中实现的机制的想法。但是,我不知道如何解决这个问题。我的蛇游戏在基本坐标系上工作。我希望它是这样的,当蛇形成一个封闭的循环(矩形或正方形)时,游戏会检测到它已经形成了一个循环。我曾尝试编写一种方法来定位蛇身体最左上角的部分,然后从那里进行检查,但似乎效果不佳。这是我尝试编写的方法,如果它有帮助的话。感谢您的帮助!!

public boolean checkRing()
    {
        
        int topLeftX = 5000;
        int topLeftY = 5000;
        for(int i = bodyParts;i>0;i--) 
        {
            // Finds coordinates of top left Box
            
            if(x[i] < topLeftX) 
            {
                topLeftX = x[i];
            }
            if(y[i] < topLeftY)
            {
                topLeftY = y[i];
            }
        }
        
        // Use isBody() method below (not bug tested) to check for rectangle
        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;
    }```

解决方法

这是一个近似的解决方案:

private boolean isEdgeCoordinate(Coordinate[] bodyparts,int index) {
   // for every bodypart check that its neighbours (bodypart one before and 
   //  bodypart one after) dont share X axis and dont share Y axis. As long 
   // as that is the case it is an edge.

   //additionally for the last bodypart you needto check that it has first 
   // bodypart as a neighbour and check them as neighbours otherwise no 
   // rectangle to begin with
}

使用此方法检查 bodyparts 数组中的边数。如果边的总数 == 4 你有一个正方形/矩形

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。