I wrote a snake game on linux with c and ncurses.
The length of snake is automatically added after every move.
why can't I delete the last node of the linked list?
insert
Code:
#include<ncurses.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LENGTH 40
#define HEIGHT 40
#define SPACE 0
#define BORDER 1
#define SNAKE 2
#define FOOD 3
#define UP 4
#define DOWN 5
#define LEFT 6
#define RIGHT 7
typedef struct snake snake;
typedef struct food food;
int game_map[HEIGHT][LENGTH]={SPACE};
int new_direction=UP;
struct snake
{
int y,x;
snake *next;
};
snake *head=NULL,*new_head=NULL,*n=NULL;
struct food
{
int y,x;
};
food new_food;
int dir;
void init_game()
{
for(int i=0;i<LENGTH;i++)
game_map[0][i]=game_map[HEIGHT-1][i]=BORDER;
for(int i=1;i<(HEIGHT-1);i++)
game_map[i][0]=game_map[i][LENGTH-1]=BORDER;
new_food.y=5;
new_food.x=5;
head=malloc(sizeof(snake));
head->y=head->x=10;
head->next=NULL;
srand(time(NULL));
}
int get_direction()
{
int new=getch();
switch(new)
{
case KEY_UP:
new_direction=UP;break;
case KEY_DOWN:
new_direction=DOWN;break;
case KEY_LEFT:
new_direction=LEFT;break;
case KEY_RIGHT:
new_direction=RIGHT;break;
default:
break;
}
return new_direction;
}
void snake_move(int dir)
{
new_head=malloc(sizeof(snake));
new_head->next=head;
switch(dir)
{
case UP:
new_head->y=head->y-1;
new_head->x=head->x;
break;
case DOWN:
new_head->y=head->y+1;
new_head->x=head->x;
break;
case LEFT:
new_head->y=head->y;
new_head->x=head->x-1;
break;
case RIGHT:
new_head->y=head->y;
new_head->x=head->x+1;
break;
}
head=new_head;
n=new_head->next;
while(n->next!=NULL)
{
new_head=n;
n=new_head->next;
}
if((head->y==new_food.y) && (head->x==new_food.x)) //eat a new food
{
new_food.y=rand()%(HEIGHT-2)+1;
new_food.x=rand()%(LENGTH-2)+1;
}
else
{
new_head->next=NULL;
free(n);
}
}
void draw()
{
game_map[new_food.y][new_food.x]=FOOD;
n=head;
while(n!=NULL)
{
game_map[n->y][n->x]=SNAKE;
n=n->next;
}
for(int i=0;i<LENGTH;i++)
for(int j=0;j<HEIGHT;j++)
switch(game_map[i][j])
{
case BORDER:
mvprintw(i,j,"#");break;
case FOOD:
mvprintw(i,j,"O");break;
case SNAKE:
mvprintw(i,j,"*");break;
}
refresh();
}
int main(int argc,char *argv[])
{
noecho();
init_game();
initscr();
cbreak();
keypad(stdscr,true);
halfdelay(3);
while(1)
{
dir=get_direction();
snake_move(dir);
draw();
if(head->y==0 || head->y == HEIGHT-1 || head->x ==0 || head->x==HEIGHT-1)
break;
}
getch();
endwin();
}