贪吃蛇 C++简易版(完整代码)

代码:

#include <iostream>
#include <conio.h>
#include <vector>
#include <windows.h>
#include <ctime>

using namespace std;
//设置范围
const int WIDTH = 20;
const int HEIGHT = 20;

const char EMPTY = ' ';
const char SNAKE = 'O';
const char FOOD = '*';

enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };

struct Position {
    int x, y;
};

class SnakeGame {
public:
    vector<Position> snake;
    Position food;
    Direction dir;
    bool gameOver;

    void SetupFood() {
        food.x = rand() % WIDTH;
        food.y = rand() % HEIGHT;

        // 确保食物不在蛇身上
        for (const auto& pos : snake) {
            if (pos.x == food.x && pos.y == food.y) {
                SetupFood(); // 递归确保食物位置有效
                break;
            }
        }
    }

    bool IsCollision(Position head) {
        // 检查撞墙
        if (head.x >= WIDTH || head.x < 0 || head.y >= HEIGHT || head.y < 0)
            return true;

        // 检查撞自己
        for (size_t i = 1; i < snake.size(); i++) {
            if (snake[i].x == head.x && snake[i].y == head.y)
                return true;
        }

        return false;
    }

public:
    SnakeGame() : dir(STOP), gameOver(false) {
        snake.push_back({WIDTH / 2, HEIGHT / 2}); // 初始化蛇头位置
        SetupFood(); // 初始化食物位置
    }

    void ChangeDirection(Direction newDir) {
        // 禁止反向移动
        if ((dir == LEFT && newDir == RIGHT) || (dir == RIGHT && newDir == LEFT) ||
            (dir == UP && newDir == DOWN) || (dir == DOWN && newDir == UP))
            return;

        dir = newDir;
    }

    void Move() {
        Position head = snake[0];
        Position newHead;

        switch (dir) {
            case LEFT: newHead = {head.x - 1, head.y}; break;
            case RIGHT: newHead = {head.x + 1, head.y}; break;
            case UP: newHead = {head.x, head.y - 1}; break;
            case DOWN: newHead = {head.x, head.y + 1}; break;
            default: return;
        }

        if (IsCollision(newHead)) {
            gameOver = true;
            return;
        }

        // 吃食物
        if (newHead.x == food.x && newHead.y == food.y) {
            SetupFood(); // 生成新食物
        } else {
            // 移动蛇身,去掉尾部
            //snake.erase(snake.begin());
            snake.pop_back();
        }

        // 添加新的头部
        snake.insert(snake.begin(), newHead);
        //snake.push_back(newHead);
    }

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

    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            bool isSnake = false;
            for (const auto& pos : snake) {
                if (pos.x == j && pos.y == i) {
                    cout << SNAKE;
                    isSnake = true;
                    break;
                }
            }

            if (!isSnake) {
                if (i == food.y && j == food.x)
                    cout << FOOD;
                else
                    cout << EMPTY;
            }

            // 每打印完一个字符后,如果不是最后一个字符,则打印空格
            if (j < WIDTH - 1)
                cout << " ";
        }
        cout << endl; // 每打印完一行后换行
    }
}
};
int main() {
    srand(time(0)); // 初始化随机数生成器
    SnakeGame game;

    while (!game.gameOver) {
        if (_kbhit()) { // 检查是否有键盘输入
            switch (_getch()) {
                case 'A': game.ChangeDirection(LEFT); break;
                case 'D': game.ChangeDirection(RIGHT); break;
                case 'W': game.ChangeDirection(UP); break;
                case 'S': game.ChangeDirection(DOWN); break;
            }
        }

        game.Move(); // 移动蛇
        game.Draw(); // 绘制游戏界面

        Sleep(200); // 等待一段时间,减少CPU占用并"控制游戏速度"
    }

    cout << "Game Over!" << endl;
    return 0;
}

C语言的贪吃蛇简易版通常使用基本的图形界面和控制台编程来实现。以下是一个简单的框架,包括基本的游戏逻辑和绘制部分。注意这只是一个基础版本,可能不包含所有高级功能,例如碰撞检测或游戏结束条件。 ```c #include <stdio.h> #include <conio.h> #include <windows.h> #define COLS 20 #define_ROWS 15 #define SNAKE_SPEED 5 #define FOOD_SIZE 3 #define SNAKE_LENGTH 5 typedef struct { int x, y; } Point; struct Snake { Point body[SNAKE_LENGTH]; int direction; }; void draw_snake(struct Snake snake) { for (int i = snake.body[snake.direction].y; i >= 0; i--) { for (int j = 0; j < COLS; j++) { if (i == snake.body[snake.direction].y && j == snake.body[snake.direction].x) { printf("O"); // 空白字符代表蛇的身体 } else { printf(" "); } } printf("\n"); } } void game_loop(struct Snake *snake) { while (1) { // 读取键盘输入并更新蛇的方向 char key = _getch(); switch (key) { case 'w': snake->direction = 0; break; case 's': snake->direction = 2; break; case 'a': snake->direction = 3; break; case 'd': snake->direction = 1; break; default: continue; } // 更新蛇的位置 snake->body[0].x += SNAKE_SPEED * (snake->direction % 2); snake->body.y += SNAKE_SPEED * (snake->direction / 2); // 碰撞检测和边界处理 // ... // 生成食物 // ... // 判断蛇是否吃到食物或撞到自己 // ... // 绘制游戏画面 draw_snake(*snake); // 暂停片刻 Sleep(100); } } int main() { struct Snake snake = {{COLS / 2, _ROWS / 2}, 0}; srand(time(NULL)); // 设置随机数种子 game_loop(&snake); return 0; }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草海桐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值