问题标题: 分享个代码

0
0
已解决
姚宇轩
姚宇轩
资深守护
资深守护

#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

const int WIDTH = 20;
const int HEIGHT = 20;

int score = 0;
bool gameOver = false;

struct Point {
    int x, y;
};

Point snake[100];
int length = 1;
Point food;
char dir = 'd';

void setup() {
    srand(time(0));
    snake[0] = {WIDTH/2, HEIGHT/2};
    food.x = rand() % WIDTH;
    food.y = rand() % HEIGHT;
}

void draw() {
    system("cls");
    
    // 绘制上边框
    for (int i = 0; i < WIDTH+2; i++)
        cout << "#";
    cout << endl;
    
    for (int y = 0; y < HEIGHT; y++) {
        cout << "#";
        for (int x = 0; x < WIDTH; x++) {
            if (x == food.x && y == food.y)
                cout << "F";
            else if (x == snake[0].x && y == snake[0].y)
                cout << "O";
            else {
                bool isBody = false;
                for (int k = 1; k < length; k++) {
                    if (snake[k].x == x && snake[k].y == y) {
                        cout << "o";
                        isBody = true;
                        break;
                    }
                }
                if (!isBody) cout << " ";
            }
        }
        cout << "#" << endl;
    }
    
    // 绘制下边框
    for (int i = 0; i < WIDTH+2; i++)
        cout << "#";
    cout << endl;
    
    cout << "分数: " << score << endl;
    cout << "WASD 控制方向,X 退出" << endl;
}

void input() {
    if (_kbhit()) {
        char key = _getch();
        key = tolower(key);
        if ((key == 'w' && dir != 's') || 
            (key == 's' && dir != 'w') || 
            (key == 'a' && dir != 'd') || 
            (key == 'd' && dir != 'a'))
            dir = key;
        if (key == 'x') gameOver = true;
    }
}

void logic() {
    // 移动身体
    for (int i = length-1; i > 0; i--) {
        snake[i] = snake[i-1];
    }
    
    // 移动头部
    switch(dir) {
        case 'w': snake[0].y--; break;
        case 's': snake[0].y++; break;
        case 'a': snake[0].x--; break;
        case 'd': snake[0].x++; break;
    }
    
    // 边界检测
    if (snake[0].x < 0 || snake[0].x >= WIDTH || 
        snake[0].y < 0 || snake[0].y >= HEIGHT)
        gameOver = true;
    
    // 吃到食物
    if (snake[0].x == food.x && snake[0].y == food.y) {
        score += 10;
        food.x = rand() % WIDTH;
        food.y = rand() % HEIGHT;
        length++;
    }
    
    // 碰撞检测
    for (int i = 1; i < length; i++) {
        if (snake[0].x == snake[i].x && snake[0].y == snake[i].y)
            gameOver = true;
    }
}

int main() {
    setup();
    while (!gameOver) {
        draw();
        input();
        logic();
        Sleep(200);
    }
    
    system("cls");
    cout << "游戏结束!" << endl;
    cout << "最终分数: " << score << endl;
    return 0;
}


0
0
我要回答