关于C++编写的贪吃蛇的问题
各位高手,我是新手,在编写贪吃蛇的过程中出现了很多的问题,运行得不到想要的结果。现把我的代码贴出来,希望大家能
够指出我的错误之处。非常感谢!
#include <iostream>
#include <ctime>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
#define N 100
enum dir{up,down,left,right}; //枚举类型enum dir;
class Snake
{ public:
void move();//移动
void getdirection(char a);//改变方向
void showsnake();
bool iseatbody(); //是否咬到自己的身体
void drawme();//显示
bool ishitground(); //是否碰到墙壁
bool iseatfood();//吃到食物否
private:
int x[N];
int y[N];
int length;//蛇长
};
class Ground
{
public :
void drawme();//显示墙壁
void setdrawme();//设置墙壁的长宽
public :
char game [20][30]; //设置墙壁的长宽
}ground;
class Food
{
public:
void getfood();//获得随机食物
int x;
int y;//食物的坐标
}food;
void Snake::move()
{ int i;
cout<<"Snake move"<<endl;
for(i=length-1;i>0;i--)/*蛇的每个环节往前移动,也就是贪吃蛇的关键算法*/
{
x[i]=x[i-1];
y[i]=y[i-1];
}
}
void Snake::getdirection(char a)
{
/*w,a,s,d表示上,下,左,右四个方向,通过这个判断来移动蛇头*/
switch(a)
{
case 'w':x[0]--;break;
case 's': x[0]++;break;
case 'a': y[0]--;break;
case 'd': y[0]++;break;
}
}
//显示蛇
void Snake::showsnake()
{ int i;
for (i=0;i<length;i++)
ground.game[x[i]][y[i]]='@';
}
bool Snake::iseatbody()
{
int i;
cout<<"Snake iseatbody"<<endl;
for(i=3;i<length;i++)/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来*/
{
if(x[i]==x[0]&&y[i]==y[0])
{
cout<<"Game over"<<endl;/*显示失败*/
return 0;
}
}
return 1;
}
void Snake::drawme()
{
cout<<"Snake drawme"<<endl;
x[0]=10;y[0]=10;/*蛇头*/
x[1]=11;y[1]=10;
length=2;/*节数*/
ground.game[x[0]][y[0]]='@';
ground.game[x[1]][y[1]]='@';
}
//是否碰到墙壁
bool Snake::ishitground()
{
cout<<"is Snake hitground ?"<<endl;
if(x[0]<0||x[0]>19||y[0]<0||y[0]>19)/*蛇是否撞到墙壁*/
{
cout<<"Game over"<<endl;/*本次游戏结束*/
return 0;
}
else return 1;
}
//是否吃到食物
bool Snake::iseatfood()
{
if (x[0]==food.x&&y[0]==food.y)
return 1;
else return 0;
}
//设置墙壁的长和宽
void Ground::setdrawme()
{ int i,j;
for( i=0; i<20; i++)
for( j=0; j<30; j++)
{
if(i==0||i==19||j==0||j==29)
game[i][j]= '*';
else game[i][j]= ' ';
}
}
//显示出墙壁
void Ground::drawme()
{ int i,j;
for( i=0; i<20; i++)
{
for(j=0; j<30; j++)
cout<<game[i][j]<<" ";
cout<<endl;
}
}
void Food::getfood ()
{
cout<<"Snake getfood "<<endl;
srand((unsigned int) time(NULL)); //做种子(程序运行时间);
x= rand()%18+1;
y= rand()%28+1;
ground.game[x][y]='*';
}
int main ()
{
Snake snake;
ground.setdrawme();
snake.drawme();
food.getfood();
ground.drawme();
while (true )
{
char a=getch();//getch()返回键盘上读取的字符;包含头文件<conio.h>
snake.getdirection(a);
while (!kbhit())//判断有没有按键落下;
{
system("cls");//清屏函数;
snake.move();
snake.showsnake();
ground.drawme();
if( snake.iseatfood()==1)
food.getfood();
else if( snake.iseatbody()==0)
exit (0);
else if (snake.ishitground()==0)
exit (0);
Sleep(2500);
}
}
// ground.drawme();
return 0;
}