SDL2 C++贪吃蛇游戏自撞

SDL2 C++ Snake Game Self Collision

作为一个学校项目,我使用 SDL2 和 C++ 制作了经典的贪吃蛇游戏。 我已经为 Snake 实现了增长、移动的功能,但是它需要基于网格进行移动,但是当我实现网格功能时,self-collision 总是在增长一个部分时触发,所以每个当我开始游戏,吃到第一个水果时,蛇就死了。

我尝试了一段时间,从延迟到添加尾巴再到延迟碰撞检查,但都没有用,它总是与自己碰撞,即使它没有。

我看不出自碰撞有什么问题,如果有人能指出错误,我将不胜感激。

Snake.h

#include "GameObject.h"
#include "common.h"
#include "draw.h"
#include "Food.h"
#include "util.h"
#include <vector>

struct Segment {

    int x;
    int y;
    Segment(int posx, int posy) {

        x = posx;
        y = posy;

    }

};

class Snake :
    public GameObject

{
public:

    ~Snake();
    void start();
    void update();
    void draw();

    void outOfBoundsCheck();
    void move();
    void addSegment(int x, int y);
    void selfCollisionCheck(bool hasEaten);
    void setHasMoved(bool a);
    void setIsAlive(bool a);

    
    int getX();
    int getY();
    int getWidth();
    int getHeight();
    bool getIsAlive();
    bool getHasMoved();
    
    std::vector<Segment*> const& getV() const;


private:

    std::vector<Segment*> body;
    SDL_Texture* headTexture;
    SDL_Texture* bodyTexture;
    
    int x;
    int y;
    int width;
    int height;
    int dx;
    int dy;
    int tempX;
    int tempY;
    bool isAlive;
    bool hasMoved;
    
};

Snake.cpp


Snake::~Snake()
{
    
}

void Snake::start()
{
    // Load Texture
    headTexture = loadTexture("gfx/player.png");
    bodyTexture = loadTexture("gfx/body.png");
    
    tempX = 0;
    tempY = 0;

    x = 0;
    y = 0;
    
    dx = 0;
    dy = 0;

    isAlive = true;
    hasMoved = false;

    width = 0;
    height = 0;

    SDL_QueryTexture(headTexture, NULL, NULL, &width, &height);
    
    addSegment(x, y);
}

void Snake::update()
{   
        std::cout << "Head" << body[0]->x << std::endl;
        if (body.size() > 1) {
            std::cout << "2nd Segment" << body[1]->x << std::endl;
            if (body.size() > 2) {
                std::cout << "3nd Segment" << body[2]->x << std::endl;
            }
        }

        move();
        outOfBoundsCheck(); 
}

void Snake::draw()
{
    if (!isAlive) return; // Cancel the render if player dies
    
    for (int i = 0; i < body.size(); i++) {
        
        blit(headTexture, body[i]->x, body[i]->y);
    }
    
}

void Snake::outOfBoundsCheck()
{
    for (int i = 0; i < body.size(); i++) {
        if (body[i]->x > SCREEN_WIDTH) {

            body[i]->x = 0;

        }
        if (body[i]->x < 0) {

            body[i]->x = SCREEN_WIDTH;

        }

        if (body[i]->y > SCREEN_HEIGHT) {

            body[i]->y = 0;

        }

        if (body[i]->y < 0) {

            body[i]->y = SCREEN_HEIGHT;

        }
    }
}

void Snake::move()
{
    
    if (app.keyboard[SDL_SCANCODE_W] && dy != 5) {
        
            dx = 0;
            dy = -5;
        
    }

    if (app.keyboard[SDL_SCANCODE_A] && dx != 5) {
        
            dx = -5;
            dy = 0;
            
    }

    if (app.keyboard[SDL_SCANCODE_S] && dy != -5) {
        
            dx = 0;
            dy = 5;
            
    }

    if (app.keyboard[SDL_SCANCODE_D] && dx != -5) {
        
            dx = 5;
            dy = 0;
            
    }

    Segment* snakeHead = *(body.begin()); //Grid

    tempX += dx;
    tempY += dy;

    if (tempX % 25 == 0) {
        snakeHead->x += tempX;
        tempX = 0;
    }

    if (tempY % 25 == 0) {
        snakeHead->y += tempY;
        tempY = 0;
    }


    for (int i = body.size() - 1; i > 0; i--) { //For the other parts to follow

        body[i]->x = body[i - 1]->x;
        body[i]->y = body[i - 1]->y;

    }

    
}

void Snake::addSegment(int x, int y)
{
    Segment* seg = new Segment(x, y );
    body.push_back(seg);
}

void Snake::selfCollisionCheck(bool hasEaten) // Fail
{
    Segment* head = body[0];

    if (hasEaten == false) {
        for (int i = 1; i < body.size(); i++) {
            if (head->x == body[i]->x && head->y == body[i]->y) {
                isAlive = false;
                break;
            }
        }
    }

    else {
        return;
    }
    
}

void Snake::setHasMoved(bool a)
{
    hasMoved = a;
}


void Snake::setIsAlive(bool a)
{
    isAlive = a;
}

int Snake::getX()
{
    return x;
}

int Snake::getY()
{
    return y;
}

int Snake::getWidth()
{
    return width;
}

int Snake::getHeight()
{
    return height;
}

bool Snake::getIsAlive()
{
    return isAlive;
}

bool Snake::getHasMoved()
{
    return hasMoved;
}


std::vector<Segment*> const& Snake::getV() const
{
    // TODO: insert return statement here
    return body;
}

GameScene.h

#include "Scene.h"
#include "GameObject.h"
#include "Snake.h"
#include "Food.h"
#include "util.h"
#include "text.h"
#include "SoundManager.h"

class GameScene : public Scene
{
public:

    GameScene();
    ~GameScene();
    void start();
    void draw();
    void update();

    void spawnFood();
    void collisionLogic();
    void selfCollision();
    void despawnFood(Food* food);

private:

    Snake* snake;
    Food* food;

    int points;

    std::vector<Food*> spawnedFood;
    
};

GameScene.cpp

#include "GameScene.h"

GameScene::GameScene()
{
    // Register and add game objects on constructor
    snake = new Snake();
    this->addGameObject(snake);

    points = 0;
}

GameScene::~GameScene()
{
    delete snake;
    delete food;
}

void GameScene::start()
{
    Scene::start();
    // Initialize any scene logic here
    initFonts();
    spawnFood();
    
}

void GameScene::draw()
{
    Scene::draw();

    drawText(110, 20, 255, 255, 255, TEXT_CENTER, "POINTS: %03d", points);

    if (snake->getIsAlive() == false) {

        drawText(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 255, 255, 255, TEXT_CENTER, "GAME OVER!");
    }


}

void GameScene::update()
{
    Scene::update();

    if (spawnedFood.size() == 0 && spawnedFood.size() != 1) {
            spawnFood();
    }
    collisionLogic();
    selfCollision();
    
}

void GameScene::spawnFood()
{
    int random = rand() % 720;
    if (random % 25 != 0) {
        random = rand() % 720;
    }

    else {
        Food* food = new Food();
        this->addGameObject(food);

        food->setPosition(rand() % SCREEN_WIDTH, rand() % SCREEN_HEIGHT);

        spawnedFood.push_back(food);
    }
}

void GameScene::collisionLogic()
{
    Segment* head = snake->getV()[0];
    std::vector<Segment*> snakeBody = snake->getV();
    

    for (int i = 0; i < objects.size(); i++) {

        Food* food = dynamic_cast<Food*>(objects[i]);
    
        if (food != NULL) {

            int collision = checkCollision(
                head->x, head->y, snake->getWidth(), snake->getHeight(),
                food->getX(), food->getY(), food->getWidth(), food->getHeight()
            );

            if (collision == 1) {

                despawnFood(food);
                snake->addSegment(snakeBody[snakeBody.size() - 1]->x, snakeBody[snakeBody.size() - 1]->y); //Adds a part to the snake
                points++;

                break;

            }

        }

    }
}

void GameScene::selfCollision()
{
    std::vector<Segment*> body = snake->getV();
    Segment* head = snake->getV()[0];

    for (int i = 1; i < snake->getV().size(); i++) {
        if (head->x == body[i]->x && head->y == body[i]->y) {
                snake->setIsAlive(false);
                break;
        }
    }
    
}

void GameScene::despawnFood(Food* food)
{
    int index = -1;
    for (int i = 0; i < spawnedFood.size(); i++) {

        if (food == spawnedFood[i]) {

            index = i;
            break;

        }

    }

    if (index != -1) {

        spawnedFood.erase(spawnedFood.begin() + index);
        delete food;
    }
}

我似乎在网格移动方面遇到了一些逻辑错误,因为当我重新编码所有内容并将网格移动更改为基于单元格而不是通过将屏幕宽度和高度除以像素来使用模数条件时我的蛇的大小并将其用作我的移动坐标,一切都恢复正常并且碰撞错误消失了。

而不是为网格移动这样做

旧网格移动代码

    tempX += dx;
    tempY += dy;

    if (tempX % 25 == 0) {
        snakeHead->x += tempX;
        tempX = 0;
    }

    if (tempY % 25 == 0) {
        snakeHead->y += tempY;
        tempY = 0;
    }
 

我在 defs.h

中将其定义为永久值

defs.h

#define CELL_SIZE 25 // Size of the segment
#define CELL_WIDTH SCREEN_WIDTH / CELL_SIZE
#define CELL_HEIGHT SCREEN_HEIGHT / CELL_SIZE

在那之后,因为我仍然要用默认分辨率渲染图片,所以我将 CELL_SIZE 乘以我的 blit 函数的 dest 变量

draw.cpp

void blit(SDL_Texture* texture, int x, int y)
{
    SDL_Rect dest;

    dest.x = x * CELL_SIZE;
    dest.y = y * CELL_SIZE;
    SDL_QueryTexture(texture, NULL, NULL, &dest.w, &dest.h);

    SDL_RenderCopy(app.renderer, texture, NULL, &dest);
}

这导致蛇和我要渲染的任何其他东西遵循网格并通过使用 CELL_WIDTH 和 CELL_HEIGHT 分配 x 和 y 值作为替代决议,我完成了网格移动,与我的碰撞检查没有冲突。