curses库写的贪吃蛇游戏
用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;
}
//snake初始化
int snake_win(int x,int y)
{
int i;
for(i=0;i<=snake.node;i++)
{
snake.x[snake.node-i]=snake.x[snake.node-i-1];
snake.y[snake.node-i]=snake.y[snake.node-i-1];
}
snake.x[0]=x;
snake.y[0]=y;
return 0;
}
int main ()
{
initscr();
noecho();
keypad(stdscr,TRUE);
//nodelay(stdscr,TRUE);
win();
socrewin();
refresh();
switch(menu())
{
case 'a':
gamerun();
case 'q':
break;
}
endwin();
return 0;
}
贪吃蛇.c.zip
(1.58 KB)
[ 本帖最后由 yxwzyyk 于 2010-11-4 16:25 编辑 ]