贪吃蛇

贪吃蛇

这里写图片描述

让蛇动起来

//compile and execute in Linux 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
#define MAP_LENGTH 12
int snakeLength = 5;
int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};
int snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};
char map[15][15] = 
{
    "************",
    "*XXXXH     *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "************"
};

void Print()
{
    system("clear");
    int i,j;
    for(i = 0; i < MAP_LENGTH; i++)
    {
        for(j = 0; j < MAP_LENGTH; j++)
        {
            printf("%c",map[i][j]);
        }
        printf("\n");
    }
}

void Clear()
{
    int i,j;
    for(i = 1; i < MAP_LENGTH-1; i++)
        for(j = 1; j < MAP_LENGTH-1; j++)
            map[i][j] = ' ';
}

void Draw()
{
    int i;
    for(int i = 0; i < snakeLength-1; i++)
        map[snakeY[i]][snakeX[i]] = SNAKE_BODY;
    map[snakeY[snakeLength-1]][snakeX[snakeLength-1]] = SNAKE_HEAD;
}

void snakeMove(int x,int y)
{
    int i;
    for(i = 0; i < snakeLength-1; i++)
    {
        snakeX[i] = snakeX[i+1];
        snakeY[i] = snakeY[i+1];
    }
    snakeX[snakeLength-1] += x;
    snakeY[snakeLength-1] += y;
    Clear();
    Draw();
}

int main()
{
    Print();
    char c;
    while(scanf("%c",&c))
    {
        switch(c)
        {
            case 'W':
                snakeMove(0,-1);
                break;
            case 'A':
                snakeMove(-1,0);
                break;
            case 'S':
                snakeMove(0,1);
                break;
            case 'D':
                snakeMove(1,0);
                break;
        }
        Print();
    }
    return 0;
}

升级版

添加食物

让蛇会死掉

//compile and execute in Linux 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
#define MAP_LENGTH 12
int snakeLength = 5;
int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};
int snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};
char map[12][12] = 
{
    "************",
    "*XXXXH     *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "************"
};
void Creat_Food();
void Print()
{
    system("clear");
    int i,j;
    for(i = 0; i < MAP_LENGTH; i++)
    {
        for(j = 0; j < MAP_LENGTH; j++)
        {
            printf("%c",map[i][j]);
        }
        printf("\n");
    }
}

void Clear()
{
    int i,j;
    for(i = 1; i < MAP_LENGTH-1; i++)
        for(j = 1; j < MAP_LENGTH-1; j++)
        {
            if(map[i][j] != '$')
                map[i][j] = ' ';
        }
}

void Draw()
{
    int i;
    for(int i = 0; i < snakeLength-1; i++)
        map[snakeY[i]][snakeX[i]] = SNAKE_BODY;
    map[snakeY[snakeLength-1]][snakeX[snakeLength-1]] = SNAKE_HEAD;
}

int eatfood(int x, int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    if(map[headY][headX] == '$')
    {
        snakeLength++;
        snakeX[snakeLength-1] = headX;
        snakeY[snakeLength-1] = headY;
        return 1;
    }
    return 0;
}

int is_ok(int x,int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    int i;
    if(headX <= 0 || headX >= 11 || headY <= 0 || headY >= 11)
        return 0;
    if(map[headY][headX] == '*')
        return 0;
    for(i = 0; i < snakeLength; ++i)
    {
        int bodyX = snakeX[i];
        int bodyY = snakeY[i];
        if(headX == bodyX && headY == bodyY)
            return 0;
    }
    return 1;
}

void snakeMove(int x,int y)
{
    if(!is_ok(x,y))
    {
        getchar();
        printf("Sorry,GAME OVER! PUSH \"C\" TO CONTINUE\n");
        getchar();
        return ;
    }
    if(eatfood(x,y))
    {
        Creat_Food();
    }
    int i;
    for(i = 0; i < snakeLength-1; i++)
    {
        snakeX[i] = snakeX[i+1];
        snakeY[i] = snakeY[i+1];
    }
    snakeX[snakeLength-1] += x;
    snakeY[snakeLength-1] += y;
    Clear();
    Draw();
}

void Creat_Food()
{
    srand(time(0));
    int fx,fy;
    while(1)
    {
        fx = rand() % 12;
        fy = rand() % 12;
        if(map[fx][fy] == ' ')
        {
            map[fx][fy] = '$';
            break;
        }
    }
}
int main()
{
    Creat_Food();
    Print();
    char c;
    while(scanf("%c",&c))
    {
        switch(c)
        {
            case 'W':
                snakeMove(0,-1);
                break;
            case 'A':
                snakeMove(-1,0);
                break;
            case 'S':
                snakeMove(0,1);
                break;
            case 'D':
                snakeMove(1,0);
                break;
        }
        Print();
    }
    return 0;
}

实现kbhit()

代码来源: Linux下非阻塞地检测键盘输入的方法 (整理)

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <termios.h>
#include <unistd.h>

static struct termios ori_attr, cur_attr;

static __inline 
int tty_reset(void)
{
        if (tcsetattr(STDIN_FILENO, TCSANOW, &ori_attr) != 0)
                return -1;

        return 0;
}


static __inline
int tty_set(void)
{

        if ( tcgetattr(STDIN_FILENO, &ori_attr) )
                return -1;

        memcpy(&cur_attr, &ori_attr, sizeof(cur_attr) );
        cur_attr.c_lflag &= ~ICANON;
//        cur_attr.c_lflag |= ECHO;
        cur_attr.c_lflag &= ~ECHO;
        cur_attr.c_cc[VMIN] = 1;
        cur_attr.c_cc[VTIME] = 0;

        if (tcsetattr(STDIN_FILENO, TCSANOW, &cur_attr) != 0)
                return -1;

        return 0;
}

static __inline
int kbhit(void) 
{

        fd_set rfds;
        struct timeval tv;
        int retval;

        /* Watch stdin (fd 0) to see when it has input. */
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
        /* Wait up to five seconds. */
        tv.tv_sec  = 0;
        tv.tv_usec = 0;

        retval = select(1, &rfds, NULL, NULL, &tv);
        /* Don't rely on the value of tv now! */

        if (retval == -1) {
                perror("select()");
                return 0;
        } else if (retval)
                return 1;
        /* FD_ISSET(0, &rfds) will be true. */
        else
                return 0;
        return 0;
}

//将你的 snake 代码放在这里

int main()
{
        //设置终端进入非缓冲状态
        int tty_set_flag;
        tty_set_flag = tty_set();

        //将你的 snake 代码放在这里
        printf("pressed `q` to quit!\n");
        while(1) {

                if( kbhit() ) {
                        const int key = getchar();
                        printf("%c pressed\n", key);
                        if(key == 'q')
                                break;
                } else {
                       ;// fprintf(stderr, "<no key detected>\n");
                }
        }

        //恢复终端设置
        if(tty_set_flag == 0) 
                tty_reset();
        return 0;
}

贪吃蛇再升级版

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <termios.h>
#include <unistd.h>

static struct termios ori_attr, cur_attr;

static __inline 
int tty_reset(void)
{
        if (tcsetattr(STDIN_FILENO, TCSANOW, &ori_attr) != 0)
                return -1;

        return 0;
}


static __inline
int tty_set(void)
{

        if ( tcgetattr(STDIN_FILENO, &ori_attr) )
                return -1;

        memcpy(&cur_attr, &ori_attr, sizeof(cur_attr) );
        cur_attr.c_lflag &= ~ICANON;
//        cur_attr.c_lflag |= ECHO;
        cur_attr.c_lflag &= ~ECHO;
        cur_attr.c_cc[VMIN] = 1;
        cur_attr.c_cc[VTIME] = 0;

        if (tcsetattr(STDIN_FILENO, TCSANOW, &cur_attr) != 0)
                return -1;

        return 0;
}

static __inline
int kbhit(void) 
{

        fd_set rfds;
        struct timeval tv;
        int retval;

        /* Watch stdin (fd 0) to see when it has input. */
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
        /* Wait up to five seconds. */
        tv.tv_sec  = 0;
        tv.tv_usec = 0;

        retval = select(1, &rfds, NULL, NULL, &tv);
        /* Don't rely on the value of tv now! */

        if (retval == -1) {
                perror("select()");
                return 0;
        } else if (retval)
                return 1;
        /* FD_ISSET(0, &rfds) will be true. */
        else
                return 0;
        return 0;
}

//灏嗕綘鐨?snake 浠g爜鏀惧湪杩欓噷
#include <stdlib.h>
#include <time.h>
#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
#define MAP_LENGTH 12
int snakeLength = 5;
int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};
int snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};
char map[12][12] = 
{
    "************",
    "*XXXXH     *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "************"
};
void Creat_Food();
void Print()
{
    system("clear");
    int i,j;
    for(i = 0; i < MAP_LENGTH; i++)
    {
        for(j = 0; j < MAP_LENGTH; j++)
        {
            printf("%c",map[i][j]);
        }
        printf("\n");
    }
}

void Clear()
{
    int i,j;
    for(i = 1; i < MAP_LENGTH-1; i++)
        for(j = 1; j < MAP_LENGTH-1; j++)
        {
            if(map[i][j] != '$')
                map[i][j] = ' ';
        }
}

void Draw()
{
    int i;
    for(int i = 0; i < snakeLength-1; i++)
        map[snakeY[i]][snakeX[i]] = SNAKE_BODY;
    map[snakeY[snakeLength-1]][snakeX[snakeLength-1]] = SNAKE_HEAD;
}

int eatfood(int x, int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    if(map[headY][headX] == '$')
    {
        snakeLength++;
        snakeX[snakeLength-1] = headX;
        snakeY[snakeLength-1] = headY;
        return 1;
    }
    return 0;
}

int is_ok(int x,int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    int i;
    if(headX <= 0 || headX >= 11 || headY <= 0 || headY >= 11)
        return 0;
    if(map[headY][headX] == '*')
        return 0;
    for(i = 0; i < snakeLength; ++i)
    {
        int bodyX = snakeX[i];
        int bodyY = snakeY[i];
        if(headX == bodyX && headY == bodyY)
            return 0;
    }
    return 1;
}

void snakeMove(int x,int y)
{
    if(!is_ok(x,y))
    {
        getchar();
        printf("Sorry,GAME OVER! PUSH \"C\" TO CONTINUE\n");
        getchar();
        return ;
    }
    if(eatfood(x,y))
    {
        Creat_Food();
    }
    int i;
    for(i = 0; i < snakeLength-1; i++)
    {
        snakeX[i] = snakeX[i+1];
        snakeY[i] = snakeY[i+1];
    }
    snakeX[snakeLength-1] += x;
    snakeY[snakeLength-1] += y;
    Clear();
    Draw();
}

void Creat_Food()
{
    srand(time(0));
    int fx,fy;
    while(1)
    {
        fx = rand() % 12;
        fy = rand() % 12;
        if(map[fx][fy] == ' ')
        {
            map[fx][fy] = '$';
            break;
        }
    }
}
int main()
{
        //璁剧疆缁堢杩涘叆闈炵紦鍐茬姸鎬?
        int tty_set_flag;
        tty_set_flag = tty_set();
        Creat_Food();
        Print();
        char c;
        while(scanf("%c",&c))
        {
            switch(c)
            {
                case 'W':
                    snakeMove(0,-1);
                    break;
                case 'A':
                    snakeMove(-1,0);
                    break;
                case 'S':
                    snakeMove(0,1);
                    break;
                case 'D':
                    snakeMove(1,0);
                    break;
            }
            Print();
        }
        //灏嗕綘鐨?snake 浠g爜鏀惧湪杩欓噷
        printf("pressed `q` to quit!\n");
        while(1) {

                if( kbhit() ) {
                        const int key = getchar();
                        printf("%c pressed\n", key);
                        if(key == 'q')
                                break;
                } else {
                       ;// fprintf(stderr, "<no key detected>\n");
                }
        }

        //鎭㈠缁堢璁剧疆
        if(tty_set_flag == 0) 
                tty_reset();
        return 0;
}

智能蛇

//compile and execute in Linux 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
#define MAP_LENGTH 12
int snakeLength = 5;
int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};
int snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};
char map[15][15] = 
{
    "************",
    "*XXXXH     *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "*          *",
    "************"
};
void Creat_Food();
void Print()
{
    system("clear");
    int i,j;
    for(i = 0; i < MAP_LENGTH; i++)
    {
        for(j = 0; j < MAP_LENGTH; j++)
        {
            printf("%c",map[i][j]);
        }
        printf("\n");
    }
}

void Clear()
{
    int i,j;
    for(i = 1; i < MAP_LENGTH-1; i++)
        for(j = 1; j < MAP_LENGTH-1; j++)
        {
            if(map[i][j] != '$')
                map[i][j] = ' ';
        }
}

void Draw()
{
    int i;
    for(int i = 0; i < snakeLength-1; i++)
        map[snakeY[i]][snakeX[i]] = SNAKE_BODY;
    map[snakeY[snakeLength-1]][snakeX[snakeLength-1]] = SNAKE_HEAD;
}

int eatfood(int x, int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    if(map[headY][headX] == '$')
    {
        snakeLength++;
        snakeX[snakeLength-1] = headX;
        snakeY[snakeLength-1] = headY;
        return 1;
    }
    return 0;
}

int is_ok(int x,int y)
{
    int headX = snakeX[snakeLength-1]+x;
    int headY = snakeY[snakeLength-1]+y;
    int i;
    if(headX <= 0 || headX >= 11 || headY <= 0 || headY >= 11)
        return 0;
    if(map[headY][headX] == '*')
        return 0;
    for(i = 0; i < snakeLength; ++i)
    {
        int bodyX = snakeX[i];
        int bodyY = snakeY[i];
        if(headX == bodyX && headY == bodyY)
            return 0;
    }
    return 1;
}

void snakeMove(int x,int y)
{
    if(!is_ok(x,y))
    {
        getchar();
        printf("Sorry,GAME OVER! PUSH \"C\" TO CONTINUE\n");
        getchar();
        return ;
    }
    if(eatfood(x,y))
    {
        Creat_Food();
    }
    int i;
    for(i = 0; i < snakeLength-1; i++)
    {
        snakeX[i] = snakeX[i+1];
        snakeY[i] = snakeY[i+1];
    }
    snakeX[snakeLength-1] += x;
    snakeY[snakeLength-1] += y;
    Clear();
    Draw();
}

void Creat_Food()
{
    srand(time(0));
    int fx,fy;
    while(1)
    {
        fx = rand() % 12;
        fy = rand() % 12;
        if(map[fx][fy] == ' ')
        {
            map[fx][fy] = '$';
            break;
        }
    }
}
int headi,headj,foodi,foodj;

void find_head()
{
    int i, j;
    for(i = 0; i < 12; i++)
    {
        for(j = 0; j < 12; j++)
        {
            if(map[i][j] == 'H')
            {
                headi = i;
                headj = j;
                goto here;
            }
        }
    }
here:
    return ;
}

void find_food()
{
    int i,j;
    for(i = 0; i < 12; i++)
    {
        for(j = 0; j < 12; j++)
        {
            if(map[i][j] == '$')
            {
                foodi = i;
                foodj = j;
                goto here;
            }
        }
    }
here:
    return;
}
//a d w s
int movable[10];
void find_way()
{
    int i;
    for(i = 0; i < 10; i++)
        movable[i] = 0;
    if(is_ok(-1,0))
        movable[0] = 1;
    if(is_ok(1,0))
        movable[1] = 1;
    if(is_ok(0,-1))
        movable[2] = 1;
    if(is_ok(0,1))
        movable[3] = 1;
}

int distance[10];

void count_distance()
{
    int i = 0;
    for(i = 0; i < 10; i++)
        distance[i] = 0;
    distance[0] = abs(foodi - (headi)) + abs(foodj - (headj-1));
    distance[1] = abs(foodi - (headi)) + abs(foodj - (headj+1));
    distance[2] = abs(foodi - (headi-1)) + abs(foodj - (headj));
    distance[3] = abs(foodi - (headi+1)) + abs(foodj - (headj));
}
#define Min(a,b) a > b ? b : a
void SmartSnake()
{
//  getchar();
    find_food();
    find_head();
    find_way();
    count_distance();
    int i;int t;
    int minn = 9999;
    for(i = 0; i < 4; i++)
    {
        if(movable[i] > 0)
        {
            if(minn > distance[i])
            {
                t = i;
                minn = distance[i];
            }
        }
    }
/*  for(i = 0; i < 4; i++)
        printf("%d ",distance[i]);
    printf("\n");
    for(i = 0; i < 4; i++)
        printf("%d ",movable[i]);
    printf("\n");
    printf("t %d",t);
    getchar();
*/  if(minn == 9999)
        return ;
    else
    {
        switch(t)
        {
            case 0:
                snakeMove(-1,0);
                Print();
                break;
            case 1:
                snakeMove(1,0);
                Print();
                break;
            case 2:
                snakeMove(0,-1);
                Print();
                break;
            case 3:
                snakeMove(0,1);
                Print();
                break;
        }
    }
}

int main()
{
    Creat_Food();
    Print();
    char c;
    printf("if you want to make your snake smart,Please press Z\n");
    printf("else press ADWS to play the game,enjoy yourself\n");
    while(scanf("%c",&c))
    {
        if(c == 'Z')
        {while(1)
            SmartSnake(); 
        break;}
        switch(c)
        {
            case 'W':
                snakeMove(0,-1);
                break;
            case 'A':
                snakeMove(-1,0);
                break;
            case 'S':
                snakeMove(0,1);
                break;
            case 'D':
                snakeMove(1,0);
                break;
        }
        Print();
    }
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值