C++贪吃蛇源代码

转自:http://blog.csdn.net/hp_justdoit/article/details/8456000

#include<iostream>
#include<windows.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>

using namespace std;

const int N=21;      //N为蛇所能移动的正方形的边长

void Get_xy(int x,int y)   //定位光标位置
{
	HANDLE hout;
	COORD pos;
	pos.X=x*2;
	pos.Y=y;
	hout=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(hout,pos);
}

void Color(int num)   //设置颜色
{
	HANDLE hout;
	hout=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(hout,num);
}

void Initial()   //初始化
{
	int i,j;
	int wall[N+2][N+2]={{0}};
	for(i=1;i<=N;i++)
		for(j=1;j<=N;j++)
			wall[i][j]=1;
	Color(11);
	for(i=0;i<N+2;i++)
	{
		for(j=0;j<N+2;j++)
		{
			if(wall[i][j])
				cout<<"■";
			else cout<<"□";
		}
		cout<<endl;
	}
	Get_xy(N+3,1); Color(20);
	cout<<"按'W','S','A','D'进行操作"<<endl;
	Get_xy(N+3,2); Color(20);
	cout<<"按任意键暂停"<<endl;
	Get_xy(N+3,3); Color(20);
	cout<<"得分:"<<endl;
}

void game()
{
	int** snake=NULL;   //snake为存储蛇身的每一点的位置的数组
	int len=1;
	int i;
	int score=0;
	int apple[2];
	int tail[2];
	char ch='p';

	Initial();
	
	//获得一个随机的食物位置
	srand((unsigned)time(NULL));
	apple[0]=rand()%N+1;
	apple[1]=rand()%N+1;      

	Get_xy(apple[0],apple[1]);
	Color(12);
	cout<<"●"<<endl;
	
	//给snake数组分配内存空间
	snake=(int**)realloc(snake,sizeof(int*)*len);
	for(i=0;i<len;i++)
		snake[i]=(int*)malloc(sizeof(int)*2);
	
	//开始将蛇置于页面正中间
	snake[0][0]=N/2; 
	snake[0][1]=N/2+1; 
	Get_xy(snake[0][0],snake[0][1]); Color(14);
	cout<<"⊙"<<endl;

	int flag=1;   //

	while(1)
	{
		//每移动一次,就把上次的尾巴还原为背景色
		if(flag)
		{
		tail[0]=snake[len-1][0];
        tail[1]=snake[len-1][1];
        Get_xy(tail[0],tail[1]);
        Color(11);
        cout<<"■"<<endl;
		}
		
		flag=1;
		for(i=len-1;i>0;i--)
		{
			snake[i][0]=snake[i-1][0];
			snake[i][1]=snake[i-1][1];
			Get_xy(snake[i][0],snake[i][1]);
			Color(14);
			cout<<"★"<<endl;
		}
		/*====================================================================
		函数名:kbhit()(VC++6.0下为_kbhit())
		功 能及返回值: 检查当前是否有键盘输入,若有则返回一个非0值,否则返回0
		用 法:int kbhit(void);
		包含头文件: include <conio.h>

		=====================================================================*/
		if(kbhit())
		{
			Get_xy(0,N+3);
			ch=getche();
		}
		switch(ch)
		{
		case 'W':
		case 'w': snake[0][1]--; break;
		case 'S':
		case 's': snake[0][1]++; break;
		case 'A':
		case 'a': snake[0][0]--; break;
		case 'D':
		case 'd': snake[0][0]++; break;
		default :break;
		} 

		for(i=1;i<len;i++)
		{
			//蛇咬到蛇身,游戏结束!
			if(snake[0][0]==snake[i][0] && snake[0][1]==snake[i][1])
			{
				Get_xy(N/2,N/2); Color(30);
				cout<<"Game over!"<<endl;
				exit(0);
			}
		}

		Get_xy(snake[0][0],snake[0][1]);
		Color(14); cout<<"⊙"<<endl;

		/*==================================================================
		函数名: sleep
		功 能: 执行挂起一段时间
		用 法: unsigned sleep(unsigned milliseconds);
		在VC中使用带上头文件
		#include <windows.h>
		在gcc编译器中,使用的头文件因gcc版本的不同而不同
		#include <unistd.h>

		===================================================================*/
		//分数越高,蛇的移动速度越快
		Sleep(abs(200-0.5*score));

		//蛇吃到食物
		if(snake[0][0]==apple[0] && snake[0][1]==apple[1])
		{
			flag=0; score++; len++;   srand((unsigned)time(NULL));
			snake=(int**)realloc(snake,sizeof(int*)*len);
			snake[len-1]=(int*)malloc(sizeof(int)*2);
			Get_xy(N+6,3); Color(20); cout<<score<<endl;
			apple[0]=rand()%N+1; apple[1]=rand()%N+1;
			Get_xy(apple[0],apple[1]);
			Color(12);
			cout<<"●"<<endl;
		}
		//蛇头撞墙了,游戏结束!
		if(snake[0][0]==0 || snake[0][0]==N || snake[0][1]==0 || snake[0][1]==N)
		{
			Get_xy(N/2,N/2); Color(30);
			cout<<"Game Over!"<<endl;
			for(i=0;i<len;i++)
				free(snake[i]);
			Sleep(INFINITE);
			exit(0);
		}
		//游戏通关!
		if(len>=N*N/20) 
		{
			Get_xy(N/2,N/2); Color(30);
			cout<<"Win!"<<endl;
			for(i=0;i<len;i++)
				free(snake[i]);
			Sleep(INFINITE);
			exit(0);
		}
	}
	
}
int main()
{
	game();
	return 0;
}


 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的贪吃蛇游戏的C++源代码,你可以根据自己的需要进行修改和优化。 ```c++ #include<iostream> #include<conio.h> #include<windows.h> using namespace std; bool gameover; //游戏结束标志 const int width = 20; //游戏区域宽度 const int height = 20; //游戏区域高度 int x, y, fruitX, fruitY, score; //蛇头坐标,果实坐标,得分 int tailX[100], tailY[100]; //蛇的身体坐标 int nTail; //蛇的长度 enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN}; //定义枚举类型,控制蛇的移动方向 eDirection dir; //蛇的移动方向 void Setup() //初始化游戏 { gameover = false; //游戏未结束 dir = STOP; //初始方向为静止 x = width / 2; //蛇头初始位置 y = height / 2; fruitX = rand() % width; //果实初始位置 fruitY = rand() % height; score = 0; //得分初始化为0 } void Draw() //绘制游戏界面 { system("cls"); //清屏 for (int i = 0; i < width+2; i++) //绘制上边框 cout << "#"; cout << endl; for (int i = 0; i < height; i++) //绘制游戏区域 { for (int j = 0; j < width; j++) { if (j == 0) cout << "#"; if (i == y && j == x) //绘制蛇头 cout << "O"; else if (i == fruitY && j == fruitX) //绘制果实 cout << "F"; else { bool print = false; for (int k = 0; k < nTail; k++) //绘制蛇的身体 { if (tailX[k] == j && tailY[k] == i) { cout << "o"; print = true; } } if (!print) cout << " "; } if (j == width - 1) cout << "#"; } cout << endl; } for (int i = 0; i < width+2; i++) //绘制下边框 cout << "#"; cout << endl; cout << "Score:" << score << endl; //显示得分 } void Input() //获取用户输入 { if (_kbhit()) //如果有按键按下 { switch (_getch()) //获取用户按下的键 { case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameover = true; break; } } } void Logic() //处理游戏逻辑 { int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; tailX[0] = x; tailY[0] = y; for (int i = 1; i < nTail; i++) //更新蛇的身体坐标 { prev2X = tailX[i]; prev2Y = tailY[i]; tailX[i] = prevX; tailY[i] = prevY; prevX = prev2X; prevY = prev2Y; } switch (dir) //根据移动方向更新蛇头坐标 { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; } if (x >= width) //检查是否越界 x = 0; else if (x < 0) x = width - 1; if (y >= height) y = 0; else if (y < 0) y = height - 1; for (int i = 0; i < nTail; i++) //检查是否碰到自己的身体 { if (tailX[i] == x && tailY[i] == y) gameover = true; } if (x == fruitX && y == fruitY) //检查是否吃到果实 { score += 10; fruitX = rand() % width; fruitY = rand() % height; nTail++; } } int main() { Setup(); //初始化游戏 while (!gameover) //循环执行游戏 { Draw(); //绘制游戏界面 Input(); //获取用户输入 Logic(); //处理游戏逻辑 Sleep(100); //暂停100毫秒,使蛇的移动速度变慢 } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值