跳到正文

闲话

贪吃蛇

jjkim约 9 分钟
原文
文章信息与版本

文章信息

发布
2025年7月5日
收录
2026年8月3日
更新
2026年11月3日
篇幅
约 9 分钟

版本

  1. v1当前

代码有错,求大佬指点

C++
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
const int WIDTH = 30;
const int HEIGHT = 20;
const int MAX_TAIL = 500;
mutex inputMutex;
vector<char> keyQueue;
bool running = true;

enum Direction { STOP, LEFT, RIGHT, UP, DOWN };
enum FoodType { NORMAL, SPEED_UP, SPEED_DOWN };

struct Food {
    int x, y;
    FoodType type;
    char GetChar() const {
        return type == SPEED_UP ? 'U' :
            type == SPEED_DOWN ? 'D' : 'F';
    }
};

class SnakeGame {
private:
    HANDLE hConsole;
    int headX, headY;
    vector<pair<int, int>> tail;
    Direction dir;
    Food food;
    int score;
    int speed;
    bool gameOver;

    void GenerateFood() {
        food.x = rand() % WIDTH;
        food.y = rand() % HEIGHT;
        food.type = (rand() % 10 == 0) ?
            (rand() % 2 ? SPEED_UP : SPEED_DOWN) : NORMAL;
    }

public:
    SnakeGame() : hConsole(GetStdHandle(STD_OUTPUT_HANDLE)) {
        Setup();
    }

    void Setup() {
        gameOver = false;
        dir = STOP;
        headX = WIDTH / 2;
        headY = HEIGHT / 2;
        score = 0;
        speed = 150;
        tail.clear();
        GenerateFood();
    }

    void Draw() {
        COORD cursorPos = { 0, 0 };
        SetConsoleCursorPosition(hConsole, cursorPos);
        for (int i = 0; i < WIDTH + 2; i++) cout << "#";
        cout << endl;
        for (int i = 0; i < HEIGHT; i++) {
            for (int j = 0; j < WIDTH; j++) {
                if (j == 0) cout << "#";

                if (i == headY && j == headX) cout << "O";
                else if (i == food.y && j == food.x) cout << food.GetChar();
                else {
                    bool isTail = false;
                    for (auto& segment : tail) {
                        if (segment.first == j && segment.second == i) {
                            cout << "o";
                            isTail = true;
                            break;
                        }
                    }
                    if (!isTail) cout << " ";
                }

                if (j == WIDTH - 1) cout << "#";
            }
            cout << endl;
        }
        for (int i = 0; i < WIDTH + 2; i++) cout << "#";
        cout << endl;
        cout << "Score:" << score << " Speed:" << speed << "ms" << endl;
    }

    void ProcessInput() {
        lock_guard<mutex> lock(inputMutex);
        while (!keyQueue.empty()) {
            char key = keyQueue.back();
            keyQueue.pop_back();

            switch (key) {
            case 'a': if (dir != RIGHT) dir = LEFT; break;
            case 'd': if (dir != LEFT) dir = RIGHT; break;
            case 'w': if (dir != DOWN) dir = UP; break;
            case 's': if (dir != UP) dir = DOWN; break;
            case 'x': gameOver = true; break;
            case 'p':
                while (_getch() != 'p') {} 
                break;
            }
        }
    }

    void Update() {
        if (tail.size() == MAX_TAIL) tail.erase(tail.begin());
        tail.emplace_back(headX, headY);
        switch (dir) {
        case LEFT: headX--; break;
        case RIGHT: headX++; break;
        case UP: headY--; break;
        case DOWN: headY++; break;
        }
        if (headX >= WIDTH) headX = 0;
        else if (headX < 0) headX = WIDTH - 1;
        if (headY >= HEIGHT) headY = 0;
        else if (headY < 0) headY = HEIGHT - 1;
        for (auto& segment : tail) {
            if (segment.first == headX && segment.second == headY) {
                gameOver = true;
            }
        }
        if (headX == food.x && headY == food.y) {
            score += 10;
            if (food.type == SPEED_UP && speed > 50) speed -= 10;
            else if (food.type == SPEED_DOWN && speed < 300) speed += 20;
            GenerateFood();
        }
    }

    bool IsOver() const { return gameOver; }
    int GetSpeed() const { return speed; }
};

void InputThread() {
    while (running) {
        if (_kbhit()) {
            lock_guard<mutex> lock(inputMutex);
            keyQueue.push_back(_getch());
        }
        this_thread::sleep_for(chrono::milliseconds(10));
    }
}

int main() {
    system("mode con cols=60 lines=25");
    srand(static_cast<unsigned>(time(nullptr)));
    thread inputThread(InputThread);

    SnakeGame game;
    while (!game.IsOver()) {
        game.ProcessInput();
        game.Update();
        game.Draw();
        this_thread::sleep_for(chrono::milliseconds(game.GetSpeed()));
    }
    running = false;
    inputThread.join();
    cout << "Game Over! Final Score: " << game.GetScore() << endl;
    system("pause");
    return 0;
}
原文
存档评论1 条抓取于