C++贪吃蛇程序

方向控制表
dir direct[dir] 行进方向 可转的方向
0 {-1,0} 左右
1 {1,0} 左右
2 {0,-1} 上下
3 {0,1} 上下
#include   
#include   
#include   
#include   
#include   
#include   
#include   
using namespace std;
int s = 12, d = 12, Hard = 3 ,Dir; 
int Snake_len = 5;
int Direct[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
struct point
{
	int x,y;
} Snake[300];
point food;

/*** 光标定位 ***/
HANDLE Hout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD Coord;

/*** 实现光标的位置控制 ***/
void Locate(int x, int y)
{
	Coord.X = y;
	Coord.Y = x;
	SetConsoleCursorPosition(Hout, Coord); //
};

/*** 隐藏光标 ***/
void Hide()
{
	CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
	SetConsoleCursorInfo(Hout, &cursor_info);
}

void get_snake(){
	int i = 0;
	while (i=1 ; i--)
	{
		Snake[i] = Snake[i - 1];
	}
	Snake[0].x += Direct[Dir][0];
	Snake[0].y += Direct[Dir][1];
	Locate(Snake[1].x, Snake[1].y);
	cout << "*";
	//吃食
	if (Snake[0].x == food.x &&Snake[0].y == food.y)
	{
		Locate(food.x, food.y);
		cout << " ";
		Snake_len++;
		Snake[Snake_len - 1] = t;
		Food();
	}
	else
	{
		Locate(t.x, t.y);
		cout << " ";
	}
	Locate(Snake[0].x, Snake[0].y); 
	cout << "@"; //放在最后,因为头和食物重合后,会变成空白
}

bool alive()
{
	//撞墙
	if (Snake[0].x == 0 || Snake[0].x == s + 1 || Snake[0].y == 0  || Snake[0].y == d + 1)
	{
		Locate(s + 2, 0);
		cout << "撞墙了";
		return false;
	}
	//自撞
	for (int  i = Snake_len-1; i >0; i--)
	{
		if (Snake[0].x == Snake[i].x && Snake[0].y == Snake[i].y)
		{
			Locate(s + 2, 0);
			cout << "自撞了";
			return false;
		}
	}
	return true;
}
int main(){
	char ch,ch1;
	Dir = 3;
	Hide();
	wall(s, d);
	get_snake();
	Food();
	clock_t Start,now;

	while (1)
	{
		double delay = 400 - 30 * Hard;
		Start = clock();
		while (1)
		{
			now = clock();
			if (now - Start > delay) break;
		}
		if (_kbhit())   //上下左右 72,80,75,77
		{
			ch = _getch();
			if (ch == -32)
			{
				ch = _getch();
				switch (ch)
				{
					case 72:   //新方向
						if (Dir == 2 || Dir == 3)  //原方向 
							Dir = 0;
						break;
					case 80:
						if (Dir == 2 || Dir == 3)   
							Dir = 1;
						break;
					case 75:   
						if (Dir == 0 || Dir == 1)  
							Dir = 2;
						break;
					case 77:
						if (Dir == 0 || Dir == 1)   
							Dir = 3;
						break;
				}
			}
		}
		move();
		if (!alive()) break;
	}
	system("pause");
	return 0;
}
bug:如果新食物出现在蛇的身体上会消失,并且再也不出现食物  额

你可能感兴趣的:(兴趣编程)