[英]How do I implement a food generator in a snake game (using c++ and OpenGL) that is not grid-based?
The snake in my game is basically a list of squares. 我的游戏中的蛇基本上是正方形列表。 Each square in this list is defined using GL_QUADS, which requires definition of two vertices (x,y and x1,y1) as so: 此列表中的每个正方形都是使用GL_QUADS定义的,它需要这样定义两个顶点(x,y和x1,y1):
void Square::draw() const
{
glBegin(GL_QUADS);
glVertex2f(x, y);
glVertex2f(x1, y);
glVertex2f(x1, y1);
glVertex2f(x, y1);
glEnd();
}
The snake moves by insertion of a new element at the front of the list, and deletion of the last. 通过在列表的前面插入新元素并删除最后一个元素,蛇会移动。 So, if the snake was initially moving towards the left, and receives a command to move upwards, a square would be created above the snake's (previous) head, and the last square in the list will be removed. 因此,如果蛇最初是向左移动并收到向上移动的命令,则将在蛇的(上一个)头部上方创建一个正方形,然后将删除列表中的最后一个正方形。
To generate food, I have the following code: 为了产生食物,我有以下代码:
void generate_food()
{
time_t seconds
time(&seconds);
srand((unsigned int)seconds);
x = (rand() % (max_width - min_width + 1)) + min_width;
y = (rand() % (max_height - min_height + 1)) + min_height;
x1 = foodx + 10;
y1 = foody + 10;
food = new Square{x,y,x1,y1 };
}
(Note: the width and height are dimensions of the playfield.) (注意:宽度和高度是运动场的尺寸。)
I also implemented a function that grows the snake: if the coordinates of the snake's head match the coordinates of the food. 我还实现了使蛇长大的功能:如果蛇头的坐标与食物的坐标匹配。 However, when I run the program, the snake's head is never EXACTLY at the same coordinates as the food block... a few pixels off, here and there. 但是,当我运行该程序时,蛇的头永远不会与食物块处于完全相同的坐标……到处都是几个像素。 Is there any way around this problem which does not require me to re-write all my code with a grid-based implementation? 有什么办法可以解决这个问题,而无需我用基于网格的实现来重写所有代码?
As i understand your explanation when snake is moving you compare two squares: square of new head and food. 据我了解您在蛇移动时的解释,您将比较两个正方形:新头和食物的正方形。 So to get it work correctly you should detect collisions of squares and not full equality. 因此,要使其正常工作,您应该检测正方形的碰撞而不是完全相等。
bool rectHitTest(const Square head, const Square food){
if ((head.x2 < food.x1 || head.y2 < food.y1) ||
(head.x1 > food.x2 || head.y1 > food.y2))
return false;
return true;
}
To allow it eat without graphical collision on the screen you can draw your food with base coords but test on collision with expanded for a few pixels 为了让它在屏幕上不发生图形碰撞的情况下进食,您可以使用基本坐标绘制食物,但在碰撞时进行测试,并扩展几个像素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.