开源软件:win10 devc++

注意事项:贪吃蛇要全屏玩,不然可能会闪;一些Windows版本要用管理员权限打开cpp文件才可以保存记录与创建文件。

用win11的版本,代码可能会出现bug,贪吃蛇与AI五子棋可能会出现字符不对位或字符重复打印的情况。迷宫困难模式生成时间比较久,请耐心等待,以上问题作者都还在改进中。

创作不易,您的点赞与收藏是我持续创作的动力

#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <climits>
#include <ctime>
#include <cstdlib>
#include <windows.h> 
#include<conio.h>
using namespace std;

//提前声明函数 
void menu();
void mine();
void w_fight();
void start();
void GenerateFood();
void drawBoard();
bool placeMark(int choice, char mark);
bool checkWin(char mark);
bool checkDraw();
void playerTurn();
void computerTurn();

// 棋盘大小和游戏常量
const int BOARD_SIZE = 15;
const int WIN_SCORE = 1000000;
int DEPTH; // 搜索深度

// 棋型评分权重
const int FIVE = 10000000;    // 连五
const int LIVE_FOUR = 300000; // 活四
const int FOUR = 100000;       // 冲四
const int LIVE_THREE = 10000;  // 活三
const int THREE = 500;       // 眠三
const int LIVE_TWO = 100;     // 活二
const int TWO = 50;           // 眠二

// 置换表条目结构体
struct TranspositionTableEntry {
    unsigned long long key;
    int depth;
    int score;
    int flag; // 0:精确, 1:下界, 2:上界
};

// 五子棋AI全局变量
int currentPlayer;
int board[BOARD_SIZE][BOARD_SIZE]; // 棋盘状态
unsigned long long zobristTable[BOARD_SIZE][BOARD_SIZE][3]; // Zobrist哈希表
unsigned long long zobristKey = 0; // 当前哈希键
map<unsigned long long, TranspositionTableEntry> transTable; // 置换表
string username,password;

//迷宫全局变量
bool MAP[51][51];
int wait_time = 2000000;
int size; 

//贪吃蛇全局变量
int s_bestscore=0;//也是系统变量
bool gameOver;
bool gamePaused;
const int width = 40;
const int height = 25;
int headX, headY;
int score;
vector<pair<int, int> > tail;
int tailLength;
int snakeSpeed;
enum FoodType { REGULAR, BONUS, SLOW, FAST, GOLD ,BOMB};
const int FOOD_TYPE_COUNT = 6;
struct Food {
    int x;
    int y;
    FoodType type;
    char symbol;
};
vector<Food> foods;
const int MAX_FOODS = 10;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
enum ConsoleColor {
    BLACK = 0,
    BLUE = 1,
    GREEN = 2,
    CYAN = 3,
    RED = 4,
    MAGENTA = 5,
    YELLOW = 6,
    WHITE = 7
};

//俄罗斯方块全局变量
int E_bestscore=0;
const int WIDTH = 10;
const int HEIGHT = 20;
const int SHAPES[7][4][4][4] = {
    {{{0,0,0,0}, {1,1,1,1}, {0,0,0,0}, {0,0,0,0}},
     {{0,0,1,0}, {0,0,1,0}, {0,0,1,0}, {0,0,1,0}},
     {{0,0,0,0}, {0,0,0,0}, {1,1,1,1}, {0,0,0,0}},
     {{0,1,0,0}, {0,1,0,0}, {0,1,0,0}, {0,1,0,0}}},
    {{{1,0,0,0}, {1,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,1,0}, {0,1,0,0}, {0,1,0,0}, {0,0,0,0}},
     {{0,0,0,0}, {1,1,1,0}, {0,0,1,0}, {0,0,0,0}},
     {{0,1,0,0}, {0,1,0,0}, {1,1,0,0}, {0,0,0,0}}},
    {{{0,0,1,0}, {1,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,0,0}, {0,1,0,0}, {0,1,1,0}, {0,0,0,0}},
     {{0,0,0,0}, {1,1,1,0}, {1,0,0,0}, {0,0,0,0}},
     {{1,1,0,0}, {0,1,0,0}, {0,1,0,0}, {0,0,0,0}}},
    {{{0,1,1,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,1,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,1,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,1,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}}},
    {{{0,1,1,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,0,0}, {0,1,1,0}, {0,0,1,0}, {0,0,0,0}},
     {{0,0,0,0}, {0,1,1,0}, {1,1,0,0}, {0,0,0,0}},
     {{1,0,0,0}, {1,1,0,0}, {0,1,0,0}, {0,0,0,0}}},
    {{{0,1,0,0}, {1,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,1,0,0}, {0,1,1,0}, {0,1,0,0}, {0,0,0,0}},
     {{0,0,0,0}, {1,1,1,0}, {0,1,0,0}, {0,0,0,0}},
     {{0,1,0,0}, {1,1,0,0}, {0,1,0,0}, {0,0,0,0}}},
    {{{1,1,0,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}},
     {{0,0,1,0}, {0,1,1,0}, {0,1,0,0}, {0,0,0,0}},
     {{0,0,0,0}, {1,1,0,0}, {0,1,1,0}, {0,0,0,0}},
     {{0,1,0,0}, {1,1,0,0}, {1,0,0,0}, {0,0,0,0}}}
}; 

//双人对打(hzq做)全局变量 
const int p_height=20;
const int p_width=20;
const int p_mostammo=700;
const int p_mostblood=20;
const int p_mostsammo=30;
int p_board[p_height+1][p_width+1];
struct p1{
    int x=1,y=1;
    int heart=0;
    int ammo=0;
    int sammo=0;
}player1;
struct p2{
    int x=p_height,y=p_width;
    int heart=0;
    int ammo=0;
    int sammo=0;
}player2;

//AI井字棋模板 
char Jboard[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}};

//打砖块全局变量
const int B_W = 50;
const int B_H = 25;
const int PADDLE_SIZE = 7;
const int BRICK_ROWS = 5;
const int BRICK_COLS = 10; 

//文件路径 
const string FILE_PATH="C:/user.txt";
const string M_PATH="C:/coin.txt";
const string S_PATH="C:/s_bestscore.txt";
const string E_PATH="C:/E_bestscore.txt";

//系统全局变量
map<string,string> userDatabase;
map<string,int> userCoins;
map<string,int> s_Bestscore;
map<string,int> E_Bestscore;
bool isLoggedIn=false;

//颜色函数 
int color(int x){
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x);
}

//贪吃蛇颜色函数
void SetColor(int textColor, int bgColor = BLACK) {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, (bgColor << 4) | textColor);
}

//贪吃蛇重置颜色到默认
void ResetColor() {
    SetColor(WHITE, BLACK);
}

//超快清屏函数
void fastcls() {
    static HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    static CONSOLE_CURSOR_INFO oldCursor;
    static bool firstRun = true;
    if(firstRun) {
        CONSOLE_CURSOR_INFO cursor = {100, FALSE};
        GetConsoleCursorInfo(hOut, &oldCursor);
        SetConsoleCursorInfo(hOut, &cursor);
        firstRun = false;
    }
    SetConsoleCursorPosition(hOut, COORD{0,0});
    for(int i=0; i<3; i++) { 
        WriteConsoleA(hOut, " \b", 2, NULL, NULL); 
    }
}

// 从文件读取用户信息1 
void loadUserData() {
    ifstream file(FILE_PATH.c_str());
    string tempUsername, tempPassword;
    if (file.is_open()) {
        while (file >> tempUsername >> tempPassword) {
            userDatabase[tempUsername] = tempPassword;
        }
        file.close();
    }
}

//从文件读取用户钱币数 
void loadUserMassage(){
    ifstream file(M_PATH.c_str());
    string tempUsername;
    int tempCoins;
    if(file.is_open()){
        while(file>>tempUsername>>tempCoins){
            userCoins[tempUsername]=tempCoins;
        }
        file.close();
    }
}

//从文件读取用户贪吃蛇最好成绩
void loadUser_s_Bestscore(){
    ifstream file(S_PATH.c_str());
    string tempUsername;
    int s_tempbestscore;
    if(file.is_open()){
        while(file>>tempUsername>>s_tempbestscore){
            s_Bestscore[tempUsername]=s_tempbestscore;
        }
        file.close();
    }
}

//从文件读取用户俄罗斯方块最好成绩
void loadUser_E_Bestscore(){
    ifstream file(E_PATH.c_str());
    string tempUsername;
    int E_tempbestscore;
    if(file.is_open()){
        while(file>>tempUsername>>E_tempbestscore){
            E_Bestscore[tempUsername]=E_tempbestscore;
        }
        file.close();
    }
}

// 注册用户
void registerUser() {
    system("cls");
    cout << "注册新用户:" << endl;
    cout << "请输入用户名(输入r返回): ";
    cin >> username;
    if(username=="r") menu();
    cout << "请输入密码: ";
    cin >> password;
    if(userDatabase[username]!=""){
        cout<<"已有这个用户,请换个用户名!";
        Sleep(1000);
        registerUser();
    }
    // 将新用户信息写入文件
    ofstream file(FILE_PATH.c_str(), ios_base::app);
    if (file.is_open()) {
        file << username << " " << password << endl;
        file.close();
        system("cls");
        cout << "注册成功!" << endl;
        Sleep(1000);
        system("cls");
    } else {
        cerr << "注册失败,运行错误!" << endl;
        exit(0);
    }
}

// 注册用户钱币数 
void RUmessage(){
    ofstream file(M_PATH.c_str(),ios_base::app);
    if(file.is_open()){
        file<<username<<" "<<0<<endl;
        file.close();
    }else{
        cerr << "记录失败,运行错误!" << endl;
        exit(0);
    }
}

//注册用户贪吃蛇最好成绩 
void RUSbestscore(){
    ofstream file(S_PATH.c_str(),ios_base::app);
    if(file.is_open()){
        file<<username<<" "<<0<<endl;
        file.close();
    }else{
        cerr << "记录失败,运行错误!" << endl;
        exit(0);
    }
}

//注册用户俄罗斯方块最好成绩 
void RUEbestscore(){
    ofstream file(E_PATH.c_str(),ios_base::app);
    if(file.is_open()){
        file<<username<<" "<<0<<endl;
        file.close();
    }else{
        cerr << "记录失败,运行错误!" << endl;
        exit(0);
    }
}

//登录太多直接关机好吧,兄弟们!
void c_login(){
    int elsetime=60;
    while(elsetime--){
        system("cls");
        cout<<"已锁住,剩余:"<<elsetime<<"秒!";
        Sleep(1000);
    }
}

// 登录验证
bool login() {
    int attempt = 0;
    while (attempt < 3) {
        cout << "登录:" << endl;
        cout << "请输入用户名(输入r返回): ";
        cin >> username;
        if(username=="r") menu();
        cout << "请输入密码: ";
        cin >> password;
        if (userDatabase.find(username) != userDatabase.end() && userDatabase[username] == password) {
            cout << "登录成功!" << endl;
            Sleep(1000);
            system("cls");
            return true;
        } else {
            attempt++;
            cout << "用户名或密码错误,请重试(" << 4 - attempt << "次机会剩余):" << endl;
            Sleep(1000);
            system("cls");            
        }
    }
    cout << "尝试次数过多,请稍后再试" << endl;
    Sleep(1000);
    system("cls");
    c_login();
    Sleep(1000);
    system("cls");
    return false;
}

// 初始化Zobrist哈希表
void initZobristTable() {
    srand(time(0));
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            for (int k = 0; k < 3; k++) {
                zobristTable[i][j][k] = (unsigned long long)rand() << 32 | rand();
            }
        }
    }
}

// 更新Zobrist哈希键
void updateZobristKey(int x, int y, int player) {
    zobristKey ^= zobristTable[x][y][0];
    zobristKey ^= zobristTable[x][y][player];
}

// 初始化棋盘
void initBoard() {
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            board[i][j] = 0;
        }
    }
    zobristKey = 0;
    initZobristTable();
}

// 打印棋盘
void printBoard(int x,int y,bool z) {
    HANDLE hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
    for(int i=0;i<20;i++){
        COORD s={0,i};
        DWORD w;
        SetConsoleCursorPosition(hConsole,s);
        FillConsoleOutputCharacter(hConsole,' ',50,s,&w);
        s={0,0};
        SetConsoleCursorPosition(hConsole,s);
    }
    // 打印列号
    cout << "    ";
    for (int i = 0; i < BOARD_SIZE; i++) {
        if(i>=10){
            cout << i << " ";
        }else{
            cout << i << "  "; 
        }
    }
    cout << endl;
    // 打印棋盘
    for (int i = 0; i < BOARD_SIZE; i++) {
        if (i < 10) cout << " ";
        cout << i << "  "; // 行号
        
        for (int j = 0; j < BOARD_SIZE; j++) {
            if(i==y&&j==x){
                if(z){
                    color(4*16+14);
                }else{
                    color(16+14);
                    cout<<"O  ";
                    continue;
                }    
            }else{
                color(15);
            }
            if (board[i][j] == 0) {
                cout << "· ";
            } else if (board[i][j] == 1) {
                cout << "X  "; // 黑子
            } else {
                cout << "O  "; // 白子
            }
        }
        cout << endl;
    }
}

// 检查胜利条件
bool checkWin(int x, int y, int player) {
    int directions[4][2] = {{1,0}, {0,1}, {1,1}, {1,-1}};
    for (int i = 0; i < 4; i++) {
        int count = 1;
        // 正向检查
        for (int step = 1; step < 5; step++) {
            int nx = x + step * directions[i][0];
            int ny = y + step * directions[i][1];
            if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE || 
                board[nx][ny] != player) break;
            count++;
        }
        // 反向检查
        for (int step = 1; step < 5; step++) {
            int nx = x - step * directions[i][0];
            int ny = y - step * directions[i][1];
            if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE || 
                board[nx][ny] != player) break;
            count++;
        }
        if (count >= 5) return true;
    }
    return false;
}

// 评估方向上的棋型
int evaluateDirection(int x, int y, int dx, int dy, int player) {
    int score = 0;
    int count = 0;
    int openEnds = 0;
    // 检查连续棋子数量
    for (int step = 0; step < 6; step++) {
        int nx = x + step * dx;
        int ny = y + step * dy;
        if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE) break;
        if (board[nx][ny] == player) count++;
        else if (board[nx][ny] == 0) { 
            openEnds++; 
            break; 
        }
        else break;
    }
    // 根据棋型评分
    if (count >= 5) return FIVE;
    if (count == 4) {
        if (openEnds == 2) return LIVE_FOUR;
        else if (openEnds == 1) return FOUR;
    }
    if (count == 3) {
        if (openEnds == 2) return LIVE_THREE;
        else if (openEnds == 1) return THREE;
    }
    if (count == 2) {
        if (openEnds == 2) return LIVE_TWO;
        else if (openEnds == 1) return TWO;
    }
    return 0;
}

// 评估棋盘状态
int evaluateBoard() {
    int score = 0;
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            if (board[i][j] == 0) continue;
            
            score += evaluateDirection(i, j, 1, 0, board[i][j]);
            score += evaluateDirection(i, j, 0, 1, board[i][j]);
            score += evaluateDirection(i, j, 1, 1, board[i][j]);
            score += evaluateDirection(i, j, 1, -1, board[i][j]);
            
            // 特别关注敌方威胁(防守连三的关键)
            if (board[i][j] == 1) {
                int threat = evaluateDirection(i, j, 1, 0, 1) +
                            evaluateDirection(i, j, 0, 1, 1) +
                            evaluateDirection(i, j, 1, 1, 1) +
                            evaluateDirection(i, j, 1, -1, 1);
                score -= threat * 7;
            }
        }
    }
    return score;
}

// 生成可能的移动
vector<pair<int, int> > generateMoves(bool defensive = false) {
    vector<pair<int, int> > moves;
    vector<pair<int, int> > defensiveMoves;
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            if (board[i][j] == 0) {
                bool nearPiece = false;
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        if (dx == 0 && dy == 0) continue;
                        int ni = i + dx, nj = j + dy;
                        if (ni >= 0 && ni < BOARD_SIZE && nj >= 0 && nj < BOARD_SIZE && 
                            board[ni][nj] != 0) {
                            nearPiece = true;
                            break;
                        }
                    }
                    if (nearPiece) break;
                }
                if (nearPiece) {
                    board[i][j] = 1;
                    int threat = evaluateDirection(i, j, 1, 0, 1) +
                                evaluateDirection(i, j, 0, 1, 1) +
                                evaluateDirection(i, j, 1, 1, 1) +
                                evaluateDirection(i, j, 1, -1, 1);
                    board[i][j] = 0;
                    
                    if (threat >= LIVE_THREE) {
                        defensiveMoves.push_back(make_pair(i, j));
                    } else {
                        moves.push_back(make_pair(i, j));
                    }
                }
            }
        }
    }
    if (defensive && !defensiveMoves.empty()) {
        defensiveMoves.insert(defensiveMoves.end(), moves.begin(), moves.end());
        return defensiveMoves;
    }
    return moves;
}

// 移动排序
void sortMoves(vector<pair<int, int> >& moves, bool maximizingPlayer) {
    vector<pair<int, pair<int, int> > > scoredMoves;
    for (vector<pair<int, int> >::iterator it = moves.begin(); it != moves.end(); ++it) {
        int score = 0;
        int centerDist = abs(it->first - BOARD_SIZE/2) + abs(it->second - BOARD_SIZE/2);
        score += (BOARD_SIZE - centerDist) * 10;
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                if (dx == 0 && dy == 0) continue;
                int ni = it->first + dx, nj = it->second + dy;
                if (ni >= 0 && ni < BOARD_SIZE && nj >= 0 && nj < BOARD_SIZE && 
                    board[ni][nj] != 0) {
                    score += 100;
                }
            }
        }
        board[it->first][it->second] = maximizingPlayer ? 2 : 1;
        score += evaluateBoard() / 10;
        board[it->first][it->second] = 0;
        
        scoredMoves.push_back(make_pair(score, *it));
    }
    if (maximizingPlayer) {
        sort(scoredMoves.rbegin(), scoredMoves.rend());
    } else {
        sort(scoredMoves.begin(), scoredMoves.end());
    }
    moves.clear();
    for (vector<pair<int, pair<int, int> > >::iterator it = scoredMoves.begin(); it != scoredMoves.end(); ++it) {
        moves.push_back(it->second);
    }
}

// 查询置换表
int probeTranspositionTable(unsigned long long key, int depth, int alpha, int beta) {
    map<unsigned long long, TranspositionTableEntry>::iterator it = transTable.find(key);
    if (it != transTable.end() && it->second.depth >= depth) {
        if (it->second.flag == 0) return it->second.score;
        if (it->second.flag == 1 && it->second.score >= beta) return beta;
        if (it->second.flag == 2 && it->second.score <= alpha) return alpha;
    }
    return INT_MAX;
}

// 存储置换表
void storeTranspositionTable(unsigned long long key, int depth, int score, int flag) {
    TranspositionTableEntry entry;
    entry.key = key;
    entry.depth = depth;
    entry.score = score;
    entry.flag = flag;
    transTable[key] = entry;
}

// Minimax算法
int minimax(int depth, int alpha, int beta, bool maximizingPlayer, unsigned long long zobristKey) {
    int val = probeTranspositionTable(zobristKey, depth, alpha, beta);
    if (val != INT_MAX) return val;
    if (depth == 0) {
        return evaluateBoard();
    }
    int bestScore = maximizingPlayer ? INT_MIN : INT_MAX;
    vector<pair<int, int> > moves = generateMoves(!maximizingPlayer);
    sortMoves(moves, maximizingPlayer);
    for (vector<pair<int, int> >::iterator it = moves.begin(); it != moves.end(); ++it) {
        board[it->first][it->second] = maximizingPlayer ? 2 : 1;
        updateZobristKey(it->first, it->second, maximizingPlayer ? 2 : 1); 
        int score = minimax(depth-1, alpha, beta, !maximizingPlayer, zobristKey);
        board[it->first][it->second] = 0;
        updateZobristKey(it->first, it->second, 0);
        if (maximizingPlayer) {
            bestScore = max(bestScore, score);
            alpha = max(alpha, bestScore);
        } else {
            bestScore = min(bestScore, score);
            beta = min(beta, bestScore);
        }
        if (beta <= alpha) break;
    }
    int flag = 0;
    if (bestScore <= alpha) flag = 2;
    else if (bestScore >= beta) flag = 1;
    storeTranspositionTable(zobristKey, depth, bestScore, flag);
    return bestScore;
}

// AI决策函数
pair<int, int> aiMove(int player) {
    int bestScore = INT_MIN;
    pair<int, int> bestMove = make_pair(-1, -1);
    vector<pair<int, int> > moves = generateMoves(true);
    sortMoves(moves, true);
    for (vector<pair<int, int> >::iterator it = moves.begin(); it != moves.end(); ++it) {
        board[it->first][it->second] = player;
        updateZobristKey(it->first, it->second, player);
        int score = minimax(DEPTH-1, INT_MIN, INT_MAX, false, zobristKey);
        board[it->first][it->second] = 0;
        updateZobristKey(it->first, it->second, 0);
        if (score > bestScore) {
            bestScore = score;
            bestMove = *it;
        }
    }
    return bestMove;
}

//五子棋游戏开始函数 
void gameLoop() {
    bool isFirstMove=true;
    initBoard();
    int x=0, y=0;
    printBoard(x,y,1);
    while (true) {
        if (currentPlayer == 1) {
            while(1){
                if(_kbhit()){
                    int a=getch();
                    if((a=='A'||a=='a')&&y-1>=0){
                        y--;
                    }
                    if((a=='S'||a=='s')&&x+1<=BOARD_SIZE){
                        x++;
                    }
                    if((a=='W'||a=='w')&&x-1>=0){
                        x--;
                    }
                    if((a=='D'||a=='d')&&y+1<=BOARD_SIZE){
                        y++;
                    }
                    if(a=='R'||a=='r') start();
                    if(a==32){
                        if(board[x][y] != 0){
                            continue;
                        }
                        break;
                    }
                    printBoard(y,x,1);
                }
            }
            printBoard(y,x,1);
            board[x][y] = 1;
            updateZobristKey(x, y, 1);
            if (checkWin(x, y, 1)) {
                printBoard(x,y,1);
                cout << "玩家获胜!" << endl;
                break;
            }
            isFirstMove=false;
        } else {
            if (isFirstMove) {
                // AI先手且为第一步,下在(7,7)
                x = 7;
                y = 7;
                board[x][y] = 2;
                updateZobristKey(x, y, 2);
                printBoard(y, x, 0);
                cout << "AI先手固定在(7,7)落子" << endl;
                isFirstMove = false; // 标记已走第一步
            } else {
                cout << "AI思考中..." << endl;
                pair<int, int> move = aiMove(2);
                board[move.first][move.second] = 2;
                updateZobristKey(move.first, move.second, 2);
                printBoard(move.second, move.first, 0);
                cout << "AI落子: " << move.first << " " << move.second << endl;
                x = move.first;
                y = move.second;
                if (checkWin(move.first, move.second, 2)) {
                    cout << "AI获胜!" << endl;
                    break;
                }
            }
        }

        currentPlayer = 3 - currentPlayer; // 切换玩家
    }
}

// 五子棋游戏AI版 
void start(){
    system("cls");
    int a1=1;
    cout<<"难度:"<<endl;
        for(int i=1;i<10;i++){
            if(a1==i){
                color(224);
                cout<<">";
            }else{
                color(15);
                cout<<" ";
            }
            cout<<"难度:"<<i<<endl;
        }
        color(2);
        cout<<endl<<"友情提示:难度高于5级可能会导致思考很慢~";
        cout<<endl<<"按r退出";
        color(15);
    while(1){
        if(_kbhit()){
            if(getch()=='r'||getch()=='R') w_fight();
            if(getch()==32){
                DEPTH=a1;
                gameLoop();
            }
            if(getch()=='w'&&a1>1){
                a1--;
            }
            if(getch()=='s'&&a1<9){
                a1++;
            }
            HANDLE hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
            for(int i=0;i<31;i++){
                color(15);
                COORD s={0,i};
                DWORD w;
                SetConsoleCursorPosition(hConsole,s);
                FillConsoleOutputCharacter(hConsole,' ',50,s,&w);
                s={0,0};
                SetConsoleCursorPosition(hConsole,s);
            }    
            cout<<"难度:"<<endl;
            for(int i=1;i<10;i++){
                if(a1==i){
                    color(224);
                    cout<<">";
                }else{
                    color(15);
                    cout<<" ";
                }
                cout<<"难度:"<<i<<endl;
            }
            color(15);
            if(a1>5) color(4);
            else color(2);
            cout<<endl<<"友情提示:难度高于5级可能会导致思考很慢~";
            cout<<endl<<"按r退出";
            color(15);
        }
    }
}

//AI五子棋对战函数
void w_AI_fight(){
    system("cls");
    while(1){
        cout<<"你要选择的模式:"<<endl;
        cout<<"A:玩家先下   B:AI先下"<<endl;
        char mode;
        cin>>mode;
        if(mode!='A'&&mode!='B'&&mode!='a'&&mode!='b'){
            system("cls");
            cout<<"请重新输入!";    
            Sleep(1000);
            system("cls");
            continue;
        }
        currentPlayer = (mode=='A'||mode=='a')?1:2;
        break;
    }
    system("cls");
    start();
}

//五子棋双人对战版函数
void w_two_fight() {
    system("cls");
    cout<<"请输入先下的玩家(1或2):";
    cin>>currentPlayer;
    system("cls");
    initBoard();
    printBoard(0, 0, false);
    while (true) {
        if (currentPlayer == 1) {
            int x, y;
            cout << "玩家1下棋 (输入坐标 x y): ";
            cin >> x >> y;
            if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || board[x][y] != 0) {
                cout << "无效坐标,请重新输入!" << endl;
                Sleep(1000);
                continue;
            }
            board[x][y] = 1;
            updateZobristKey(x, y, 1);
            printBoard(y, x, 1);
            if (checkWin(x, y, 1)) {
                printBoard(x, y, 1);
                cout << "玩家1获胜!" << endl;
                Sleep(5000);
                break;
            }
        } else {
            int x, y;
            cout << "玩家2下棋 (输入坐标 x y): ";
            cin >> x >> y;
            if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || board[x][y] != 0) {
                cout << "无效坐标,请重新输入!" << endl;
                Sleep(1000);
                continue;
            }
            board[x][y] = 2;
            updateZobristKey(x, y, 2);
            printBoard(y, x, 0);
            if (checkWin(x, y, 2)) {
                printBoard(x, y, 0);
                cout << "玩家2获胜!" << endl;
                Sleep(5000);
                break;
            }
        }
        currentPlayer = 3 - currentPlayer; // 切换玩家
    }

//判断创建的文件是否存在
bool fileExists(const char* path){
    ifstream f(path);
    return f.good();
}

//创建文件用户信息 
void create1(){
    const char* path="C:/user.txt";
    if(!fileExists(path)){
        ofstream newFile(path);
        if(newFile){
            cout<<"文件1创建成功!"<<endl;
            newFile.close();
            Sleep(1000);
            system("cls");
        }else{
            cerr<<"文件1创建失败,运行错误!"<<endl;
            exit(0);
        }
    }
}

//创建文件记录用户钱币数 
void create2(){
    const char* path="C:/coin.txt";
    if(!fileExists(path)){
        ofstream newFile(path);
        if(newFile){
            cout<<"文件2创建成功!"<<endl;
            newFile.close();
            Sleep(1000);
            system("cls");
        }else{
            cerr<<"文件2创建失败,运行错误!"<<endl;
            exit(0);
        }
    }
}

//创建文件记录用户贪吃蛇最好成绩
void create3(){
    const char* path="C:/s_bestscore.txt";
    if(!fileExists(path)){
        ofstream newFile(path);
        if(newFile){
            cout<<"文件3创建成功!"<<endl;
            newFile.close();
            Sleep(1000);
            system("cls");
        }else{
            cerr<<"文件3创建失败,运行失败!"<<endl;
            exit(0);
        }
    }
}

//创建文件记录用户俄罗斯方块最好成绩
void create4(){
    const char* path="C:/E_bestscore.txt";
    if(!fileExists(path)){
        ofstream newFile(path);
        if(newFile){
            cout<<"文件4创建成功!"<<endl;
            newFile.close();
            Sleep(1000);
            system("cls");
            cout<<"正在启动游戏……"<<endl;
            Sleep(1000);
            system("cls");
        }else{
            cerr<<"文件4创建失败,运行失败!"<<endl;
            exit(0);
        }
    }
}

//注销账号 
void unregisterUser() {
    system("cls");
    string  password;
    cout << "注销账号:" << endl;
    cout << "请输入密码: ";
    cin >> password;
    // 从文件中查找并删除用户信息
    ifstream file("C:/user.txt");
    ofstream newFile("C:/user_temp.txt");
    string tempUsername, tempPassword;
    bool found = false;
    if (file.is_open() && newFile.is_open()) {
        while (file >> tempUsername >> tempPassword) {
            if (username != tempUsername || password != tempPassword ) {
                newFile << tempUsername << " " << tempPassword << endl;
            } else {
                found = true;
            }
        }
        file.close();
        newFile.close();
    } else {
        cerr << "注销失败,运行错误!" << endl;
        Sleep(1000);
        return;
    }
    // 删除原始文件,并将临时文件重命名为原始文件名
    remove("C:/user.txt");
    rename("C:/user_temp.txt", "C:/user.txt");
    if (found) {
        cout << "注销成功!" << endl;
        // 设置登录状态为未登录,并返回到主菜单
        isLoggedIn = false;
        Sleep(1000);
        system("cls");
        menu(); // 返回到主菜单
    } else {
        cout << "用户名或密码错误,注销失败!" << endl;
    }
    Sleep(1000);
    system("cls");
}

//修改密码 
void changePassword() {
    system("cls");
    string oldPassword, newPassword, confirmNewPassword;
    cout << "修改密码:" << endl;
    cout << "请输入当前密码: ";
    cin >> oldPassword;
    if (userDatabase[username] != oldPassword) {
        cout << "当前密码错误,修改失败!" << endl;
        Sleep(1000);
        return;
    }
    cout << "请输入新密码: ";
    cin >> newPassword;
    cout << "请确认新密码: ";
    cin >> confirmNewPassword;
    if (newPassword != confirmNewPassword) {
        cout << "两次输入不一致,修改失败!" << endl;
        Sleep(1000);
        return;
    }
    // 创建临时文件
    ofstream temp("C:/temp.txt");
    ifstream orig(FILE_PATH.c_str());   
    if(!temp || !orig) {
        cerr << "文件操作失败!" << endl;
        return;
    }
    string line;
    while(getline(orig, line)) {
        if(line.find(username) == 0) {
            temp << username << " " << newPassword << endl;
        } else {
            temp << line << endl;
        }
    }    
    orig.close();
    temp.close();   
    // 替换原文件
    remove(FILE_PATH.c_str());
    rename("C:/temp.txt", FILE_PATH.c_str());
    // 更新内存中的数据
    userDatabase[username] = newPassword;
    cout << "密码修改成功!" << endl;
    Sleep(1000);
}

//修改贪吃蛇最好成绩
void sR_bestscore(){
    ofstream temp("C:/s_temp.txt");
    ifstream orig(S_PATH.c_str());
    if(!temp||!orig){
        cerr<<"文件操作失败!"<<endl;
        return;
    }
    string line;
    while(getline(orig,line)){
        if(line.find(username)==0){
            temp<<username<<" "<<s_bestscore<<endl;
        }else{
            temp<<line<<endl;
        }
        orig.close();
        temp.close();
        remove(S_PATH.c_str());
        rename("C:/s_temp.txt",S_PATH.c_str());
        s_Bestscore[username]=s_bestscore;
    }
}

//修改俄罗斯方块最好成绩
void ER_bestscore(){
    ofstream temp("C:/E_temp.txt");
    ifstream orig(E_PATH.c_str());
    if(!temp||!orig){
        cerr<<"文件操作失败!"<<endl;
        return;
    }
    string line;
    while(getline(orig,line)){
        if(line.find(username)==0){
            temp<<username<<" "<<E_bestscore<<endl;
        }else{
            temp<<line<<endl;
        }
        orig.close();
        temp.close();
        remove(E_PATH.c_str());
        rename("C:/E_temp.txt",E_PATH.c_str());
        E_Bestscore[username]=E_bestscore;
    }
}

//退出登录
void reLoggedIn(){
    system("cls");
    cout<<"你确定要退出登录吗(Y/N):";
    char choose;
    cin>>choose;
    if(choose=='Y'||choose=='y'){
        isLoggedIn=false;
        menu();
    }else{
        mine();
    }
}

//我的详细信息
void more_massage(){
    system("cls");
    cout<<"你有"<<userCoins[username]<<"个钱币-"<<endl;
    cout<<"你的贪吃蛇最好成绩为:"<<s_Bestscore[username]<<endl;
    cout<<"你的俄罗斯方块最好成绩为:"<<E_Bestscore[username]<<endl;
    cout<<"按r退出"<<endl;
    while(true){
        if(_kbhit()){
            if(getch()=='r'||getch()=='R') mine();
        }
    }

//我的
void mine() {
    while (true) {
        system("cls");
        cout << " -- 我的 -- " <<endl;
        cout << "欢迎, " << username << "!" << endl; // 显示用户名
        int choose;
        cout << "1.注销账号" << endl;
        cout << "2.修改密码" << endl;
        cout << "3.退出登录" << endl;
        cout << "4.详细信息" << endl; 
        cout << "5.返回" << endl;
        cout << "请输入你的选择:";
        cin >> choose;
        if (choose == 1) {
            unregisterUser();
        } else if (choose == 2) {
            changePassword(); 
        } else if (choose == 3) {
            reLoggedIn();
        } else if (choose == 4){
            more_massage();
        } else if (choose == 5){
            menu();
        } else {
            cout<<"无效输入!"<<endl;
            Sleep(1000);
            mine();
        }
    }
}

//五子棋
void w_fight(){
    system("cls");
    int choose;
    cout<<" -- 五子棋 -- "<<endl;
    cout<<"1.大战AI"<<endl;
    cout<<"2.双人对战"<<endl;
    cout<<"3.返回"<<endl;
    cin>>choose;
    if(choose==1){
        w_AI_fight();    
    }else if(choose==2){
        w_two_fight();
    }else if(choose==3){
        menu();
    }else{
        cout<<"无效输入!"<<endl;
        Sleep(1000);
        w_fight();
    }
}

//迷宫代码起始点(刘凯祺作) 
//迷宫地图打印
void m_paintboard(int xx,int yy){
    fastcls();
    for(int i=0;i<=size;i++){
        for(int j=0;j<=size;j++){
            if(i == xx && j == yy){
                cout << "M";
                continue;
            }
            else if(i == size-1 && j == size-1){
                cout << "E";
            }
            if(MAP[i][j]) cout << "#";
            else cout << " ";
        }
        cout << endl;
    }
}

//迷宫搜索核心
bool bfs(){
    queue<pair<int,int> > q;
    q.push(make_pair(1,1));
    const int dx[]={1,0,-1,0};
    const int dy[]={0,1,0,-1};
    int vis[52][52];
    for(int i=1;i<size;i++){
        for(int j=1;j<size;j++){
            vis[i][j] = MAP[i][j] == true ? 1 : 0;
        }
    }
    while(!q.empty()){
        pair<int,int> u = q.front();
        int x = u.first;
        int y = u.second;
        if(x == size-1 && y == size-1){
            return true;
        }
        for(int i=0;i<4;i++){
            int xx = x+dx[i];
            int yy = y+dy[i];
            if(xx >= 1 && xx < size && yy >= 1 && yy < size && vis[xx][yy] == 0){
                vis[xx][yy] = 1;
                q.push(make_pair(xx,yy));
            }
        }
        q.pop();
    }
    return false;
}

//迷宫
void maze(){
    skip1:
    system("cls");
    cout << "欢迎来到迷宫游戏" << endl;
    cout << "请选择难度:" << endl;
    cout << "1.简单"<<endl;
    cout << "2.中等"<<endl;
    cout << "3.困难"<<endl;
    cout << "4.自定义" << endl;
    cout << "5.返回" << endl;
    int difficulty;
    cin >> difficulty;
     if(difficulty == 1){
         size = 21;
     }else if(difficulty == 2){
         size = 36;
     }else if(difficulty == 3){
         size = 51;
     }else if(difficulty == 4){
         cout << "请输入难度(迷宫大小)" << endl;
         cin >> size; 
         size++;
     }else if(difficulty==5){
         menu();
     }else{
         system("cls");
         cout << "输入错误,请重试";
         Sleep(1000);
         goto skip1;
     }
    srand(time(NULL));
    for(int i=0;i<=size;i++){
        for(int j=0;j<=size;j++){
            if(i == 1 && j == 1){
                MAP[i][j] = 0;
                continue;
            }
            else if(i == size-1 && j == size-1){
                MAP[i][j] = 0;
                continue;
            }
            if(i == 0 || j == 0 || i == size || j == size){
                MAP[i][j] = 1;
                continue;
            }
            else{
                int x = rand()% 10;
                if(x < 5){
                    MAP[i][j] = 0;
                }
                else{
                    MAP[i][j] = 1;
                }
            }
        }
    }
    unsigned long long times=0;
    while(!bfs()){
        times++;
        if(times%wait_time == 0){
            system("cls");
            cout << "请等待……(预计2分钟左右)" << endl;
            if(times/wait_time >= 100){
                cout << "已生成:" << 99 << "%" <<endl;
            }
            else cout << "已生成:" << times/wait_time << "%" <<endl; 
        }
        for(int i=0;i<=size;i++){
            for(int j=0;j<=size;j++){
                if(i == 1 && j == 1){
                    MAP[i][j] = 0;
                    continue;
                }
                else if(i == size-1 && j == size-1){
                    MAP[i][j] = 0;
                    continue;
                }
                if(i == 0 || j == 0 || i == size || j == size){
                    MAP[i][j] = 1;
                    continue;
                }
                else{
                    int x = rand()% 10;
                    if(x < 5){
                        MAP[i][j] = 0;
                    }
                    else{
                        MAP[i][j] = 1;
                    }
                }
            }
        }
    }
    system("cls");
    cout << "已生成:" << 100 << "%" <<endl;
    Sleep(2000);
    system("cls");
    color(rand()% 15+1);
    for(int i=0;i<=size;i++){
        for(int j=0;j<=size;j++){
            if(i == 1 && j == 1){
                color(2);
                cout << "M";
                color(15);
                continue;
            }
            else if(i == size-1 && j == size-1){
                cout << "E";
            }
            if(MAP[i][j]) cout << "#";
            else cout << " ";
        }
        cout << endl;
    }
    int x = 1, y = 1,step_num = 0;
    while(true){
        if(_kbhit()){
            char key = getch();
            switch(tolower(key)){
            Sleep(100);
            case 's' : {
                x++;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    x--;
                }
                break;
            }
            case 'S' : {
                x++;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    x--;
                }
                break;
            }
            case 'w' : {
                x--;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    x++;
                }
                break;
            }
            case 'W' : {
                x--;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    x++;
                }
                break;
            }
            case 'a' : {
                y--;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    y++;
                }
                break;
            }
            case 'A' : {
                y--;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    y++;
                }
                break;
            }
            case 'd' : {
                y++;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    y--;
                }
                break;
            }
            case 'D' : {
                y++;
                if(MAP[x][y] == 0 && x >= 1 && x < size && y >= 1 && y < size){
                    m_paintboard(x,y);
                    step_num++;
                }
                else{
                    y--;
                }
                break;
            }
        }
            if(x == size-1 && y == size-1){
                break;
            }
        }
    }
    system("cls");
    cout << "你赢了!!" << endl;
    cout << "所用步数:" << step_num << endl; 
    Sleep(3000);
    menu();
}
//迷宫代码终点

//贪吃蛇代码起点
// 初始化游戏
void Setup() {
    gameOver = false;
    gamePaused = false;
    dir = RIGHT; // 初始设置为向右移动
    headX = width / 2;
    headY = height / 2;
    srand((unsigned)time(0));
    
    // 初始分数和蛇长
    score = 0;
    tailLength = 0; // 初始蛇身长度为0(只有头部)
    snakeSpeed = 150; // 移动延迟(毫秒)
    
    // 清空蛇尾
    tail.clear();
    
    // 生成初始食物
    foods.clear();
    for (int i = 0; i < MAX_FOODS; i++) {
        GenerateFood();
    }
}

// 生成新食物
void GenerateFood() {
    GenerateFood1:
    if (foods.size() >= MAX_FOODS) return;

    Food newFood;
    bool validPosition;
    int attempts = 0;
    const int MAX_ATTEMPTS = 100;

    do {
        int typeIndex; 
        validPosition = true;
        newFood.x = rand() % width;
        newFood.y = rand() % height;
        
        // 随机分配食物类型
        int foodKind = rand() % 101+1; // enum FoodType { REGULAR, BONUS, SLOW, FAST, GOLD ,BOMB};
        if(foodKind >= 1 && foodKind <= 30) typeIndex = REGULAR;
        if(foodKind > 30 && foodKind <= 60) typeIndex = BONUS;
        if(foodKind > 60 && foodKind <= 70) typeIndex = SLOW;
        if(foodKind > 70 && foodKind <= 80) typeIndex = FAST;
        if(foodKind > 80 && foodKind <= 98) typeIndex = GOLD;
        if(foodKind > 98) typeIndex = BOMB;
        newFood.type = static_cast<FoodType>(typeIndex);
        
        // 设置食物符号和类型
        switch (newFood.type) {
            case REGULAR: 
                newFood.symbol = '@'; 
                break;
            case BONUS: 
                newFood.symbol = '$'; 
                break;
            case SLOW: 
                newFood.symbol = 'S'; 
                break;
            case FAST: 
                newFood.symbol = 'F'; 
                break;
            case GOLD: 
                newFood.symbol = 'G'; 
                break;
            case BOMB:
                newFood.symbol = 'B';
                break; 
        }

        // 检查是否与蛇头重合
        if (newFood.x == headX && newFood.y == headY) {
            validPosition = false;
        }
        
        // 检查是否与蛇身重合
        for (vector<pair<int, int> >::iterator it = tail.begin(); it != tail.end(); ++it) {
            if (it->first == newFood.x && it->second == newFood.y) {
                validPosition = false;
                break;
            }
        }
        
        // 检查是否与其他食物重合
        for (vector<Food>::iterator it = foods.begin(); it != foods.end(); ++it) {
            if (it->x == newFood.x && it->y == newFood.y) {
                validPosition = false;
                break;
            }
        }
        
        attempts++;
    } while (!validPosition && attempts < MAX_ATTEMPTS);

    if (validPosition) {
        foods.push_back(newFood);
    }
}

// 绘制游戏界面
void Draw() {
    // 清屏
    fastcls();
    
    // 绘制顶部边框
    SetColor(YELLOW);
    for (int i = 0; i < width + 2; i++)
        cout << "#";
    cout << endl;
    
    // 绘制游戏区域
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            // 绘制左侧边框
            if (j == 0) {
                SetColor(YELLOW);
                cout << "#";
            }
            
            // 绘制蛇头
            if (i == headY && j == headX) {
                SetColor(GREEN);
                cout << "O";
            }
            else {
                bool printed = false;
                
                // 绘制食物
                for (vector<Food>::iterator it = foods.begin(); it != foods.end(); ++it) {
                    if (it->x == j && it->y == i) {
                        switch (it->type) {
                            case REGULAR: SetColor(RED); break;
                            case BONUS: SetColor(MAGENTA); break;
                            case SLOW: SetColor(CYAN); break;
                            case FAST: SetColor(BLUE); break;
                            case GOLD: SetColor(YELLOW); break;
                            case BOMB: SetColor(WHITE); break;
                        }
                        cout << it->symbol;
                        printed = true;
                        break;
                    }
                }
                
                // 绘制蛇身
                if (!printed) {
                    bool isTail = false;
                    for (vector<pair<int, int> >::iterator it = tail.begin(); it != tail.end(); ++it) {
                        if (it->first == j && it->second == i) {
                            SetColor(GREEN);
                            cout << "o";
                            isTail = true;
                            printed = true;
                            break;
                        }
                    }
                    
                    // 绘制空白
                    if (!printed) {
                        cout << " ";
                    }
                }
            }
            
            // 绘制右侧边框
            if (j == width - 1) {
                SetColor(YELLOW);
                cout << "#";
            }
        }
        cout << endl;
    }
    
    // 绘制底部边框
    SetColor(YELLOW);
    for (int i = 0; i < width + 2; i++)
        cout << "#";
    cout << endl;
    
    // 绘制分数和游戏信息
    ResetColor();
    cout << "Score: " << score << endl;
    if(score>s_bestscore) s_bestscore=score;
    cout << "Bestscore:" << s_Bestscore[username] <<endl;
    cout << "Length: " << tailLength + 1 << endl; // +1 包括蛇头
    cout << "Speed: " << (snakeSpeed < 100 ? "FAST" : (snakeSpeed > 140 ? "SLOW" : "NORMAL")) << endl;
    cout << "\nFood Types:\n";
    SetColor(RED); cout << "  @ Regular (+1 length)\n";
    SetColor(MAGENTA); cout << "  $ Bonus (+5 points)\n";
    SetColor(CYAN); cout << "  S Slow (-10ms delay)\n";
    SetColor(BLUE); cout << "  F Fast (+10ms delay)\n";
    SetColor(YELLOW); cout << "  G Gold (+10 points, +2 length)\n";
    SetColor(WHITE); cout << "  B Bomb (-5 points, -1 length)\n";
    ResetColor();
    cout << "\nControls: WASD to move, P to pause, R to exit";
    
    if (gamePaused) {
        SetColor(YELLOW);
        cout << "\n\n  GAME PAUSED - Press P to resume";
        ResetColor();
    }
}

// 处理用户输入
void Input() {
    if (_kbhit()) {
        char key = _getch();
        switch (key) {
            case 'a':
                if (dir != RIGHT) dir = LEFT;
                break;
            case 'd':
                if (dir != LEFT) dir = RIGHT;
                break;
            case 'w':
                if (dir != DOWN) dir = UP;
                break;
            case 's':
                if (dir != UP) dir = DOWN;
                break;
            case 'p':
                gamePaused = !gamePaused;
                break;
            case 'r':
                gameOver = true;
                break;
        }
    }
}

// 游戏逻辑
void Logic() {
    if (gamePaused) return;

    // 记录蛇头之前的位置
    pair<int, int> prev(headX, headY);
    
    // 只有当蛇身长度大于0时添加到尾部
    if (tailLength > 0) {
        tail.insert(tail.begin(), prev);
    }

    // 移除多余的蛇尾
    if ((int)tail.size() > tailLength) {
        tail.pop_back();
    }

    // 根据方向移动蛇头
    switch (dir) {
        case LEFT:
            headX--;
            break;
        case RIGHT:
            headX++;
            break;
        case UP:
            headY--;
            break;
        case DOWN:
            headY++;
            break;
        default:
            break;
    }

    // 边界检测(穿过边界)
    if (headX >= width) headX = 0;
    else if (headX < 0) headX = width - 1;
    if (headY >= height) headY = 0;
    else if (headY < 0) headY = height - 1;

    // 自身碰撞检测(只有当尾巴长度大于0时才检测)
    if (tailLength > 0) {
        for (vector<pair<int, int> >::iterator it = tail.begin(); it != tail.end(); ++it) {
            if (it->first == headX && it->second == headY) {
                gameOver = true;
                return;
            }
        }
    }

    // 食物检测
    for (vector<Food>::iterator it = foods.begin(); it != foods.end(); ) {
        if (headX == it->x && headY == it->y) {
            // 根据食物类型执行不同效果
            switch (it->type) {
                case REGULAR:
                    tailLength++;
                    score += 1;
                    break;
                case BONUS:
                    score += 5;
                    break;
                case SLOW:
                    snakeSpeed += 10; // 减速
                    if (snakeSpeed > 200) snakeSpeed = 200;
                    break;
                case FAST:
                    snakeSpeed -= 10; // 加速
                    if (snakeSpeed < 40) snakeSpeed = 40;
                    break;
                case GOLD:
                    tailLength += 2;
                    score += 10;
                    break;
                case BOMB:
                    if(tailLength > 1){
                        tailLength--;
                    }
                    if(score >= 5){
                        score -= 5;
                    }
                    break;
            }
            
            // 移除被吃的食物
            it = foods.erase(it);
            
            // 生成新食物
            GenerateFood();
        } else {
            ++it;
        }
    }
}

void Snakes(){
    Setup();
    while (!gameOver) {
        Draw();
        Input();
        if (!gamePaused) {
            Logic();
        }
        Sleep(snakeSpeed);
    }
    // 游戏结束画面
    system("cls");
    SetColor(RED);
    cout << "\n\n  **************************";
    cout << "\n  *       GAME OVER!       *";
    cout << "\n  **************************";
    SetColor(YELLOW);
    cout << "\n\n  Final Score: " << score;
    if(s_bestscore>s_Bestscore[username]) sR_bestscore();
    cout << "\n  Best Score:"<<s_Bestscore[username];
    cout << "\n  Snake Length: " << tailLength + 1; // +1 包括蛇头
    ResetColor();
    Sleep(3000);
    cout << "\n\n  Press any key to exit...";
    _getch();
}
//贪吃蛇代码结束

//俄罗斯方块代码起始点
class Tetris {
private:
    vector<vector<int> > board;
    int currentShape;
    int rotation;
    int posX, posY;
    int score;
    bool gameOver;
    void drawBoard() {
        fastcls();
        cout << "分数: " << score << endl << endl;
        for (int y = 0; y < HEIGHT; y++) {
            cout << "|";
            for (int x = 0; x < WIDTH; x++) {
                if (board[y][x] || (y >= posY && y < posY + 4 && 
                    x >= posX && x < posX + 4 && 
                    SHAPES[currentShape][rotation][y-posY][x-posX])) {
                    cout << "#";
                } else {
                    cout << " ";
                }
            }
            cout << "|" << endl;
        }
        cout << "+";
        for (int x = 0; x < WIDTH; x++) cout << "-";
        cout << "+" << endl;
    }
    bool checkCollision(int newX, int newY, int newRotation) {
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                if (SHAPES[currentShape][newRotation][y][x]) {
                    int boardX = newX + x;
                    int boardY = newY + y;
                    
                    if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
                        return true;
                    }
                    
                    if (boardY >= 0 && board[boardY][boardX]) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    void mergePiece() {
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                if (SHAPES[currentShape][rotation][y][x]) {
                    int boardY = posY + y;
                    int boardX = posX + x;
                    if (boardY >= 0 && boardY < HEIGHT && boardX >= 0 && boardX < WIDTH) {
                        board[boardY][boardX] = 1;
                    } else {
                        gameOver = true;
                    }
                }
            }
        }
    }
    void clearLines() {
        for (int y = HEIGHT-1; y >= 0; y--) {
            bool lineComplete = true;
            for (int x = 0; x < WIDTH; x++) {
                if (!board[y][x]) {
                    lineComplete = false;
                    break;
                }
            }
            if (lineComplete) {
                for (int y2 = y; y2 > 0; y2--) {
                    for (int x = 0; x < WIDTH; x++) {
                        board[y2][x] = board[y2-1][x];
                    }
                }
                for (int x = 0; x < WIDTH; x++) {
                    board[0][x] = 0;
                }
                
                score += 100;
                y++;
            }
        }
    }
    void newPiece() {
        currentShape = rand() % 7;
        rotation = 0;
        posX = WIDTH / 2 - 2;
        posY = -2;       
        if (checkCollision(posX, posY, rotation)) {
            gameOver = true;
        }
    }
public:
    Tetris() : board(HEIGHT, vector<int>(WIDTH, 0)), score(0), gameOver(false) {
        srand(time(0));
        newPiece();
    }
    void run() {
        while (!gameOver) {
            drawBoard();           
            if (_kbhit()) {
                int key = _getch();
                
                switch (key) {
                    case 'a': case 'A': 
                        if (!checkCollision(posX-1, posY, rotation)) {
                            posX--;
                        }
                        break;
                    case 'd': case 'D':
                        if (!checkCollision(posX+1, posY, rotation)) {
                            posX++;
                        }
                        break;
                    case 's': case 'S':
                        if (!checkCollision(posX, posY+1, rotation)) {
                            posY++;
                        }
                        break;
                    case 'w': case 'W':
                        {
                            int newRotation = (rotation + 1) % 4;
                            if (!checkCollision(posX, posY, newRotation)) {
                                rotation = newRotation;
                            }
                        }
                        break;
                    case 'q': case 'Q': 
                        gameOver = true;
                        break;
                }
            }
            if (!checkCollision(posX, posY+1, rotation)) {
                posY++;
            } else {
                mergePiece();
                clearLines();
                newPiece();
            }
            
            Sleep(350);
        }       
        drawBoard();
        if(score>E_bestscore) E_bestscore=score;
        if(E_bestscore>E_Bestscore[username]) ER_bestscore();
        cout << "游戏结束! 最终分数: " << score << endl;
        cout << "历史最高分数:" << E_Bestscore[username] <<endl;
        Sleep(3000);
        menu();
    }
};
void E_block(){
    HANDLE hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
    for(int i=0;i<21;i++){
        COORD s={0,i};
        DWORD w;
        SetConsoleCursorPosition(hConsole,s);
        FillConsoleOutputCharacter(hConsole,' ',20,s,&w);
        s={0,0};
        SetConsoleCursorPosition(hConsole,s);
    }
    Sleep(100);
    Tetris game;
    game.run();

//俄罗斯方块代码终点 

//双人对打(hzq做)代码起点
//绘制地图函数 
void p_paintboard(){
    for(int i=1;i<=p_height;i++){
        cout<<"                                                               ";
        for(int j=1;j<=p_width;j++){
            if(p_board[i][j]==1) cout<<"A ";
            else if(p_board[i][j]==2) cout<<"B ";
            else if(p_board[i][j]==3) cout<<"a ";
            else if(p_board[i][j]==4) cout<<"b ";
            else cout<<". ";
            //cout<<p_board[i][j]<<" ";
        }
        cout<<"                                                               ";
        cout<<endl;
    }
    cout<<endl<<"                                                               ";
    cout<<"A被扣血:"<<-player1.heart<<"          "<<"B被扣血:"<<-player2.heart <<endl;
    cout<<"                                                               ";
    cout<<"A使用普通子弹:"<<-player1.ammo <<"    "<<"B使用普通子弹:"<<-player2.ammo <<endl;
    cout<<"                                                               ";
    cout<<"A使用散弹:"<<-player1.sammo <<"        "<<"B使用散弹:"<<-player2.sammo <<endl;
    cout<<"                                                               ";
    cout<<"每个玩家有"<<p_mostblood<<"滴血!"<<"有"<<p_mostammo<<"颗普通子弹!"<<endl;
    cout<<"                                                               ";
    cout<<"每个玩家有"<<p_mostsammo<<"颗散弹!"<<endl;
}
//控制子弹函数 
void p_move(){
    for(int i=1;i<=p_height;i++){
        for(int j=p_width;j>=1;j--){
            if(p_board[i][j]==3){
                p_board[i][j]=0;
                if(j<p_width) p_board[i][j+1]=3;
            }
        }
    }
    for(int i=1;i<=p_height;i++){
        for(int j=1;j<=p_width;j++){
            if(p_board[i][j]==4){
                p_board[i][j]=0;
                if(j>1) p_board[i][j-1]=4;
            }
        }
    }
}
//血量函数 
void p_blood(){
    for(int i=1;i<=p_height;i++){
        for(int j=1;j<=p_width;j++){
            if(p_board[i][j]==3&&player2.x ==i&&player2.y ==j){
                player2.heart-=1;
            }
            if(p_board[i][j]==4&&player1.x ==i&&player1.y ==j){
                player1.heart-=1;
            }
        }
    }
}
//打架函数 
void p_fight(){
    player1.x =1;player1.y =1;player1.heart =0;player1.ammo =0;player1.sammo =0;
    player2.x =p_height;player2.y =p_width;player2.heart =0;player2.ammo =0;player2.sammo =0;
    while(true){
        fastcls();
        p_board[player1.x ][player1.y ]=1;
        p_board[player2.x ][player2.y ]=2;
        p_move();
        p_blood();
        if(-player1.ammo >=p_mostammo&&-player2.ammo >=p_mostammo){
            Sleep(500);
            system("cls");
            cout<<"A和B玩家子弹耗尽,游戏结束!";
            Sleep(3000);
            break;
        }
        p_paintboard();
        if(-player1.heart>=p_mostblood){
            Sleep(500);
            system("cls");
            cout<<"A玩家输了!";
            Sleep(3000);
            break; 
        }
        if(-player2.heart>=p_mostblood){
            Sleep(500);
            system("cls");
            cout<<"B玩家输了!";
            Sleep(3000);
            break;
        }
        Sleep(20);
        if(_kbhit()){
            char key=getch();
            switch(tolower(key)){
                case 's':{
                    p_board[player1.x ][player1.y ]=0;
                    player1.x ++;
                    if(player1.x >p_height) player1.x --;
                    p_board[player1.x ][player1.y ]=1;
                    break;
                }
                case 'w':{
                    p_board[player1.x ][player1.y ]=0;
                    player1.x --;
                    if(player1.x <1) player1.x ++;
                    p_board[player1.x ][player1.y ]=1;
                    break;
                }
                case 'i':{
                    p_board[player2.x ][player2.y ]=0;
                    player2.x --;
                    if(player2.x <1) player2.x ++;
                    p_board[player2.x ][player2.y ]=2;
                    break;
                }
                case 'k':{
                    p_board[player2.x ][player2.y ]=0;
                    player2.x ++;
                    if(player2.x >p_height) player2.x --;
                    p_board[player2.x ][player2.y ]=2;
                    break;
                }
                case 'q':{
                    if(-player1.ammo <p_mostammo){
                        p_board[player1.x][player1.y+1]=3;
                        player1.ammo --;
                    }
                    break;
                }
                case 'o':{
                    if(-player2.ammo <p_mostammo){
                        p_board[player2.x][player2.y-1]=4;
                        player2.ammo --;
                    }
                    break;
                }
                case 'a':{
                    if(-player1.sammo <p_mostsammo){
                        for(int i=-2;i<=2;i++){
                            if(i+player1.x >0){
                                p_board[player1.x +i][player1.y +1]=3;
                            }
                        }
                        player1.sammo --;
                    }
                    break;
                }
                case 'l':{
                    if(-player2.sammo <p_mostsammo){
                        for(int i=-2;i<=2;i++){
                            if(i+player2.x >0){
                                p_board[player2.x +i][player2.y -1]=4;
                            }
                        }
                        player2.sammo --;
                    }
                    break;
                }
                case 'r':{
                    menu();
                    break;
                }
            }
        }
    }
}
//双人对打(hzq做)代码终点 

//猜数字(太简单了)!!
class GuessGame {
private:
    int secretNumber;
    int attempts;
    
public:
    GuessGame() {
        srand(std::time(0));
        secretNumber = std::rand() % 100 + 1;
        attempts = 0;
    }
    
    void play() {
        int guess;
        cout << "猜数字游戏(1-100):" << std::endl;
        
        do {
            g_play:
            cout << endl << "请输入你的猜测(不想玩了可以输入-1退出): ";
            cin >> guess;
            if(guess==-1) menu();
            if(guess<0||guess>100){
                cout<<"你的数不符合要求,请重新输入!";
                goto g_play;
            }
            attempts++;
            
            if (guess > secretNumber) {
                cout << "太大了!" << std::endl;
            } else if (guess < secretNumber) {
                cout << "太小了!" << std::endl;
            }
        } while (guess != secretNumber);
        system("cls");
        std::cout << "恭喜! 你在" << attempts << "次尝试后猜中了数字 " << secretNumber << std::endl;
    }
};
void g_guessgame(){
    system("cls");
    GuessGame guessgame;
    guessgame.play() ;
    Sleep(3000);
    system("cls");

//井字棋游戏
bool tryCorner() {
    int corners[] = {1,3,7,9};
    for(int i=0; i<4; i++) {
        int choice = corners[i];
        if(placeMark(choice, 'O')) return true;
    }
    return false;
}

bool tryEdge() {
    int edges[] = {2,4,6,8};
    for(int i=0; i<4; i++) {
        int choice = edges[i];
        if(placeMark(choice, 'O')) return true;
    }
    return false;
}

// 绘制游戏板
void drawBoard() {
    cout << "\n";
    cout << " " << Jboard[0][0] << " | " << Jboard[0][1] << " | " << Jboard[0][2] << endl;
    cout << "-----------\n";
    cout << " " << Jboard[1][0] << " | " << Jboard[1][1] << " | " << Jboard[1][2] << endl;
    cout << "-----------\n";
    cout << " " << Jboard[2][0] << " | " << Jboard[2][1] << " | " << Jboard[2][2] << endl;
    cout << "\n";
}

// 放置标记
bool placeMark(int choice, char mark) {
    int row = (choice - 1) / 3;
    int col = (choice - 1) % 3;
    if(choice >= 1 && choice <= 9 && Jboard[row][col] != 'X' && Jboard[row][col] != 'O') {
        Jboard[row][col] = mark;
        return true;
    }
    return false;
}

// 检查胜利条件
bool checkWin(char mark) {
    // 检查行
    for(int i = 0; i < 3; i++) {
        if(Jboard[i][0] == mark && Jboard[i][1] == mark && Jboard[i][2] == mark)
            return true;
    }
    // 检查列
    for(int i = 0; i < 3; i++) {
        if(Jboard[0][i] == mark && Jboard[1][i] == mark && Jboard[2][i] == mark)
            return true;
    }
    // 检查对角线
    if(Jboard[0][0] == mark && Jboard[1][1] == mark && Jboard[2][2] == mark)
        return true;
    if(Jboard[0][2] == mark && Jboard[1][1] == mark && Jboard[2][0] == mark)
        return true;
    
    return false;
}

// 检查平局
bool checkDraw() {
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            if(Jboard[i][j] != 'X' && Jboard[i][j] != 'O')
                return false;
        }
    }
    return true;
}

// 玩家回合
void playerTurn() {
    int choice;
    cout << "请选择一个位置(1-9): ";
    cin >> choice;
    while(!placeMark(choice, 'X')) {
        cout << "无效选择,请重试: ";
        cin >> choice;
    }
}

// 电脑回合(简单AI)
void computerTurn() {
    cout << "【战术AI思考中】\n";
    // 1. 直接获胜检查
    for(int i=1; i<=9; i++) {
        if(placeMark(i, 'O')) {
            if(checkWin('O')) return;
            else Jboard[(i-1)/3][(i-1)%3] = '0'+i;
        }
    }
    // 2. 阻挡玩家
    for(int i=1; i<=9; i++) {
        if(placeMark(i, 'X')) {
            if(checkWin('X')) {
                Jboard[(i-1)/3][(i-1)%3] = 'O';
                return;
            }
            else Jboard[(i-1)/3][(i-1)%3] = '0'+i;
        }
    }
    // 3. 抢占中心
    if(Jboard[1][1] == '5') {
        Jboard[1][1] = 'O';
        return;
    }
    // 4. 双角战术
    if(Jboard[1][1] == 'X') {
        if(tryCorner()) return;
        if((Jboard[0][0]=='X' && Jboard[2][2]=='X') || 
           (Jboard[0][2]=='X' && Jboard[2][0]=='X')) {
            if(tryEdge()) return;
        }
    }
    // 5. 占角优先
    if(tryCorner()) return;
    // 6. 最后占边
    if(tryEdge()) return;
}
void J_AI(){
    system("cls");
    srand(time(0)); // 初始化随机种子
    Jboard[0][0]='1';
    Jboard[0][1]='2';
    Jboard[0][2]='3';
    Jboard[1][0]='4';
    Jboard[1][1]='5';
    Jboard[1][2]='6';
    Jboard[2][0]='7';
    Jboard[2][1]='8';
    Jboard[2][2]='9';
    cout << "欢迎来到井字棋游戏!\n";
    cout << "玩家(X) 对战 电脑(O)\n\n";
    while(true) {
        drawBoard();
        playerTurn();
        if(checkWin('X')) {
            drawBoard();
            cout << "恭喜你赢了!\n";
            break;
        }
        if(checkDraw()) {
            drawBoard();
            cout << "平局!\n";
            break;
        }       
        computerTurn();
        if(checkWin('O')) {
            drawBoard();
            cout << "电脑赢了!\n";
            break;
        }
        if(checkDraw()) {
            drawBoard();
            cout << "平局!\n";
            break;
        }
    }
    Sleep(3000);
}

//打砖块
class Game {
private:
    int ballX, ballY;
    int ballDirX, ballDirY;
    int paddleX;
    bool bricks[BRICK_ROWS][BRICK_COLS];
    int score;
    bool gameOver;
    void init() {
        ballX = B_W/2;
        ballY = B_H/2;
        ballDirX = -1;
        ballDirY = -1;
        paddleX = B_W/2 - PADDLE_SIZE/2;
        score = 0;
        gameOver = false;
        for(int i=0; i<BRICK_ROWS; i++) {
            for(int j=0; j<BRICK_COLS; j++) {
                bricks[i][j] = true;
            }
        }
    }
    void draw() {
        fastcls();       
        // 绘制上边界
        for(int i=0; i<B_W+2; i++) cout << "#";
        cout << endl; 
        // 绘制游戏区域
        for(int i=0; i<B_H; i++) {
            for(int j=0; j<B_W; j++) {
                if(i == ballY && j == ballX) {
                    cout << "O";  // 球
                }
                else if(i == B_H-1 && j >= paddleX && j < paddleX+PADDLE_SIZE) {
                    cout << "=";  // 挡板
                }
                else if(i < BRICK_ROWS && bricks[i][j/5] && j%5 == 0) {
                    cout << "[";  // 砖块左半部分
                }
                else if(i < BRICK_ROWS && bricks[i][j/5] && j%5 == 4) {
                    cout << "]";  // 砖块右半部分
                }
                else {
                    cout << " ";
                }
            }
            cout << endl;
        }
        // 显示分数
        cout << "分数: " << score << endl;
    }
    void input() {
        if(_kbhit()) {
            switch(_getch()) {
                case 'a': paddleX = max(0, paddleX-2); break;
                case 'd': paddleX = min(B_W-PADDLE_SIZE, paddleX+2); break;
                case 'q': gameOver = true; break;
            }
        }
    }
    void update() {
        // 移动球
        ballX += ballDirX;
        ballY += ballDirY;
        // 墙壁碰撞
        if(ballX <= 0 || ballX >= B_W-1) ballDirX *= -1;
        if(ballY <= 0) ballDirY *= -1;
        // 挡板碰撞
        if(ballY >= B_H-1 && ballX >= paddleX && ballX < paddleX+PADDLE_SIZE) {
            ballDirY *= -1;
        }
        // 砖块碰撞
        if(ballY < BRICK_ROWS && ballY >= 0) {
            int brickRow = ballY;
            int brickCol = ballX/5;
            if(bricks[brickRow][brickCol]) {
                bricks[brickRow][brickCol] = false;
                ballDirY *= -1;
                score += 10;
            }
        }
        // 游戏结束条件
        if(ballY >= B_H) {
            gameOver = true;
        }
    }
public:
    Game() { init(); }
    void run() {
        while(!gameOver) {
            draw();
            input();
            update();
            Sleep(50);
        }
        system("cls");
        cout << "游戏结束! 最终分数: " << score << endl;
    }
};
void B_fightblock(){
    Game game;
    game.run();
    Sleep(3000);

//主菜单 
void menu() {
    while (true) {
        system("cls");
        if (!isLoggedIn) {
            bool isNewUser = false;
            char choice;
            cout << "欢迎使用c++游戏程序!" << endl;
            cout << "你是新用户吗?(Y/N): ";
            cin >> choice;
            system("cls");
            if (choice == 'Y' || choice == 'y') {
                registerUser();
                RUmessage();
                RUSbestscore();
                RUEbestscore();
                isNewUser = true;
            } else if (choice == 'N' || choice == 'n') {
                isLoggedIn = login();
            } else {
                cout << "无效输入,请重新选择。" << endl;
                Sleep(1000);
                system("cls");
            }
            if (isNewUser) {
                cout << "注册成功后自动登录游戏..." << endl;
                isLoggedIn = true; // 新用户注册后直接视为登录成功
                Sleep(500);
                system("cls");
            }
        } else {
            cout << "欢迎回来, " << username << "!" << endl;
        }
        if(!isLoggedIn) menu();
        int choose;
        cout << "1.五子棋对战" << endl;
        cout << "2.迷宫" << endl;
        cout << "3.贪吃蛇" << endl;
        cout << "4.俄罗斯方块" << endl;
        cout << "5.双人对打" << endl; 
        cout << "6.猜数字" << endl;
        cout << "7.井字棋AI" << endl;
        cout << "8.打砖块" << endl;
        cout << "9.我的" << endl;
        cout << "请输入你的选择:";
        cin >> choose;
        if (choose == 1) {
            w_fight();
        } else if (choose == 2) {
            maze();
        } else if (choose == 3){
            Snakes();
        } else if (choose == 4){
            E_block();
        } else if (choose == 5){
            p_fight();
        } else if (choose == 6){
            g_guessgame();
        } else if (choose == 7){
            J_AI();
        } else if (choose == 8){
            B_fightblock();
        } else if (choose==9){
            mine();
        } else {
            cout<<"无效输入!"<<endl;
            Sleep(1000);
            menu();
        }
    }
}

//开始主菜单
void menu_start(){
    //创建文件
    create1();
    create2();
    create3();
    create4();
    loadUserData(); // 加载用户名和密码 
    loadUserMassage(); // 加载用户钱币数 
    loadUser_s_Bestscore();
    loadUser_E_Bestscore();
    menu(); // 主菜单

//c++主函数 
int main(){
    menu_start();
    return 0;
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐