c++贪吃蛇游戏代码

include

include <conio.h>

include <windows.h>

include

include

using namespace std;

const int WIDTH = 20;
const int HEIGHT = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
bool gameOver;

void Setup() {
gameOver = false;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
nTail = 0; // 初始化蛇尾长度
}

void Draw() {
system("cls"); // 清屏

// 绘制上边界
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 == y && j == x)
            cout << "#"; // 蛇头改为小正方形
        else if (i == fruitY && j == fruitX)
            cout << "."; // 食物改为小圆点
        else {
            bool printTail = false;
            for (int k = 0; k < nTail; k++) {
                if (tailX[k] == j && tailY[k] == i) {
                    cout << "#"; // 蛇身改为小正方形
                    printTail = true;
                }
            }
            if (!printTail)
                cout << " ";
        }

        if (j == WIDTH - 1)
            cout << "#"; // 右边界
    }
    cout << endl;
}

// 绘制下边界
for (int i = 0; i < WIDTH + 2; i++)
    cout << "#";
cout << endl;

cout << "分数:" << score << endl;

}

void Input() {
if (_kbhit()) {
switch (_getch()) {
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':
case 'X':
gameOver = true;
break;
}
}
}

void Logic() {
// 保存蛇尾位置
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;

// 移动蛇尾
for (int i = 1; i < nTail; i++) {
    prev2X = tailX[i];
    prev2Y = tailY[i];
    tailX[i] = prevX;
    tailY[i] = prevY;
    prevX = prev2X;
    prevY = prev2Y;
}

// 移动蛇头
switch (dir) {
case LEFT:
    x--;
    break;
case RIGHT:
    x++;
    break;
case UP:
    y--;
    break;
case DOWN:
    y++;
    break;
}

// 碰撞检测
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
    gameOver = true;

// 咬到自己检测
for (int i = 0; i < nTail; i++) {
    if (tailX[i] == x && tailY[i] == y)
        gameOver = true;
}

// 吃到食物
if (x == fruitX && y == fruitY) {
    score += 10;
    fruitX = rand() % WIDTH;
    fruitY = rand() % HEIGHT;
    nTail++;
}

}

int main() {
srand(static_cast(time(0)));
Setup();

while (!gameOver) {
    Draw();
    Input();
    Logic();
    Sleep(100); // 控制游戏速度
}

cout << "游戏结束! 最终分数: " << score << endl;
return 0;

}

posted @ 2025-10-12 17:45  hjy35147873  阅读(2)  评论(0)    收藏  举报