用curses庫寫的貪吃蛇游戲,額 初學c語言,可能寫的很垃圾,代碼也很亂 ,剛學編程的可以看看, 希望有高手能指點下
#include <stdio.h>
#include <curses.h>
#include <stdlib.h>
#include <time.h>
struct Food{
int x;
int y;
int exist;
};
struct Snake{
int x[100];
int y[100];
int node;
};
struct Food food;
struct Snake snake;
int t=300000;
int point=0;
//繪制主窗口
int win(void)
{
int i;
for(i=0;i<20;i++)
{
move(i,0);
addstr("+");
move(i,50);
addstr("+");
}
for(i=0;i<=50;i++)
{
move(0,i);
addstr("+");
move(20,i);
addstr("+");
}
}
//繪制得分窗口
int socrewin (void)
{
int i;
for(i=0;i<5;i++)
{
move(i,52);
addstr("+");
move(i,62);
addstr("+");
}
for (i = 52; i <=62; i += 1)
{
move(0,i);
addstr("+");
move(5,i);
addstr("+");
}
}
//菜單選項
int menu(void)
{
int ch;
move(3,5);
addstr("a. Star");
move(5,5);
addstr("q. Exit");
ch=getch();
switch(ch)
{
case a:
return a;
case q:
return q;
}
}
//游戲運行
int gamerun(void)
{
int ch,i;
i=0;
snake.x[0]=10;
snake.y[0]=25;
snake.node=1;
nodelay(stdscr,TRUE);
food_init();
while(i!=-1)
{
if((pd())==1)
{
food_init();
}
snake_win(snake.x[0],snake.y[0]);
food_win(food.x,food.y);
if((game_win())==-1)
break;
ch=getch();
if((key(ch))!=0)
i=key(ch);
switch(i)
{
case 1:
snake.x[0]--;
break;
case 2:
snake.x[0]++;
break;
case 3:
snake.y[0]--;
break;
case 4:
snake.y[0]++;
break;
}
coo ();
}
move(10,20);
addstr("Game over");
refresh();
sleep(5);
return 0;
}
//食物初始化
int food_init(void)
{
srand((int)time(0));
food.x=rand()%20;
if(food.x==0)
food.x=1;
food.y=rand()%50;
if(food.y==0)
food.y=1;
food_win(food.x,food.y);
}
//游戲圖形繪制
int game_win(void)
{
int i;
if(snake.x[0]==0||snake.x[0]==20||snake.y[0]==0||snake.y[0]==50)
return -1;
for (i=0;i<=snake.node;i++)
{
move(snake.x[i],snake.y[i]);
addstr("O");
}
move(LINES-1,0);
return 0;
}
//鍵盤信號捕捉
int key (ch)
{
if(ch==KEY_UP)
return 1;
if(ch==KEY_DOWN)
return 2;
if(ch==KEY_LEFT)
return 3;
if(ch==KEY_RIGHT)
return 4;
if(ch==q)
return -1;
return 0;
}
//判斷
int pd(void)
{
if(food.x==snake.x[0])
{
if(food.y==snake.y[0])
{
snake.node++;
point++;
return 1;
}
}
return 0;
}
//得分
int Score()
{
move(2,55);
addstr("Score");
move(3,57);
printw("%d",point);
}
//食物圖形繪制
int food_win(int x, int y)
{
move(x,y);
addstr("$");
return 0;
}
//刷新屏幕
int coo (void)
{
clear();
win();
socrewin();
Score();
usleep(t);
refresh();
return 0;
}