C++写贪吃蛇源代码

源码如下:

#include <iostream>
#include <conio.h>
#include <vector>
#include <Windows.h>
#include <time.h>
#include <easyx.h>
using namespace std;

//节点的数据
struct node
{
	int x, y, r;
};
char dir = 's';//方向
vector<node> mv;//容器用来存数据的

node foodNode = { 0, 0, 10 };//食物节点
int x = 0;//分数
void initSnake()
{
	mv.push_back({ 30, 40, 10 });
	mv.push_back({ 50, 40, 10 });
	mv.push_back({ 70, 40, 10 });
}//把身体节点放入容器
void drawMap()
{
	for (auto& i : mv) //for循环的遍历容器的方式
	{
		circle(i.x, i.y, i.r);
	}
	circle(foodNode.x, foodNode.y, foodNode.r);
}
void move()
{
	for (int i = mv.size() - 1; i > 0; i--)
	{
		mv[i] = mv[i - 1];
	}
	//让蛇的身体跟着头移动
	switch (dir)
	{
	case 'w':
		mv[0].y -= 20;
		break;
	case 's':
		mv[0].y += 20;
		break;
	case 'a':
		mv[0].x -= 20;
		break;
	case 'd':
		mv[0].x += 20;
		break;
	}
}
void play()
{
	if (_kbhit())
		switch (_getch())
	{
		case 'w':
			if (dir != 's')
				dir = 'w';
			break;
		case 's':
			if (dir != 'w')
				dir = 's';
			break;
		case 'a':
			if (dir != 'd')
				dir = 'a';
			break;
		case 'd':
			if (dir != 'a')
				dir = 'd';
			break;
	}
}
bool crash(node n, int x, int y)
{
	int xx = abs(n.x - x);//abs求绝对值
	int yy = abs(n.y - y);
	return xx < 20 && yy < 20;
}
void initFood()
{
	int x, y;
	while (1)
	{
		x = rand() % 781 + 10;
		y = rand() % 781 + 10;
		for (auto& i : mv)
		{
			if (!crash(i, x, y))
				goto a;
		}
	}
a:
	foodNode.x = x;
	foodNode.y = y;
}
void eat()
{
	if (crash(mv[0], foodNode.x, foodNode.y))
	{
		mv.push_back(foodNode);
		initFood();
		x++;
	}
}
void loser()
{
	if (mv[0].x < 0 || mv[0].x>800 || mv[0].y < 0 || mv[0].y>800)
	{
		MessageBox(GetHWnd(), "游戏失败", "提示", MB_OK);
		getchar();
		exit(1);
	}
	for (int i = 1; i < mv.size(); i++)
	{
		if (crash(mv[0], mv[i].x, mv[i].y))
		{
			MessageBox(GetHWnd(), "游戏失败", "提示", MB_OK);
			getchar();
			exit(1);
		}
	}
}
int main()
{
	srand((unsigned)time(NULL));
	initgraph(800, 800);
	initSnake();
	char str[6] = { 0 };
	initFood();
	while (1)
	{
		sprintf(str, "%d", x);
		outtext(str);

		play();
		eat();
		move();
		loser();
		drawMap();
		Sleep(100);
		cleardevice();
	}
	system("pause");
	closegraph();
	return 0;
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浔汐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值