C++控制台贪吃蛇

软件实训作品, 现放出个人源代码, 供需要的同学参考

运行效果

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

#include <iostream>
#include <list>
#include <cstdio>
#include <string>
#include <vector>
#include <ctime>
#include <algorithm>
#include <conio.h>
#include <windows.h>
using namespace std;

class Node { //蛇身坐标结点
public:
    int x, y;
    Node(int x1, int y1); //构造Node对象
};

class UserData { //用户资料
public:
    string name;
    int score;
    UserData(string s, int sc); //构造UserData对象
    friend bool operator < (UserData a, UserData b); //重载运算符,按分数由大到小排列
};

#define RIGHT 0x4d
#define LEFT 0x4b  
#define UP 0x48  
#define DOWN 0x50 
#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY
#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY
#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY

const int STARTX = 8; //X起点
const int STARTY = 4; //Y起点
const int RANGEX = 60; //X范围
const int RANGEY = 20; //Y范围
const int ENDX = STARTX + RANGEX; //X终点
const int ENDY = STARTY + RANGEY; //Y终点

bool isSnake[RANGEY + 10 ][RANGEX + 10]; //标记蛇身
int speed; //休眠时间,控制蛇前进速度; 值越小, 蛇越快
list<Node> snake; //蛇身位置结点
int curDiraction; //蛇的当前前进方向, 1上, 2下, 3左, 4右
int score; //当前分数
int snakeLen; //蛇的长度
int foodx, foody; //食物坐标
int gox, goy; //蛇头坐标

void GoTo(int x, int y); //定位光标
void DrawBoard(); //绘制边框
void ShowInformation(); //展示游戏信息
void Init(); //初始化游戏
void RunSnake(int x, int y); //绘制蛇身
void Try(int& x, int& y); //试走
bool IsGoodCoord(int x, int y); //前进坐标是否合法
void AddFood(); //增加食物
void EartFood(); //吃食物
void InitSnake(); //初始化蛇身
bool EndGame(); //结束游戏
bool StartGame(); //启动游戏
bool GameMenu(); //游戏菜单
void ShowRanking(); //排行榜
void ShowAbout(); //相关信息
void InputData(); //输入玩家名字

int main() {
    while (true) {
        if (!GameMenu()) return 0;
    }
    return 0;
}

Node::Node(int x1, int y1) { //构造Node对象
    x = x1; y = y1; 
}

bool operator < (UserData a, UserData b) { //重载运算符,按分数由大到小排列
    return a.score > b.score;
}

UserData::UserData(string s, int sc) { //构造UserData对象
    name = s; score = sc;
}

void GoTo(int x, int y) { //定位光标
    COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void ShowInformation() { //输出游戏信息
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    GoTo(78, 5);
    printf("贪吃蛇游戏");
    GoTo(78, 8);
    printf("游戏规则:");
    GoTo(78, 10);
    printf("请按 ↑ ↓ ← →  来控制您的蛇吃东西");
    GoTo(78, 12);
    printf("吃的越多,蛇就越长,您的等级也将越高");
    GoTo(78, 14);
    printf("当蛇吃到自己或撞上墙时,游戏结束。");
    GoTo(78, 20);
    printf("当前等级: %8d", snakeLen - 3);
    GoTo(78, 23);
    printf("您的分数: %8d", score);
}

void DrawBoard() { //绘制墙体

    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //获得输出句柄

    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; //光标信息
    SetConsoleCursorInfo(hOut, &cursor_info); //隐藏光标

    COORD size = { 120, 30 };
    SetConsoleScreenBufferSize(hOut, size); //重设缓冲区大小

    SMALL_RECT rc = { 0 , 0, 120, 30 };
    SetConsoleWindowInfo(hOut, true, &rc); //重设窗口大小

    SetConsoleTextAttribute(hOut, CYAN);

    for (int i = STARTX - 2; i <= ENDX + 2; i += 2) { //横向墙体
        GoTo(i, STARTY - 1);
        printf("■");
        GoTo(i, ENDY + 1);
        printf("■");
    }
    for (int i = STARTY - 1; i <= ENDY + 1; ++i) { //竖向墙体
        GoTo(STARTX - 2, i);
        printf("■");
        GoTo(ENDX + 2, i);
        printf("■");
    }
}

void Init() { //初始化游戏
    system("cls");
    memset(isSnake, 0, sizeof(isSnake));
    speed = 200;
    curDiraction = 4;
    score = 0;

    DrawBoard();
    InitSnake();
    ShowInformation();
    AddFood();
}

void RunSnake(int x, int y) { //绘制蛇身
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    score += snakeLen + 1;
    if (x == foodx && y == foody) {
        EartFood();
        return;
    }
    snake.push_front(Node(x, y));
    isSnake[y][x] = true;
    GoTo(x, y);
    printf("■");

    Node back = snake.back();
    snake.pop_back();
    isSnake[back.y][back.x] = false;
    GoTo(back.x, back.y);
    printf(" ");
}

void Try(int& x, int& y) { //试走
    int key, cnt = 100;
    while (cnt--) { //多次检测键盘状态
        if (_kbhit()) {
            key = getch();
            switch (key) {
            case UP: 
                if (curDiraction == 1 || curDiraction == 2) break;
                --y; curDiraction = 1; return;
            case DOWN: 
                if (curDiraction == 1 || curDiraction == 2) break;
                ++y; curDiraction = 2; return;
            case LEFT: 
                if (curDiraction == 3 || curDiraction == 4) break;
                x -= 2; curDiraction = 3; return;
            case RIGHT: 
                if (curDiraction == 3 || curDiraction == 4) break;
                x += 2; curDiraction = 4; return;
            }
        }
    }
    if (curDiraction == 1) --y; //用户没有输入时
    else if (curDiraction == 2) ++y;
    else if (curDiraction == 3) x -= 2;
    else x += 2;
}

bool IsGoodCoord(int x, int y) { //判断光标是否合法
    if (x <= ENDX && y <= ENDY && x >= STARTX && y >= STARTY)
        return true;
    else
        return false;
}

void AddFood() { //增加食物
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);
    srand((unsigned)time(NULL));
    while (true) {
        foodx = (rand()%ENDX) + 1;
        foody = (rand()%ENDY) + 1;
        if (foodx&1) foodx++;
        if (!isSnake[foody][foodx] && IsGoodCoord(foodx, foody)) break;
    }
    GoTo(foodx, foody);
    printf("★");
}

void EartFood() { //吃东西
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    snake.push_front(Node(foodx, foody));
    isSnake[foody][foodx] = true;
    ++snakeLen;
    if (speed >= 20) speed -= 10;

    GoTo(foodx, foody);
    printf("■");

    AddFood();
}

void InitSnake() { //初始化蛇身
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    snakeLen = 3, gox = 18, goy = 14;
    snake.clear();
    snake.push_front(Node(12, 14));
    snake.push_front(Node(14, 14));
    snake.push_front(Node(16, 14));
    for (int i = 12; i <= 16; i += 2) {
        GoTo(i, 14);
        printf("■");
        isSnake[14][i] = true;
    }
}
bool EndGame() { //结束游戏
    system("cls");
    DrawBoard();
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    GoTo(28, 10);
    printf("您的本局游戏得分: %d分", score);
    GoTo(32, 18);
    printf("...游戏结束...");
    GoTo(27, 20);
    printf("是否继续游戏: 是(1), 否(0)");
    GoTo(27, 22);
    char key = getch();
    while (true) {
        if (key == '1') return false;
        else if (key == '0') return true;
        else key = getch();
    }
}

bool StartGame() { //启动游戏

    Init();

    while (IsGoodCoord(gox, goy) && !isSnake[goy][gox]) { //当试走合法时
        RunSnake(gox, goy);
        ShowInformation();
        Try(gox, goy);
        Sleep(speed);
    }
    InputData();
    if (EndGame()) return false;
    return true;
}

bool GameMenu() { //游戏菜单
    system("cls");
    DrawBoard();
    GoTo(STARTX + 22, STARTY + 4);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);
    printf("欢迎进入贪吃蛇游戏!");
    GoTo(STARTX + 24, STARTY + 10);
    printf("1: 新游戏");
    GoTo(STARTX + 24, STARTY + 12);
    printf("2: 排行榜");
    GoTo(STARTX + 24, STARTY + 14);
    printf("3: 关于游戏");
    GoTo(STARTX + 24, STARTY + 16);
    printf("4: 退出游戏");

    while (true) {
        if (_kbhit()) {
            char key = getch();
            switch (key) {
            case '1':
                if (!StartGame()) return false; 
                else return true;
            case '2':
                ShowRanking(); return true;
            case '3':
                ShowAbout(); return true;
            case '4':
                return false;
            default:
                return true;
            }
        }
    }
}

void ShowRanking() { //展示排行榜
    vector<UserData> vu;
    FILE *fp = fopen("GameData.txt", "r");
    if (fp == NULL) fp = fopen("GameData.txt", "w+");
    char name[20];
    int len = 0;
    while (fscanf(fp, "%s", name) != EOF) {
        ++len;
        int score;
        fscanf(fp, "%d%*c", &score);
        vu.push_back(UserData(string(name), score));
    }
    fclose(fp);

    sort(vu.begin(), vu.end()); //对得分进行排名

    system("cls");
    DrawBoard();
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);
    GoTo(STARTX + 8, STARTY + 2);
    printf("用户");
    GoTo(STARTX + 28, STARTY + 2);
    printf("分数");
    GoTo(STARTX + 48, STARTY + 2);
    printf("排行");
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    for (int i = 0; i < len && i < 10; ++i) { //打印前十名用户数据
        char const *p = vu[i].name.c_str();
        GoTo(STARTX + 8, STARTY + 4 + i);
        printf("%s", p);
        GoTo(STARTX + 28, STARTY + 4 + i);
        printf("%d", vu[i].score);
        GoTo(STARTX + 48, STARTY + 4 + i);
        printf(" %d", i + 1);
    }

    GoTo(STARTX + 4, ENDY - 2);
    printf("-----------------  按'1'返回游戏菜单  ---------------");
    while (true) {
        if (_kbhit()) {
            char key = getch();
            if (key == '1') break;
        }
    }
}

void ShowAbout() { //展示游戏相关
    system("cls");
    DrawBoard();
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    GoTo(STARTX + 4, STARTY + 2);
    printf("-------------------  贪吃蛇游戏  -------------------");
    GoTo(STARTX + 10, STARTY + 5);
    printf("制作人: ");
    GoTo(STARTX + 10, STARTY + 7);
    printf("Night_13");

    GoTo(STARTX + 4, ENDY - 2);
    printf("-----------------  按'1'返回游戏菜单  ---------------");
    while (true) {
        if (_kbhit()) {
            char key = getch();
            if (key == '1') break;
        }
    }
}

void InputData() { //用户输入名字
    char name[20];
    GoTo(STARTX + 10, STARTY + 10);
    printf("请输入您的名字: ");
    COORD coord = { STARTX + 10, STARTY + 12 };
    SetConsoleCursorPosition(GetStdHandle(STD_INPUT_HANDLE), coord);
    while (true) { //忽略非法字符
        scanf("%s", name);
        if (name[0] != 0 && name[0] != ' ') break; 
    }

    FILE *fp = fopen("GameData.txt", "a");
    if (fp == NULL) fp = fopen("GameData.txt", "w+");
    fprintf(fp, "%s %d\n", name, score);
    fclose(fp);
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值