跳到正文

剪贴板

剪贴板 xsyrlht3

原文
剪贴板信息

剪贴板信息

收录
更新

贪吃蛇

可在这篇文章查看游戏说明

-std=c++11 !!!

C++
#include <iostream>
#include <vector>
#include <thread>
#include <conio.h>
#include <Windows.h>
#include <random>
#include <chrono>
#include <string>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <set>

const int width = 25; // 游戏画面宽度
const int height = 25; // 游戏画面高度

int x, y; // 蛇头坐标
int fruitX, fruitY; // 水果坐标
int score; // 得分
int health; // 血量
int tailX[100], tailY[100]; // 蛇身坐标数组
int nTail; // 蛇身长度
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 方向枚举
Direction dir;
bool gameOver;
std::mt19937 rd(std::chrono::system_clock::now().time_since_epoch().count());
std::string difficulty,high_score_string;
int speed,high_score;
std::ifstream fin;
std::ofstream fout;

struct Bomb {
    int x;
    int y;
};

bool operator <(Bomb tmp1,Bomb tmp2){
	if(tmp1.x != tmp2.x) return tmp1.x < tmp2.x;
	return tmp1.y < tmp2.y;
}

std::set<Bomb> bombs; // 炸弹数组

void Setup()
{
    gameOver = false;
    dir = STOP;
    x = width >> 1;
    y = height >> 1;
    fruitX = rd() % width;
    fruitY = rd() % height;
    score = 0;
    health = 3;
    nTail = 0;

    // 初始时只有一个炸弹
    bombs.insert({rd() % width, rd() % height});
}

void Draw()
{
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD cursorPos;
    cursorPos.X = 0;
    cursorPos.Y = 0;
    SetConsoleCursorPosition(console, cursorPos);

    for (int i = 0; i < width + 2; i++)
        std::cout << "#"; // 上边框
    std::cout << std::endl;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            if (j == 0)
                std::cout << "#"; // 左边框

            if (i == y && j == x)
                std::cout << "O"; // 蛇头
            else if (i == fruitY && j == fruitX)
                std::cout << "F"; // 水果
            else
            {
                bool printTail = false;
                for (int k = 0; k < nTail; k++)
                {
                    if (tailX[k] == j && tailY[k] == i)
                    {
                        std::cout << "o"; // 蛇身
                        printTail = true;
                    }
                }
                if (!printTail)
                {
                    bool printBomb = false;
                    for (const Bomb& bomb : bombs)
                    {
                        if (bomb.x == j && bomb.y == i)
                        {
                            std::cout << "B"; // 炸弹
                            printBomb = true;
                            break;
                        }
                    }
                    if (!printBomb)
                        std::cout << " ";
                }
            }

            if (j == width - 1)
                std::cout << "#"; // 右边框
        }
        std::cout << std::endl;
    }

    for (int i = 0; i < width + 2; i++)
        std::cout << "#"; // 下边框
    std::cout << std::endl;

    std::cout << "Score: " << score << " Health: " << health << " High Score:" << high_score << std::endl;

    CONSOLE_CURSOR_INFO cursorInfo;
    GetConsoleCursorInfo(console, &cursorInfo);
    cursorInfo.bVisible = false; // 隐藏光标
    SetConsoleCursorInfo(console, &cursorInfo);
}

void Input()
{
    if (_kbhit()) // 键盘输入检测
    {
        switch (_getch())
        {
        case 'a':
        case 'A':
            if (dir != RIGHT || nTail == 0) // 如果当前不是向右移动,则可以改变方向为向左
                dir = LEFT;
            break;
        case 'd':
        case 'D':
            if (dir != LEFT || nTail == 0) // 如果当前不是向左移动,则可以改变方向为向右
                dir = RIGHT;
            break;
        case 'w':
        case 'W':
            if (dir != DOWN || nTail == 0) // 如果当前不是向下移动,则可以改变方向为向上
                dir = UP;
            break;
        case 's':
        case 'S':
            if (dir != UP || nTail == 0) // 如果当前不是向上移动,则可以改变方向为向下
                dir = DOWN;
            break;
        case 'q':
        case 'Q':
            gameOver = true;
            break;
        case ' ':
			while(_getch() != ' ');
        }

    }
}

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 >= width)
        x = 0;
    else if (x < 0)
        x = width - 1;

    if (y >= height)
        y = 0;
    else if (y < 0)
        y = height - 1;

    // 检测碰撞
    for (int i = 1; i < nTail; i++) {
        if (tailX[i] == x && tailY[i] == y && nTail > 0) {
            // 蛇头碰到蛇身,减少血量并截断后面的蛇身
            health--;
            if (health <= 0) {
                gameOver = true;
            }
            while (nTail > i) {
                nTail--;
            }
        }
    }

    // 吃到水果
    if (x == fruitX && y == fruitY) {
        if(difficulty == "A") score += 10;
        else if(difficulty == "B") score += 15;
        else if(difficulty == "C") score += 25;
        else if(difficulty == "D") score += 40;
        fruitX = rd() % width;
        fruitY = rd() % height;
        nTail++;

        // 每吃到一个水果增加一个炸弹,但数量不能超过15个
        if (difficulty != "D" || bombs.size() < 15) {
        	Bomb &&tmp = {rd() % width, rd() % height};
        	while(tmp.x == x && tmp.y == y) tmp = {rd() % width, rd() % height};
            bombs.insert(tmp);
        }
    }

    // 碰到炸弹
    if (bombs.count({x,y})) {
        health--;
        if (health <= 0) {
            gameOver = true;
        }
		if(!gameOver) Sleep(200);
    }
}

void GameLoop()
{
    while (!gameOver)
    {
        Draw();
        Input();
        Logic();
        if(difficulty != "D") Sleep(speed); // 线程休眠
    }
}

void decrypt(){
	std::reverse(high_score_string.begin(),high_score_string.end());
	for(int i = 0;i < high_score_string.length();i++){
		if(i & 1) high_score_string[i] -= 13;
		else high_score_string[i] += 19;
	}
}

void encryption(){
	for(int i = 0;i < high_score_string.length();i++){
		if(i & 1) high_score_string[i] += 13;
		else high_score_string[i] -= 19;
	}
	std::reverse(high_score_string.begin(),high_score_string.end());
}

int main()
{
	fin.open("high_score.txt");
	fin >> high_score_string;
	try{
		if(!high_score_string.empty()){
			decrypt();
			high_score = stoi(high_score_string);
		}
	} catch(...){
		std::cout << "最高分不合法,无法读入" << std::endl;
		system("pause");
		system("cls");
		goto aim2;
	}
	fin >> high_score_string;
	if(!(all_of(high_score_string.begin(),high_score_string.end(),
		[](char c){
			return c == '.';
		}
	) && count(high_score_string.begin(),high_score_string.end(),'.') == high_score)){
		std::cout << "最高分不合法,无法读入" << std::endl;
		system("pause");
		system("cls");
		high_score = 0;
	}
	aim2:
	fin.close();
	std::cout << "请选择游戏难度:\nA.easy    B.middling    C.hard    D.impossible" << std::endl;
	aim:
	std::cin >> difficulty;
	if(difficulty.length() != 1) goto aim;
	difficulty[0] = toupper(difficulty[0]);
	if(difficulty == "A") speed = 55;
	else if(difficulty == "B") speed = 30;
	else if(difficulty == "C") speed = 15;
	else if(difficulty == "D") speed = 5;
	else{
		std::cout << "输入不合法,请重新输入:" << std::endl;
		goto aim;
	}
	system("cls");

    Setup();

    std::thread gameThread(GameLoop); // 创建游戏线程

    gameThread.join(); // 等待游戏线程结束
    high_score = std::max(high_score,score);
    high_score_string = std::to_string(high_score);
    encryption();
    fout.open("high_score.txt");
    fout << high_score_string << '\n';
    for(int i = rd()%23;i;i--){
    	for(int j = rd()%31;j;j--){
    		fout << ' ';
		}
		fout << '\n';
	}
    while(high_score--){
    	fout << '.';
	}
    fout.close();

    // output log
    fout.open("snake log.txt");
    fout << "bombs pos:\n";
    for(auto i : bombs){
    	fout << i.x << ' ' << i.y << '\n';
	}
	fout << "The length of the snake when it died: " << nTail;
	fout.close();
    system("pause");

    return 0;
}

修改时间:2024.8.7 11:24

update:

2024.8.7 将炸弹碰撞的判断从 O(n)O(n) 优化成 O(logn)O(log n)

您是第Counter位访问本页面的人