C语言最简单贪吃蛇小游戏

#include 
#include 
#include 
#include 

#define height 20
#define width 40


int i,j,k;
char ch='w';
int grow=0;


struct Food
{
    int x;
    int y;
} food;
struct Snake
{
    int x[50];
    int y[50];
    int len;
    int speed;
} snake;
void pos1(int x, int y)
{

    HANDLE hout;
    COORD cor;
    hout=GetStdHandle(STD_OUTPUT_HANDLE);
    cor.X=x;
    cor.Y=y;
    SetConsoleCursorPosition(hout,cor);
}
void pos(int x, int y,char c)
{

    HANDLE hout;
    COORD cor;
    hout=GetStdHandle(STD_OUTPUT_HANDLE);
    cor.X=x;
    cor.Y=y;
    SetConsoleCursorPosition(hout,cor);

    putchar(c);
}
void ini_map()
{
    for(int i=0;ipos(0,i,'#'),pos(width-1,i,'#');
    for(int i=0;ipos(i,0,'#'),pos(i,height-1,'#');
    snake.len=3;
    snake.speed=200;
    snake.x[0]=20;
    snake.x[1]=20;
    snake.x[2]=20;
    snake.y[0]=10;
    snake.y[1]=11;
    snake.y[2]=12;
    for(int i=0;i<3;i++)
        pos(snake.x[i],snake.y[i],'.');
    food.x=5,food.y=10;
    pos(food.x,food.y,'*');
}
void update_food()
{
    if(snake.x[0]==food.x&&snake.y[0]==food.y)
    {
        srand(time(0));
        grow=1;
        snake.len++;
        food.x=rand()%(width-2)+1;
        food.y=rand()%(height-2)+1;
        pos(food.x,food.y,'*');
    }
}
void pf_snake()
{
    int len=snake.len;
    if(kbhit()) ch=getch();
    if(!grow) pos(snake.x[len-1],snake.y[len-1],' ');
    for(int i=len-1;i;i--)
        snake.x[i]=snake.x[i-1],snake.y[i]=snake.y[i-1];
    if(ch=='w') snake.y[0]--;
    else if(ch=='s') snake.y[0]++;
    else if(ch=='a') snake.x[0]--;
    else if(ch=='d') snake.x[0]++;
    pos(snake.x[0],snake.y[0],'.');
    grow=0;
    pos1(0,height);
}
int get_speed()
{
    int len=snake.len,sd;
    if(len<10) sd=200;
    else if(len<20) sd=300;
    else sd=400;
    return sd;
}
int geme_over()
{
    if((snake.x[0]==0||snake.x[0]==width-1)||(snake.y[0]==0||snake.y[0]==height-1)) return 1;
    for(k=1; kif(snake.x[k]==snake.x[0]&&snake.y[k]==snake.y[0]) return 1;
    return 0;
}
int main()
{
    ini_map();
    while(1)
    {
        update_food();
        pf_snake();
        Sleep(get_speed());
        if(geme_over()) break;
    }
    puts("geme over!");
    system("pause");
    return 0;
}

你可能感兴趣的:(c)