gpt4 book ai didi

c - C语言中的移动蛇

转载 作者:行者123 更新时间:2023-12-01 08:56:10 24 4
gpt4 key购买 nike

我们正在 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);
}
}

关于c - C语言中的移动蛇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com