贪吃蛇怎么写
2026-10-26 17:40:50
发布于:浙江
请回复
全部评论 4
#include <iostream> #include <windows.h> #include <conio.h> #include <vector> #include <cstdlib> #include <ctime> using namespace std; // 游戏配置常量 const int WIDTH = 40; const int HEIGHT = 20; const char SNAKE_HEAD = 'O'; const char SNAKE_BODY = 'o'; const char FOOD = '*'; const char WALL = '#'; const char EMPTY = ' '; // 方向枚举 enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 坐标结构体 struct Point { int x, y; }; class SnakeGame { private: bool gameOver; Direction dir; int score; vector<Point> snake; Point food; // 控制台光标定位 void gotoXY(int x, int y) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } // 隐藏光标 void hideCursor() { CONSOLE_CURSOR_INFO cursorInfo; cursorInfo.dwSize = 100; cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo); } // 生成食物 void generateFood() { bool validPosition = false; while (!validPosition) { food.x = rand() % (WIDTH - 2) + 1; food.y = rand() % (HEIGHT - 2) + 1; validPosition = true; // 确保食物不在蛇身上 for (const auto& segment : snake) { if (segment.x == food.x && segment.y == food.y) { validPosition = false; break; } } } } // 绘制界面 void draw() { system("cls"); // 绘制上边界 for (int i = 0; i < WIDTH + 2; i++) { cout << WALL; } cout << endl; // 绘制中间区域 for (int y = 0; y < HEIGHT; y++) { cout << WALL; // 左边界 for (int x = 0; x < WIDTH; x++) { bool isSnake = false; bool isHead = false; // 检查是否是蛇身 for (size_t i = 0; i < snake.size(); i++) {2026-10-30 来自 北京
3直接能运行的c++代码,测试了还不错
2026-10-30 来自 北京
3好的
2026-10-31 来自 浙江
2没放完好像……
2026-10-31 来自 北京
2
C++:
结构体:蛇头/蛇身,位置x,y,方向d;
每次清屏更新数组,输出;
按键改方向,食物生成在随机位置
2026-10-30 来自 云南
2OK!
2026-11-02 来自 浙江
2
和一位
2026-10-26 来自 上海
2
2026-10-26 来自 上海
2






























有帮助,赞一个