贪吃蛇游戏 - 为什么蛇会跳过一个方块?

Snake Game - why does the snake skip a tile?

我制作了一个贪吃蛇游戏,效果很好,但是,当蛇到达屏幕边缘时,我让它绕回一圈。 问题是他一圈回来的时候好像漏了一段?

我不知道怎么说,所以这是一个视频。 https://youtu.be/fxuEYsrIZMU

它不是只出现在边缘,而是跳过 1 到 2 个图块。 这是代码片段:

void update(std::vector<sf::RectangleShape>& food) {
        std::cout << body.size();
        for(int i = body.size() - 1; i > 0; i--) {
            checkBounds(body.at(i)); // Check Snake is in screen.
            /* ... */
        }
        checkBounds(body.at(0));
        /* ... */
    }
void checkBounds(sf::RectangleShape& point) {
        if(point.getPosition().x < 0) point.move(WIDTH, 0);
        if(point.getPosition().y < 0) point.move(0, HEIGHT);
        if(point.getPosition().x > WIDTH) point.move(-WIDTH, 0);
        if(point.getPosition().y > HEIGHT) point.move(0, -HEIGHT);
    }

WIDTH,HEIGHT 为屏幕宽高。 正文是 std::vector<sf::RectangleShape> 这是完整的代码: https://pastebin.com/sr4Tbrin

假设您有一个网格大小为 10 的棋盘

当你决定缠绕时,蛇头会在11

但是他会被移动到11-10 = 1,而不是0。

你需要:

    if(point.getPosition().x > WIDTH) point.move(-(WIDTH+1), 0);
    if(point.getPosition().y > HEIGHT) point.move(0, -(HEIGHT+1));