c++实现贪食蛇-LMLPHP今天老师布置了作业 让我们观察c++实现贪食蛇的代码

#include<windows.h>
#include<time.h>
#include<stdlib.h>
#include<conio.h>
#define N 21
#include<iostream>
using namespace std;
void gotoxy(int x,int y)//位置函数
{
COORD pos;
pos.X=*x;
pos.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
void color(int a)//颜色函数
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}
void init(int apple[])//初始化函数(初始化围墙、显示信息、苹果)
{
int i,j;//初始化围墙
int wall[N+][N+]={{}};
for(i=;i<=N;i++)
{
for(j=;j<=N;j++)
wall[i][j]=;
}
color();
for(i=;i<N+;i++)
{
for(j=;j<N+;j++)
{
if(wall[i][j])
cout<<"■";
else cout<<"□" ;
}
cout<<endl;
}
gotoxy(N+,);//显示信息
color();
cout<<"按 W S A D 移动方向"<<endl;
gotoxy(N+,);
color();
cout<<"按任意键暂停"<<endl;
gotoxy(N+,);
color();
cout<<"得分:"<<endl;
apple[]=rand()%N+;//苹果
apple[]=rand()%N+;
gotoxy(apple[],apple[]);
color();
cout<<"●"<<endl;
}
int main()
{
int i,j;
int** snake=NULL;
int apple[];
int score=;
int tail[];
int len=;
char ch='p';
srand((unsigned)time(NULL));
init(apple);
snake=(int**)realloc(snake,sizeof(int*)*len);
for(i=;i<len;i++)
snake[i]=(int*)malloc(sizeof(int)*);
for(i=;i<len;i++)
{
snake[i][]=N/;
snake[i][]=N/+i;
gotoxy(snake[i][],snake[i][]);
color();
cout<<"★"<<endl;
}
while()//进入消息循环
{
tail[]=snake[len-][];
tail[]=snake[len-][];
gotoxy(tail[],tail[]);
color();
cout<<"■"<<endl;
for(i=len-;i>;i--)
{
snake[i][]=snake[i-][];
snake[i][]=snake[i-][];
gotoxy(snake[i][],snake[i][]);
color();
cout<<"★"<<endl;
}
if(kbhit())
{
gotoxy(,N+);
ch=getche();
}
switch(ch)
{
case 'w':snake[][]--;break;
case 's':snake[][]++;break;
case 'a':snake[][]--;break;
case 'd':snake[][]++;break;
default: break;
}
gotoxy(snake[][],snake[][]);
color();
cout<<"★"<<endl;
Sleep(abs(-0.5*score));
if(snake[][]==apple[]&&snake[][]==apple[])//吃掉苹果后蛇分数加1,蛇长加1
{
score++;
len++;
snake=(int**)realloc(snake,sizeof(int*)*len);
snake[len-]=(int*)malloc(sizeof(int)*);
apple[]=rand()%N+;
apple[]=rand()%N+;
gotoxy(apple[],apple[]);
color();
cout<<"●"<<endl;
gotoxy(N+,);
color();
cout<<score<<endl;
}
if(snake[][]==||snake[][]==N||snake[][]==||snake[][]==N)//撞到围墙后失败
{
gotoxy(N/,N/);
color();
cout<<"失败!!!"<<endl;
for(i=;i<len;i++)
free(snake[i]);
Sleep(INFINITE);
exit();
}
}
return ;
}

代码运行截图:

c++实现贪食蛇-LMLPHP

c++实现贪食蛇-LMLPHP

05-11 17:39