C语言-贪吃蛇运动

#include<stdio.h>
#include<conio.h>
#include<windows.h>


#define BEG_X  2
#define BEG_Y  1
#define WID   20
#define HEI   20
 

HANDLE hout;
typedef enum{UP,DOWN,LEFT,RIGHT} DIR;
typedef struct Snake_body
{
COORD pos;//蛇身的位置
struct Shake_body *next;//下一个蛇身
struct Shake_body *prev;//前一个蛇身
}SNAKE,*PSNAKE;
PSNAKE head=NULL;//蛇头
PSNAKE tail=NULL;//蛇尾


//画游戏边框的函数
void DrawBorder()
{
int i,j;
COORD pos={BEG_X,BEG_Y};
for(i=0;i<HEI;i++)
{
	SetConsoleCursorPosition(hout,pos);
  for(j=0;j<WID;j++)
  {
    if(i==0)//第一行
	{
	if(j==0)
		printf("「");
	else if(j==WID-1)
		printf("|");
	else 
		printf("—");
	}

else if(i==HEI-1)//最后一行
{
if(j ==0)
	{
	if(j==0)
		printf("⊥");
	else if(j==WID-1)
		printf("」");
	else 
		printf("—");
}
else if(j==0||j==WID-1)//第一列或最好一列

	printf("|");
else
printf("  ");
}
++pos.Y;
  }
}

//添加蛇身函数

void AddBody(COORD pos)
{
  PSNAKE pnew=(PSNAKE)calloc(1,sizeof(SNAKE));
  pnew->pos =pos;
  if(!head)
  {
  head=tail=pnew ;
  }
  else
  {
  pnew->next=head;//新蛇身的next指向原先的蛇头
  head->prev =pnew;//原先的蛇头的prew指向新创建蛇身
  head=pnew;//把新创建的蛇身作为新的蛇身
  }
  SetConsoleCursorPosition(hout,head->pos);
  printf("◎");
}

//蛇身移动的函数
void MoveBody(DIR dir)
{
PSNAKE ptmp;
COORD pos=head->pos;
switch(dir)
{
case UP:
	if(head->pos.Y >BEG_Y+1)
	--pos.Y ;
	else 
		return;
	break;
case DOWN:
	if(head->pos.Y <BEG_Y+HEI-2)
	++pos.Y ;
else 
		return;
	break;
case LEFT:
	if(head->pos .X <BEG_X+2)
	pos.X-=2;
else 
		return;
	break;
case RIGHT:
	if(head->pos .X <BEG_X+(WID-2)*2)
	pos.X +=2;
	else 
		return;
	break;
}
AddBody(pos);//添加了一个新的蛇头
ptmp=tail;//保存当前的蛇尾
tail=tail->prev ;
if(tail)
tail->next=NULL;
SetConsoleCursorPosition(hout,ptmp->pos);
printf("  ");
free(ptmp);
}
int main()
{
int ctrl;
DIR dir=RIGHT;//初始蛇的方向是向右的
COORD pos={BEG_X+2,BEG_Y+HEI/2};
system("color OE");
system("mode con cols=90 lines=30");
	hout=GetStdHandle(STD_OUTPUT_HANDLE);
printf("    --------贪吃蛇的移动------------\n");
DrawBorder();
//自定义几个蛇的身体
AddBody(pos);
pos.X +=2;
AddBody(pos);
pos.X +=2;

AddBody(pos);
pos.X +=2;

AddBody(pos);
pos.X +=2;
AddBody(pos);
//
while(ctrl=getch())
{
	switch(ctrl)
	{
	case 'w':
		if(dir==DOWN)
			continue;
		dir=UP;
		break;
	case 's':
		
		if(dir==UP)
			continue;
		dir=DOWN;
		break;
	case 'a':
		
		if(dir==RIGHT)
			continue;
		dir=LEFT;
		break;
	case 'd':
		
		if(dir==LEFT)
			continue;
		dir=RIGHT;
		break;
	case 'q':
		return 0;
	}
MoveBody(dir);

}
return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盒曰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值