【问题标题】:Game Over condition simple Snake c++ gameGame Over 条件简单的 Snake c++ 游戏
【发布时间】:2018-09-12 22:39:23
【问题描述】:

我有 C++ 的基本知识,并且正在尝试创建一个在 while 循环中运行的简单 Snake 游戏,只要“游戏结束”条件评估为假。 如果它变成“真”(当蛇的头出界时),“游戏结束!”打印在液晶屏上。

由于某种原因,代码直接跳到游戏结束屏幕而不运行游戏本身。

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

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();
}

这怎么行不通? 谢谢

【问题讨论】:

  • 你有没有试过调试它来发现问题?
  • head_xhead_y 是如何初始化的?
  • 听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
  • 我的钱将用于缺少 _head_x_head_y 的初始化,或者将它们初始化为 0。但是 - 你应该学会使用调试器。

标签: c++ collision-detection


【解决方案1】:

试试这个,只是猜测。我认为当所有四个条件都为假时,你应该得出没有碰撞的结论。我认为您在 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;
}

【讨论】:

    【解决方案2】:

    碰撞检测是可疑的。如果您检查的所有特定条件均未返回 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多