【发布时间】: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_x和head_y是如何初始化的? -
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
-
我的钱将用于缺少
_head_x或_head_y的初始化,或者将它们初始化为 0。但是 - 你应该学会使用调试器。