贪吃蛇 C++

#include<bits/stdc++.h>
#include <conio.h>
#include <windows.h>
using namespace std;
void gotoxy(int x,int y) //将输出位置改到 y行x列 
{
    CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
    HANDLE hConsoleOut;
    hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsoleOut,&csbiInfo);
    csbiInfo.dwCursorPosition.X = x;
    csbiInfo.dwCursorPosition.Y = y;
    SetConsoleCursorPosition(hConsoleOut,csbiInfo.dwCursorPosition);
}

pair<int,int> operator + (pair<int,int> a,pair<int,int> b)
{
    return make_pair(a.first+b.first,a.second+b.second);
}

struct _
{
    vector<pair<int,int>> v; //蛇身坐标
    pair<int,int> p,food,cur;//方向,食物,当前方向坐标
    int len,dif = 100; //长度,刷新速度

    void init() //初始化
    {
        p = make_pair(1,0);
        v.clear();
        for(int i = 2; i >= 0; i--)
            v.push_back(make_pair(i,0));
        L1:int x = rand()%80, y = rand()%20;
        food = make_pair(x,y);
        if(find(v.begin(),v.end(),food)!=v.end()) goto L1;
    }

    void print() //将蛇身,食物输入到屏幕
    {
        gotoxy(v[0].first,v[0].second);
        putchar('@');
        for(int i = 1; i < (int)v.size(); i++){
            gotoxy(v[i].first,v[i].second);
            putchar('O');
        }
        gotoxy(food.first,food.second);
        putchar('#');
        getkey();
    }

    void getkey() // 输入方向 
    {
        long long t = clock();
        cur = p;
        while(clock()-t < dif){
            if(_kbhit()) pd(_getch());
        }
        Move();
        system("cls");
        print();
    }

    void Move() // 移动
    {
        pair<int,int> t = v[0];
        v[0] = v[0]+p;
        v[0].first = (v[0].first+80)%80;v[0].second = (v[0].second+20)%20;
        if(find(v.begin()+1,v.end(),v[0]) != v.end()){
            gotoxy(32,10);puts("Game Over");
            gotoxy(30,11);puts("1、按 ESC 退出");
            gotoxy(30,12);puts("2、按任意键复活");
            if(_getch() == 27) exit(0);
            else {
                init();
                print();
            }
        }
        if(v[0] == food) {
            v.resize(v.size()+5);
            L1:int x = rand()%80, y = rand()%20;
            food = make_pair(x,y);
            if(find(v.begin(),v.end(),food)!=v.end()) goto L1;
        }
        for(int i = 1; i < (int)v.size(); i++){
            pair<int,int> tmp = v[i];
            v[i] = t;
            t = tmp;
        }
    }

    bool pd(int t) // 判断方向是否与当前方向相反
    {
        pair<int,int> x;
        if(t == 77) x = make_pair(-1,0);
        if(t == 75) x = make_pair(1,0);
        if(t == 72) x = make_pair(0,1);
        if(t == 80) x = make_pair(0,-1);
        if(cur != x){
            if(t == 77) p = make_pair(1,0);
            if(t == 75) p = make_pair(-1,0);
            if(t == 72) p = make_pair(0,-1);
            if(t == 80) p =make_pair(0,1);
            return true;
        }
        return false;
    }

}tcs;

int main()
{
    system("mode con: cols=80 lines=20");
    system("title 贪吃蛇");
    gotoxy(30,10);puts("按任意键开始...");_getch();
    tcs.init();
    tcs.print();
    return 0;
}

### 如何用C++编写贪吃蛇游戏 要实现一个基于控制台的贪吃蛇游戏,可以按照以下逻辑结构设计程序。以下是完整的解决方案: #### 游戏核心概念 1. **地图表示**:使用二维数组模拟游戏区域。 2. **蛇的身体**:通过坐标列表存储蛇的位置。 3. **食物生成**:随机生成食物位置并更新分数。 4. **移动机制**:根据键盘输入调整方向,并实时刷新屏幕。 --- #### 完整代码示例 以下是一个基础版本的C++贪吃蛇游戏代码: ```cpp #include <iostream> #include <conio.h> // 用于获取按键输入 #include <vector> #include <cstdlib> #include <ctime> using namespace std; // 定义常量 const int WIDTH = 20; const int HEIGHT = 15; // 初始化变量 int x, y; // 蛇头位置 int fruitX, fruitY;// 食物位置 bool gameOver; char direction = 'R'; // 初始向右 vector<pair<int, int>> snakeTail; // 存储蛇身部分 int score = 0; void Setup() { srand(time(0)); gameOver = false; x = WIDTH / 2; y = HEIGHT / 2; fruitX = rand() % WIDTH; fruitY = rand() % HEIGHT; } void Draw() { system("cls"); // 清屏 for (int i = 0; i < HEIGHT; ++i) { for (int j = 0; j < WIDTH; ++j) { if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) cout << "#"; // 边界墙 else if (i == y && j == x) cout << "O"; // 蛇头 else if (fruitX == j && fruitY == i) cout << "*"; // 食物 else { bool isPartOfSnake = false; for(auto &part : snakeTail){ if(part.first == j && part.second == i){ isPartOfSnake = true; break; } } if(isPartOfSnake) cout << "o"; // 蛇身 else cout << " "; // 空白处 } } cout << endl; } cout << "Score: " << score << endl; } void Input() { if (_kbhit()) { // 检测是否有键被按下 switch(_getch()){ case 'w': if(direction != 'S') direction = 'W'; break; case 's': if(direction != 'W') direction = 'S'; break; case 'a': if(direction != 'D') direction = 'A'; break; case 'd': if(direction != 'A') direction = 'D'; break; case 'q': gameOver = true; break; // 按Q退出 } } } void Logic() { pair<int, int> prevHead = make_pair(x, y); switch(direction){ case 'W': --y; break; case 'S': ++y; break; case 'A': --x; break; case 'D': ++x; break; } // 添加新的头部到尾巴 snakeTail.push_back(prevHead); // 如果吃到食物 if(x == fruitX && y == fruitY){ score += 10; fruitX = rand() % WIDTH; fruitY = rand() % HEIGHT; }else{ snakeTail.erase(snakeTail.begin()); // 移除最后一节尾巴 } // 检查碰撞 if(x >= WIDTH || x < 0 || y >= HEIGHT || y < 0){ gameOver = true; } for(auto &part : snakeTail){ if(part.first == x && part.second == y){ gameOver = true; } } } int main(){ Setup(); while(!gameOver){ Draw(); Input(); Logic(); } cout << "Game Over! Final Score: " << score << endl; return 0; } ``` --- #### 关于代码的关键说明 上述代码实现了以下几个主要功能: - 使用`_kbhit()`和`_getch()`处理即时键盘输入[^2]。 - 动态管理蛇体长度变化以及检测是否撞墙或自咬[^3]。 - 提供简单易懂的地图边界绘制方法[^1]。 此代码适用于Windows环境下的编译器(如Visual Studio),如果是在Linux/Mac上运行,则需替换清屏命令`system("clear")`替代`system("cls")`,同时可能需要安装额外库支持类似`ncurses`的功能来捕获按键事件。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值