我们正在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结构添加了上一个指针并创建了板子大小的矩阵来存储苹果/蛇段的位置,这是一个非常简单的修复。
仅当头部不与苹果碰撞时才删除尾巴。
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);
}
}
关于c - 在C中移动蛇,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34168298/