I think your problem is probably partly in the get_next_position_to function, where you increment the position of the body part passed into the function. I think this should probably only add. The ‘RIGHT’ case also modifies both X and Y.
position_t get_position_next_to(body_part_t *part) {
position_t pos;
switch(part->dir) {
case UP:
initialize_position(&pos, part->pos.x, part->pos.y + 1);
break;
case DOWN:
initialize_position(&pos, part->pos.x, part->pos.y - 1);
break;
case LEFT:
initialize_position(&pos, part->pos.x - 1, part->pos.y);
break;
case RIGHT:
initialize_position(&pos, part->pos.x + 1, part->pos.y);
break;
default:
break;
}
return pos;
}
Additionally, your move_snake function does not update the following body parts. Since you are using a linked list, you could move the last element of the list to just after the head and copy the position etc from the head to the next element before moving the head. You’d need to change your list to a bidirectional list for that. You could code this far more efficiently with a circular buffer instead.
Your list cleanup function is wrong, since you free the next element before accessing it again. You need to store a temporary and iterate and then free the temporary. And you definitely shouldn’t free &snake.head as you didn’t malloc it. It should be something like this:
void cleanup() {
body_part_t* tmp;
body_part_t *next = snake.head.next;
while (next) {
tmp = next;
next = next->next;
free(tmp);
}
}
1
solved The head of the snake is a couple points away from the body (c++ game) [closed]