我们正在STM32探索板上创建一个蛇游戏,并将其显示在LED屏幕上。我们将蛇存储在链表类型的结构中。我们有碰撞检测的东西,我们知道如何移动蛇头,但我们不知道如何生长。你能给我们一些建议吗?
以下是我们的产品:
void move_seg() {
struct seg *temp = malloc(sizeof(struct seg));
temp->x = head->x + xdir[direction]*4;
temp->y = head->y + ydir[direction]*4;
head->next = temp;
head = temp;
draw_seg(head, WHITE);
//check if snake collided with itself..
collision_detection();
//check if apple was eaten
apple_eaten();
if (apple_was_eaten) {
draw_seg(tail, WHITE);
}
else {
draw_seg(tail, BLACK);
}
tail = tail->next;
}
}
我只是想发布一个更新来展示我们所做的。一旦我们在seg结构中添加了一个prev指针,并创建了一个板大小的矩阵来存储苹果/蛇段的位置,这是一个非常简单的修复方法。
只有当苹果的头部没有与苹果碰撞时,我们才会删除尾部。
void move_seg() {
//get head's next position, set that as new head
seg* next_head = malloc(sizeof(seg));
next_head->x = (head->x + xdir[direction] + 24) % 24;
next_head->y = (head->y + ydir[direction] + 32) % 32;
next_head->prev = 0;
next_head->next = head;
head->prev = next_head;
head = next_head;
int delete_tail = 1;
//check if head collided with apple
if (board[head->x][head->y] == HAS_APPLE) {
//if so, delete tail, create new apple
delete_tail = 0;
create_apple();
}
//check if head collided with any other part of the snake
if (board[head->x][head->y] == HAS_SNAKE) {
//if so, game over
game_over = 1;
}
//draw the head, add it to the matrix
draw_seg(head, WHITE);
board[head->x][head->y] = HAS_SNAKE;
//if the snake didn't collide with an apple
if (delete_tail) {
//delete the tail
board[tail->x][tail->y] = 0;
seg* temp = tail;
tail = temp->prev;
tail->next = 0;
draw_seg(temp, BLACK);
//free(temp);
}
}