写一个贪吃蛇的程序
#include <iostream>
#include <list>
#include <ctime>
using namespace std;
const int width = 20; // 地图宽度
const int height = 20; // 地图高度
int map[height][width]; // 地图,0表示空地,1表示蛇身,2表示食物
int dir = 0; // 蛇运动方向,0-上 1-右 2-下 3-左
// 这里使用list来存储蛇的位置坐标,每个元素是一个pair<int, int>
list<pair<int, int>> snake_body;
// 随机生成食物
void create_food() {
// 无法生成食物时退出函数
if (snake_body.size() == width * height) { return; }
while (true) {
int x = rand() % width; // 生成随机x坐标
int y = rand() % height; // 生成随机y坐标
bool flag = true; // 标志位:能否创建食物
for (auto body : snake_body) { // 遍历蛇的每一部分
if (body.first == x && body.second == y) { // 判断是否在蛇身上
flag = false; break; // 是的话将flag置false退出循环
} else if (map[y][x] == 2) { // 判断是否已存在食物
flag = false; break; // 是的话将flag置false退出循环
} else {} // 不是的话什么都不做 continue循环即可
} if (flag) { map[y][x] = 2 ; break;} } return ;} void init_map(){ for(int i=0 ; i<height ; i++){for(int j=0 ; j<width ; j++){map[i][j] = 0;} }} void init_snake(){pair<int, int> head , tail1 , tail2 , tail3 ;head.first=5 ; head.second=5 ;tail1.first=4 ; tail1.second=5 ;tail2.first=3 ; tail2.second=5 ;tail3.first=2 ; tail3.second=5 ;;snake_body . push_back(head);snake_body . push_back(tail1);snake_body . push_back(tail2);snake_body . push
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。