samedi 28 mars 2015

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:



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?





Aucun commentaire:

Enregistrer un commentaire