【问题标题】:Snake Game - why does the snake skip a tile?Snake Game - 为什么蛇会跳过棋子?
【发布时间】:2017-08-14 08:06:59
【问题描述】:

我制作了一个蛇游戏,它运行良好,但是,当蛇到达屏幕边缘时,我让它循环回来。 问题是当他循环回来时,它似乎跳过了一段?

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

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

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 是屏幕 W. 和 H. 正文是std::vector&lt;sf::RectangleShape&gt; 这是完整的代码: https://pastebin.com/sr4Tbrin

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    假设您有一个网格大小为 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));
    

    【讨论】:

    • 问题确实出在这些行中,但解决方案不正确:正确的值分别是 -(WIDTH + 1) 和 -(HEIGHT + 1)。您提供的值会导致蛇多跳过一块,即它最终会出现在第二个字段上。
    • 没问题。至于否决票,我认为如果您将此问题作为对主要问题的评论而不是对答案的评论,它会更加明显。
    • @KjMag 谢谢!固定
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 2012-09-29
    • 1970-01-01
    • 2021-01-06
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多