c 贪吃蛇 不能移动
用c 在linux环境里写的贪吃蛇 用了 ncurses库 程序才写了一半,画出了游戏框和蛇,程序还正常,再加上让蛇移动的代码之后就出错了。
哪里有问题? 谢谢。
程序代码:
//c语言贪吃蛇,用了ncurses库 #define Y_MAX 32 //整个游戏界面 32行 #define X_MAX 92 //整个游戏界面 62列 #define Snake_unit 1 #define Food_unit 2 #define Border_unit 3 // 1:蛇 2:食物 3:边框 #define Right 0 #define Left 9 #define Up 8 #define Down 7 #include<ncurses.h> #include<stdlib.h> WINDOW* snake; //游戏窗口 int space[Y_MAX][X_MAX]; //游戏二维空间 struct snake { int x,y; struct snake* next; }; struct snake *s_head,*s_current,*s_next; int i,j,k; int direction; int main() { int snake_end(); int snake_initial(); int snake_play(); snake_initial(); snake_play(); snake_end(); } int snake_initial() { initscr(); halfdelay(5); noecho(); keypad(snake,TRUE); direction=Right; snake=newwin(Y_MAX,X_MAX,3,6); s_head=malloc(sizeof(struct snake)); s_current=malloc(sizeof(struct snake)); s_next=malloc(sizeof(struct snake)); s_head->y=3;s_head->x=9;s_head->next=s_current; s_current->y=3;s_current->x=8;s_current->next=s_next; s_next->y=3;s_next->x=7;s_next->next=NULL; //初始化蛇 长度为3 s_current=s_head; for(i=0,j=(Y_MAX-1),k=0;k<X_MAX;k++) space[i][k]=space[j][k]=Border_unit; for(i=0,j=(X_MAX-1),k=1;k<(Y_MAX-1);k++) space[k][i]=space[k][j]=Border_unit; //这俩for 设定边框 } int snake_play() {while(1){ direction=wgetch(snake); if(direction==KEY_UP) direction=Up; else if(direction==KEY_DOWN) direction=Down; else if(direction==KEY_LEFT) direction=Left; else if(direction==KEY_RIGHT) direction=Right; switch(direction) //移动头 { case Up: { s_current=s_head; s_head=malloc(sizeof(struct snake)); s_head->y=(s_current->y-1);s_head->x=s_current->x;s_head->next=s_current; break; } case Down: { s_current=s_head; s_head=malloc(sizeof(struct snake)); s_head->y=(s_current->y+1);s_head->x=s_current->x;s_head->next=s_current; break; } case Left: { s_current=s_head; s_head=malloc(sizeof(struct snake)); s_head->y=s_current->y;s_head->x=(s_current->x-1);s_head->next=s_current; break; } case Right: { s_current=s_head; s_head=malloc(sizeof(struct snake)); s_head->y=s_current->y;s_head->x=(s_current->x+1);s_head->next=s_current; } } s_current=s_head; while(1) //移动整个身体 { space[s_current->y][s_current->x]=Snake_unit; if((s_current->next)==NULL) { space[s_current->y][s_current->x]=0; s_current=NULL; break; } s_current=s_current->next; } for(i=0;i<Y_MAX;i++) for(j=0;j<X_MAX;j++) switch(space[i][j]) { case Border_unit: { wmove(snake,i,j); wprintw(snake,"#"); break; } case Snake_unit: { wmove(snake,i,j); wprintw(snake,"+"); break; } } wrefresh(snake); }} int snake_end() { wgetch(snake); endwin(); }
[此贴子已经被作者于2018-1-28 15:06编辑过]