栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

手把手教你写贪吃蛇(C++版)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手把手教你写贪吃蛇(C++版)

要求

我们的贪吃蛇有以下要求

1.有一条蛇

2.有可以生成的豆子

3.蛇可以移动

4.蛇吃了豆子后会变长一个字符

思路

我们用一个数组来记录蛇身体每个字符的位置,用x和y来记录蛇头的坐标,用string数组来存放地图,然后用随机函数随机生成豆子的坐标,每当蛇吃到豆子时,我们要进行特判,vector要增加一位来放新加的一个字符的长度的蛇身,豆子就会随机生成在地图的一个地方,如果生成在蛇的身体上就再生成一次。

直接上代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
string maze[40]; 
struct node{
	int x;
	int y;
}a[1600];
int len = 1;
int main() {
	srand((int)time(NULL));
	for (int i = 0; i < 40; i++) {
		maze[i] = "........................................";
	}
	int x = 0, y = 0;
	a[0].x = 0;
	a[0].y = 0;
	int px , py;
	px = 3;
	py = 3;
	maze[px][py] = '#';
	system("cls");
	maze[0][0] = 'O';
	for (int i = 0; i < 40; i++) {
		cout << maze[i] << endl;
	}
	while (1) {
		char ch = getch();
		if (ch == 'w') {
			if (maze[x - 1][y] == '#') {
				x--;
				a[len].x = x;
				a[len++].y = y;
				px = rand() % 40;
				py = rand() % 40;
				maze[px][py] = '#';
			} else {
				x--;
				a[len].x = x;
				a[len++].y = y;
				for (int i = 1; i < len; i++) {
					a[i - 1] = a[i];
				}
				a[len - 1] = {0, 0};
				len--;
			}
		} else if (ch == 'a') {
			if (maze[x][y - 1] == '#') {
				y--;
				a[len].x = x;
				a[len++].y = y;
				px = rand() % 40;
				py = rand() % 40;
				maze[px][py] = '#';
			} else {
				y--;
				a[len].x = x;
				a[len++].y = y;
				for (int i = 1; i < len; i++) {
					a[i - 1] = a[i];
				}
				a[len - 1] = {0, 0};
				len--;
			}
		} else if (ch == 'd') {
			if (maze[x][y + 1] == '#') {
				y++;
				a[len].x = x;
				a[len++].y = y;
				px = rand() % 40;
				py = rand() % 40;
				maze[px][py] = '#';
			} else {
				y++;
				a[len].x = x;
				a[len++].y = y;
				for (int i = 1; i < len; i++) {
					a[i - 1] = a[i];
				}
				a[len - 1] = {0, 0};
				len--;
			}
		} else if (ch == 's') {
			if (maze[x + 1][y] == '#') {
				x++;
				a[len].x = x;
				a[len++].y = y;
				px = rand() % 40;
				py = rand() % 40;
				maze[px][py] = '#';
			} else {
				x++;
				a[len].x = x;
				a[len++].y = y;
				for (int i = 1; i < len; i++) {
					a[i - 1] = a[i];
				}
				a[len - 1] = {0, 0};
				len--;
			}
		} 
		for (int i = 0; i < 40; i++) {
			maze[i] = "........................................";
		}
		maze[px][py] = '#';
		for (int i = 0; i < len; i++) {
			maze[a[i].x][a[i].y] = 'O';
		}
		system("cls");
		for (int i = 0; i < 40; i++) {
			cout << maze[i] << endl;
		}
	}
	return 0;
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001928.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号