How do I implement a food generator in a snake game (using c++ and OpenGL) that is not grid-based? -


the snake in game list of squares. each square in list defined using gl_quads, requires definition of 2 vertices (x,y , x1,y1) so:

void square::draw() const { glbegin(gl_quads);      glvertex2f(x, y);     glvertex2f(x1, y);     glvertex2f(x1, y1);     glvertex2f(x, y1);      glend(); } 

the snake moves insertion of new element @ front of list, , deletion of last. so, if snake moving towards left, , receives command move upwards, square created above snake's (previous) head, , last square in list removed.

to generate food, have 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: width , height dimensions of playfield.)

i implemented function grows snake: if coordinates of snake's head match coordinates of food. however, when run program, snake's head never @ same coordinates food block... few pixels off, here , there. there way around problem not require me re-write code grid-based implementation?

as understand explanation when snake moving compare 2 squares: square of new head , food. work correctly should detect collisions of squares , 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 eat without graphical collision on screen can draw food base coords test on collision expanded few pixels


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -