游戏结束条件简单的贪吃蛇 C++ 游戏

Game Over condition simple Snake c++ game

我具有 C++ 的基本知识,并且正在尝试创建一个在 while 循环中运行的简单贪吃蛇游戏,只要 "Game Over" 条件的计算结果为 false。 如果变成"true"(当蛇头出界时),"Game Over!"会打印在液晶屏上。

出于某种原因,代码直接跳到游戏结束屏幕,运行 没有游戏本身。

我的代码涉及一些 类,其中一个我有一个碰撞检测功能,如下所示:

bool SnakeEngine::collision_detection()
{
    // check the snake coordinates so that the head doesn't go off screen
    if (_head_y < 1) {
        return 1;
    }
    if (_head_y > HEIGHT - 4) {
        return 1;
    }
    if (_head_x < 1) {
        return 1;
    }
    if (_head_x > WIDTH - 4) {
        return 1;
    } else {
        return 0;
    }

}

在主循环中我有:

int main()
{
    snake.draw(lcd); // draw the initial game frame and the sprites
    lcd.refresh();

    while(!snake.collision_detection()) {

        snake.read_input(pad); // reads the user input
        snake.update(pad); // updates the sprites positions and calls the collision_detection() function
        render(); // clears the lcd, draws the sprites in the updated positions, refreshes the lcd
        wait(1.0f/fps);

    }
    lcd.printString("Game Over!",6,4);
    lcd.refresh();
}

为什么这不起作用? 谢谢

试试这个,只是 guessing.I 想想当所有四个条件都为假时,你应该得出没有碰撞的结论。我认为您在 collision_detection() 的最后一个 else 语句中犯了一个错误。

bool SnakeEngine::collision_detection()
{
    // check the snake coordinates so that the head doesn't go off screen
    if (  _head_y < 1 || _head_y > (HEIGHT - 4) || _head_x < 1 || _head_x > (WIDTH - 4) )
        return true;

       return false;
}

碰撞检测有问题。如果您检查的所有特定条件都不 return true (1),则最终结果应为 false (0).

这个条件太严格了:

  if (_head_x > WIDTH - 4) {
        return 1;
    } else {
        return 0;
    }

应限制为:

  if (_head_x > WIDTH - 4) {
        return 1;
  }

  return 0;

修改后的代码使用 bool 类型 truefalse 看起来像:

bool SnakeEngine::collision_detection()
{
    // check the snake coordinates so that the head doesn't go off screen
    if (_head_y < 1) {
        return true;
    }

    if (_head_y > HEIGHT - 4) {
        return true;
    }

    if (_head_x < 1) {
        return true;
    }

    if (_head_x > WIDTH - 4) {
        return true;
    } 

    return false;
}