我正试图创建Snake的经典游戏(在Linux终端中),但我的链表和/或基本逻辑实现都有问题。我相当确信我的move_snake()方法是正确的——然而,在完成grow_snak()后,该程序将冻结,该方法添加的节点数量与检索到的奖杯的值相同。我有一种感觉,这是因为我如何在grow_snake()类中分配指针,特别是在添加到蛇的头部之后,但我一直很困难,在这一点上我真的可以用另一双眼睛。提前谢谢。
move_snake()
// Moves the snake based on user input, via key press
void move_snake(){
struct snake_struct *temp_ptr = root;
struct snake_struct *last_node = malloc(sizeof(struct snake_struct *));
change_direction(ui); // Change direction on UI
draw_border(); // Clear screen & draw border
draw_trophy(); // Keep trophy on screen
// grow_snake();
check_position();
while(temp_ptr->next){
mvaddch(temp_ptr->y_pos, temp_ptr->x_pos, DEFAULT_SYMBOL);
last_node = temp_ptr;
temp_ptr = temp_ptr->next;
}
temp_ptr->x_pos = root->x_pos + x_dir;
temp_ptr->y_pos = root->y_pos + y_dir;
if(root->next != NULL)
temp_ptr->next = root;
last_node->next = NULL;
root = temp_ptr;
mvaddch(root->y_pos, root->x_pos, set_symbol());
refresh();
usleep(speed);
}
grow_snake()
// Grows the snake based on trophy value that was ate
void grow_snake(){
struct snake_struct *temp_ptr = root;
struct snake_struct *new_head = malloc(sizeof(struct snake_struct *));
change_direction(ui); // Change direction on UI
// int num_links = 2;
int num_links = trophy.value;
generate_trophy();
int i = 0;
draw_border(); // Clear screen & draw border
draw_trophy(); // Keep trophy on screen
while(temp_ptr->next){
mvaddch(temp_ptr->y_pos, temp_ptr->x_pos, DEFAULT_SYMBOL);
temp_ptr = temp_ptr->next;
}
for(i = 0; i < num_links; i++) {
new_head->x_pos = root->x_pos + x_dir;
new_head->y_pos = root->y_pos + y_dir;
new_head->next = root;
new_head->symbol = DEFAULT_SYMBOL;
root = new_head;
set_symbol();
change_direction(ui);
mvaddch(root->y_pos, root->x_pos, root->symbol);
refresh();
usleep(speed);
}
}
change_direction()
// Changes direction on user key input
void change_direction(char key_press){
if ((char) tolower(key_press) == 'w'){
if(y_dir == 1 && root->next){
alert(2);
}
else{
y_dir = -1;
x_dir = 0;
}
}
else if ((char) tolower(key_press) == 'a'){
if(x_dir == 1 && root->next){
alert(2);
}
else{
y_dir = 0;
x_dir = -1;
}
}
else if ((char) tolower(key_press) == 's'){
if(y_dir == -1 && root->next){
alert(2);
}
else{
y_dir = 1;
x_dir = 0;
}
}
else if ((char) tolower(key_press) == 'd'){
if(x_dir == -1 && root->next){
alert(2);
}
else{
y_dir = 0;
x_dir = 1;
}
}
}
在grow_snake()
函数中,malloc()
调用没有分配适当的字节数。通过书写:
malloc(sizeof(struct snake_struct *));
您正在为结构分配指针的大小,而不是分配结构本身的大小。删除"*"并尝试使用
malloc(sizeof(struct snake_struct));
我的感觉是,您必须在growt_snake中的每个迭代中创建一个new_head。例如移动
struct snake_struct *new_head = malloc(sizeof(struct snake_struct *));
直接在之后
for(i = 0; i < num_links; i++) {