C语言编写贪吃蛇小游戏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dreamispossible/article/details/81988737
                                            **游戏结构**

      1.知道怎么控制终端上光标的位置。

  #include<stdio.h>
  #include<stdlib.h>
  #include<windows.h>
 int main(intargc,char*argv[])
  {
      COORDpos ={};
       HANDLEhOutput=NULL;
       pos.X=10;
       pos.Y=20;
     hOutput=GetStdHandle(STD_OUTPUT_HANDLE);//获取一个指向特定标准设备的句柄
     SetConsoleCursorPosition(hOutput,pos);
       printf("this issnake\n)
  }

将设置位置功能封装成一个函数

void SetPos(int x, int y)
{
 COORD pos = {0};//COORD是WindowsAPI中定义的一种结构,表示一个字符在控制台屏幕上的坐标。pos是一个结构体变量
 HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);//获取标准输出的句柄
 pos.X = x;
 pos.Y = y;
 SetConsoleCursorPosition(handle,pos);//获取标准输出上光标的位置
}

      2:绘制地图
            在这里插入图片描述
根据上图,代码如下:

void CreateMap()
{
 color(7);
 int i = 0;
 //上
 for (i = 0; i <= 58; i += 2)
 {
  SetPos(i, 0);
  printf(WALL);
 }
 //下
 for (i = 0; i <= 58; i += 2)
 {
  SetPos(i,27);
  printf(WALL);
 }
 //左
 for (i = 1; i <= 26; i++)
 {
  SetPos(0,i);
  printf(WALL);
 }
 //右
 for (i = 1; i <= 26; i++)
 {
  SetPos(58,i);
  printf(WALL);
 }
}

      3:绘制蛇
这里的蛇用链表保存。所以需要蛇身体节点,以及维护整条蛇的数据结构,另外,蛇的
前进方向我们定义成枚举,我们也一并把游戏的运行状态也定义了。

#define WALL "■"//墙
#define FOOD "▲"//蛇的食物
#define INIT_X 20//蛇的初始位置
#define INIT_Y 10
//方向
enum  Direction
{
 UP = 1,
 DOWN,
 LEFT,
 RIGHT
};
//游戏状态
enum GameStatus
{
 OK,//正常运行
 NORMAL_END,//正常结束
 KILL_BY_WALL,//撞墙
 KILL_BY_SELF//咬到自己
};
//蛇身节点
typedef struct SnakeNode
{
 int x;
 int y;
 struct SnakeNode* next;
}SnakeNode,*pSnakeNode;
typedef struct Snake
{
 pSnakeNode _pSnake;//维护整条蛇的指针
 pSnakeNode _Food;//维护食物的指针
 int _TotalScore;//总分
 int _AddScore;//加分
 int _SleepTime;//每走一步的睡眠时间
 enum  Direction _Dir;
 enum GameStatus _Status;
}Snake,*pSnake;

初始化蛇

void InitSnake(pSnake ps)
{
 color(4);
 pSnakeNode first = BuyNode();
 pSnakeNode cur = NULL;
 int i = 0;
 first->x = INIT_X;
 first->y = INIT_Y;
 for (i = 1; i <= 4; i++)
 {
  cur = BuyNode();
  cur->x = first->x + 2;
  cur->y = first->y;
  cur->next = first;
  first = cur;
 }
 //绘制蛇
 while (cur)
 {
  SetPos(cur->x,cur->y);
  printf(FOOD);
  cur = cur->next;
 }
 ps ->_pSnake = first;
 SetPos(30,13);
}

      4:产生食物

void CreateFood(pSnake ps)
{
 pSnakeNode pFood = BuyNode();
 pSnakeNode cur = ps->_pSnake;
 pFood->y = rand() % 26 + 1;
 do
 {
  pFood->x = rand() % 55 + 2;
 } while (pFood->x % 2 !=0);
 
 while (cur)
 {
  if (cur->x == pFood->x && cur->y == pFood->y)
  {
   CreateFood(ps);
   return;
  }
  cur = cur->next;
 }
 ps->_Food = pFood;
 SetPos(pFood->x,pFood ->y );
 printf(FOOD);
 //printf("\n");
} 

      5:封装成一个初始化函数
为了用户的友好,加入了一个启动界面

在这里插入代码片

猜你喜欢

转载自blog.csdn.net/dreamispossible/article/details/81988737