我们的贪吃蛇有以下要求
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; }



