当我一个中午写完下面的代码时,突然感觉我也可以当大佬了
声明:除了隐藏光标那个函数是上网扣的,其他均属原创
#include<cstdio>
#include<windows.h>
#include<conio.h>
#include<ctime>
using namespace std;
const int N=15;
char sit[N+1][N+1],ctl;
int d[4][2]={
{
-1,0},{
1,0},{
0,-1},{
0,1}},dir;
bool flag=1,op;
void HideCursor()//隐藏光标
{
CONSOLE_CURSOR_INFO cursor_info = {
1,0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void print()//输出
{
system("cls");
for(int i=1;i<=N;i++)
{
for(int j=1;j<=N;j++)
printf("%c",sit[i][j]);
printf("\n");
}
}
class snake//定义snake类型
{
public:
snake* ne;
int x,y;
void move(int tox,int toy)//移动到它上一个节点的位置
{
sit[x][y]=' ';
x=tox,y=toy;
sit[x][y]='*';
}
snake(int a,int b)//初始化
{
x=a,y=b;
sit[x][y]='*';
ne=NULL;
}
};
snake head(N/2,N/2);//蛇的头
void bmove(snake* body,int p,int q,bool add)//蛇身移动
{
int a=body->x,b=body->y;
body->move(p,q);
if(body->ne)//如果它后面有节点
bmove(body->ne,a,b,add);
else if(add)//如果要新增节点
body->ne=new snake(a,b);
}
void hmove(snake* head,int dir)//蛇头移动
{
int a=head->x,b=head->y;
int p=a,q=b;
a+=d[dir][0];
b+=d[dir][1];
if(a<1||a>N||b<1||b>N)
flag=0;
else
{
bool add=sit[a][b]=='@'?1:0;
sit[head->x][head->y]=' ';
head->x=a,head->y=b;
sit[a][b]='*';
if(head->ne)//如果蛇头后面有子节点
bmove(head->ne,p,q,add);
if(add&&head->ne==NULL)//特判只有头节点的情况
head->ne=new snake(p,q);
}
}
void setp()//随机掉落苹果
{
int x=rand()%N+1,y=rand()%N+1;
sit[x][y]='@';
}
int main()
{
HideCursor();
srand(time(0));
while(flag)
{
print();
ctl=getch();
switch(ctl)
{
case 'w':
dir=0;
break;
case 's':
dir=1;
break;
case 'a':
dir=2;
break;
case 'd':
dir=3;
break;
}
hmove(&head,dir);
setp();
}
return 0;
}