全部评论 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++) {
           
    

    6天前 来自 北京

    3
  • C++:

    结构体:蛇头/蛇身,位置x,y,方向d;

    每次清屏更新数组,输出;

    按键改方向,食物生成在随机位置

    6天前 来自 云南

    2
  • 和一位

    1周前 来自 上海

    2

热门讨论