• 个人简介

    共有6个游戏代码给大家!

    第一个游戏代码是井字棋游戏

    第二个游戏代码是迷宫探险游戏

    第三个游戏代码是太空射击游戏

    第四个游戏代码是贪吃蛇游戏

    第五个游戏代码是五子棋游戏

    第六个游戏代码我还没研究出来,大家自己研究吧!

    游戏代码1:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <limits>
    using namespace std;
    vector<vector<char>> board(3, vector<char>(3, ' '));
    void DisplayBoard() {
        system("cls");
        cout << "  0   1   2" << endl;
        cout << "0 " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
        cout << " ---|---|---" << endl;
        cout << "1 " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
        cout << " ---|---|---" << endl;
        cout << "2 " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
    }
    bool CheckWin(char player) {
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == player && board[i][1] == player && board[i][2] == player)
                return true;
        }
        for (int j = 0; j < 3; j++) {
            if (board[0][j] == player && board[1][j] == player && board[2][j] == player)
                return true;
        }
        if (board[0][0] == player && board[1][1] == player && board[2][2] == player)
            return true;
        if (board[0][2] == player && board[1][1] == player && board[2][0] == player)
            return true;
        
        return false;
    }
    bool CheckDraw() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ')
                    return false;
            }
        }
        return true;
    }
    void AIMove() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = 'O';
                    if (CheckWin('O')) {
                        return;
                    }
                    board[i][j] = ' ';
                }
            }
        }
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = 'X';
                    if (CheckWin('X')) {
                        board[i][j] = 'O';
                        return;
                    }
                    board[i][j] = ' ';
                }
            }
        }
        if (board[1][1] == ' ') {
            board[1][1] = 'O';
            return;
        }
        vector<pair<int, int>> corners = {{0,0}, {0,2}, {2,0}, {2,2}};
        for (auto corner : corners) {
            if (board[corner.first][corner.second] == ' ') {
                board[corner.first][corner.second] = 'O';
                return;
            }
        }
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = 'O';
                    return;
                }
            }
        }
    }
    void PlayerMove() {
        int row, col;
        while (true) {
            cout << "输入你的移动 (行 列): ";
            cin >> row >> col;
            if (cin.fail()) {
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "无效输入,请使用数字0-2!" << endl;
                continue;
            }
            if (row < 0 || row > 2 || col < 0 || col > 2) {
                cout << "输入超出范围,请使用0-2!" << endl;
            } else if (board[row][col] != ' ') {
                cout << "该位置已被占用!" << endl;
            } else {
                board[row][col] = 'X';
                break;
            }
        }
    }
    void PlayGame(bool vsAI) {
        board = vector<vector<char>>(3, vector<char>(3, ' '));
        bool playerTurn = true;
        while (true) {
            DisplayBoard();
            if (CheckWin('X')) {
                cout << "玩家获胜!" << endl;
                break;
            } else if (CheckWin('O')) {
                cout << (vsAI ? "AI获胜!" : "玩家2获胜!") << endl;
                break;
            } else if (CheckDraw()) {
                cout << "平局!" << endl;
                break;
            }
            
            if (playerTurn) {
                cout << "玩家回合 (X)" << endl;
                PlayerMove();
            } else {
                cout << (vsAI ? "AI回合 (O)" : "玩家2回合 (O)") << endl;
                if (vsAI) {
                    AIMove();
                } else {
                    PlayerMove();
                }
            }
            
            playerTurn = !playerTurn;
        }
    }
    int main() {
        while (true) {
            system("cls");
            cout << "=== 井字棋游戏 ===" << endl;
            cout << "1. 玩家 vs 玩家" << endl;
            cout << "2. 玩家 vs AI" << endl;
            cout << "3. 退出" << endl;
            cout << "请选择: ";
            int choice;
            cin >> choice;
            if (cin.fail()) {
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                continue;
            }
            switch (choice) {
                case 1:
                    PlayGame(false);
                    break;
                case 2:
                    PlayGame(true);
                    break;
                case 3:
                    return 0;
                default:
                    cout << "无效选择!" << endl;
                    break;
            }
            cout << "按任意键继续..." << endl;
            cin.ignore();
            cin.get();
        }
        return 0;
    }
    
    

    游戏代码2:

    #include <iostream>
    #include <vector>
    #include <conio.h>
    #include <windows.h>
    #include <chrono>
    #include <cstdlib>
    #include <ctime>
    #include <algorithm>
    using namespace std;
    const int MAP_WIDTH = 30;
    const int MAP_HEIGHT = 15;
    const int MAX_ENEMIES = 5;
    const int MAX_TREASURES = 10;
    enum CellType { EMPTY, WALL, PLAYER, ENEMY, TREASURE, EXIT };
    enum Direction { UP, DOWN, LEFT, RIGHT };
    struct GameObject {
        int x, y;
        int health;
        int attack;
    };
    struct GameState {
        vector<vector<CellType>> map;
        GameObject player;
        vector<GameObject> enemies;
        vector<pair<int, int>> treasures;
        pair<int, int> exit;
        int score;
        bool gameOver;
        bool win;
    } game;
    void GenerateMap() {
        game.map = vector<vector<CellType>>(MAP_HEIGHT, vector<CellType>(MAP_WIDTH, EMPTY));
        for (int y = 0; y < MAP_HEIGHT; y++) {
            game.map[y][0] = WALL;
            game.map[y][MAP_WIDTH-1] = WALL;
        }
        for (int x = 0; x < MAP_WIDTH; x++) {
            game.map[0][x] = WALL;
            game.map[MAP_HEIGHT-1][x] = WALL;
        }
        for (int y = 1; y < MAP_HEIGHT-1; y++) {
            for (int x = 1; x < MAP_WIDTH-1; x++) {
                if (rand() % 5 == 0) game.map[y][x] = WALL;
            }
        }
        game.exit = {MAP_HEIGHT-2, MAP_WIDTH-2};
        game.map[game.exit.first][game.exit.second] = EXIT;
        game.player = {1, 1, 100, 10};
        game.map[1][1] = PLAYER;
        for (int i = 0; i < MAX_TREASURES; ) {
            int x = 1 + rand() % (MAP_WIDTH-2);
            int y = 1 + rand() % (MAP_HEIGHT-2);
            if (game.map[y][x] == EMPTY) {
                game.treasures.push_back({x, y});
                game.map[y][x] = TREASURE;
                i++;
            }
        }
        for (int i = 0; i < MAX_ENEMIES; ) {
            int x = 1 + rand() % (MAP_WIDTH-2);
            int y = 1 + rand() % (MAP_HEIGHT-2);
            if (game.map[y][x] == EMPTY) {
                game.enemies.push_back({x, y, 30, 5});
                game.map[y][x] = ENEMY;
                i++;
            }
        }
    }
    void DrawMap() {
        system("cls");
        const int COLORS[] = {
            0x07,
            0x88,
            0x0A,
            0x0C,
            0x0E,
            0x0B
        };
        for (int y = 0; y < MAP_HEIGHT; y++) {
            for (int x = 0; x < MAP_WIDTH; x++) {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), COLORS[game.map[y][x]]);
                switch (game.map[y][x]) {
                    case EMPTY: cout << " "; break;
                    case WALL: cout << "#"; break;
                    case PLAYER: cout << "P"; break;
                    case ENEMY: cout << "E"; break;
                    case TREASURE: cout << "$"; break;
                    case EXIT: cout << "X"; break;
                }
            }
            cout << endl;
        }
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
        cout << "生命: " << game.player.health << " | 攻击: " << game.player.attack 
             << " | 分数: " << game.score << endl;
        cout << "WASD移动, 空格攻击, Q退出" << endl;
    }
    bool IsValidMove(int x, int y) {
        if (x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT)
            return false;
        return game.map[y][x] != WALL;
    }
    void MovePlayer(Direction dir) {
        int dx = 0, dy = 0;
        switch (dir) {
            case UP: dy = -1; break;
            case DOWN: dy = 1; break;
            case LEFT: dx = -1; break;
            case RIGHT: dx = 1; break;
        }
        int newX = game.player.x + dx;
        int newY = game.player.y + dy;
        if (IsValidMove(newX, newY)) {
            switch (game.map[newY][newX]) {
                case TREASURE:
                    game.score += 50;
                    game.treasures.erase(
                        remove_if(game.treasures.begin(), game.treasures.end(), 
                            [&](const pair<int,int>& t) { return t.first == newX && t.second == newY; }),
                        game.treasures.end()
                    );
                    break;
                case ENEMY:
                    return;
                case EXIT:
                    if (game.treasures.empty()) {
                        game.win = true;
                        game.gameOver = true;
                    }
                    return;
            }
            game.map[game.player.y][game.player.x] = EMPTY;
            game.player.x = newX;
            game.player.y = newY;
            game.map[game.player.y][game.player.x] = PLAYER;
        }
    }
    void AttackEnemy() {
        int directions[4][2] = {{0,-1}, {0,1}, {-1,0}, {1,0}};
        for (int i = 0; i < 4; i++) {
            int x = game.player.x + directions[i][0];
            int y = game.player.y + directions[i][1];
            if (x >= 0 && x < MAP_WIDTH && y >= 0 && y < MAP_HEIGHT && 
                game.map[y][x] == ENEMY) {
                for (auto& enemy : game.enemies) {
                    if (enemy.x == x && enemy.y == y) {
                        enemy.health -= game.player.attack;
                        if (enemy.health <= 0) {
                            game.map[y][x] = EMPTY;
                            enemy.health = 0;
                            game.score += 100;
                        }
                        if (enemy.health > 0) {
                            game.player.health -= enemy.attack;
                            if (game.player.health <= 0) {
                                game.player.health = 0;
                                game.gameOver = true;
                            }
                        }
                        return;
                    }
                }
            }
        }
    }
    void MoveEnemies() {
        for (auto& enemy : game.enemies) {
            if (enemy.health <= 0) continue;
            int dir = rand() % 4;
            int dx = 0, dy = 0;
            switch (dir) {
                case 0: dy = -1; break;
                case 1: dy = 1; break;
                case 2: dx = -1; break;
                case 3: dx = 1; break;
            }
            int newX = enemy.x + dx;
            int newY = enemy.y + dy;
            if (IsValidMove(newX, newY) && game.map[newY][newX] == EMPTY) {
                game.map[enemy.y][enemy.x] = EMPTY;
                enemy.x = newX;
                enemy.y = newY;
                game.map[enemy.y][enemy.x] = ENEMY;
            }
        }
    }
    int main() {
        srand(static_cast<unsigned>(time(0)));
        GenerateMap();
        game.score = 0;
        game.gameOver = false;
        game.win = false;
        CONSOLE_CURSOR_INFO cursorInfo;
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = FALSE;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
        while (!game.gameOver) {
            DrawMap();
            if (_kbhit()) {
                switch (tolower(_getch())) {
                    case 'w': MovePlayer(UP); break;
                    case 's': MovePlayer(DOWN); break;
                    case 'a': MovePlayer(LEFT); break;
                    case 'd': MovePlayer(RIGHT); break;
                    case ' ': AttackEnemy(); break;
                    case 'q': game.gameOver = true; break;
                }
            }
            static int frameCount = 0;
            if (++frameCount % 5 == 0) {
                MoveEnemies();
            }
            game.enemies.erase(
                remove_if(game.enemies.begin(), game.enemies.end(),
                    [](const GameObject& e) { return e.health <= 0; }),
                game.enemies.end()
            );
            Sleep(100);
        }
        system("cls");
        if (game.win) {
            cout << "恭喜通关!最终分数: " << game.score << endl;
        } else {
            cout << "游戏结束!最终分数: " << game.score << endl;
        }
        cout << "按任意键退出..." << endl;
        _getch();
        return 0;
    }
    
    

    游戏代码3:

    #include <iostream>
    #include <vector>
    #include <conio.h>
    #include <windows.h>
    #include <chrono>
    #include <cstdlib>
    #include <ctime>
    #include <algorithm>
    using namespace std;
    const int WIDTH = 40;
    const int HEIGHT = 20;
    const int PLAYER_SPEED = 2;
    const int BULLET_SPEED = 1;
    const int ENEMY_SPEED = 1;
    struct GameObject {
        int x, y;
        bool active;
    };
    struct GameState {
        GameObject player;
        vector<GameObject> bullets;
        vector<GameObject> enemies;
        int score;
        int lives;
        bool gameOver;
        chrono::system_clock::time_point lastEnemySpawn;
    } game;
    void InitGame() {
        game = GameState();
        game.player = {WIDTH/2, HEIGHT-2, true};
        game.score = 0;
        game.lives = 3;
        game.gameOver = false;
        game.lastEnemySpawn = chrono::system_clock::now();
    }
    void DrawGame() {
        system("cls");
        for (int i = 0; i < WIDTH+2; i++) cout << "#";
        cout << endl;
        for (int y = 0; y < HEIGHT; y++) {
            for (int x = 0; x < WIDTH; x++) {
                if (x == 0) cout << "#"; 
                bool drawn = false;
                if (x == game.player.x && y == game.player.y) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
                    cout << "A";
                    drawn = true;
                }
                if (!drawn) {
                    for (auto& bullet : game.bullets) {
                        if (bullet.active && x == bullet.x && y == bullet.y) {
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);
                            cout << "|";
                            drawn = true;
                            break;
                        }
                    }
                }
                if (!drawn) {
                    for (auto& enemy : game.enemies) {
                        if (enemy.active && x == enemy.x && y == enemy.y) {
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
                            cout << "V";
                            drawn = true;
                            break;
                        }
                    }
                }
                if (!drawn) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
                    cout << " ";
                }
                
                if (x == WIDTH-1) cout << "#";
            }
            cout << endl;
        }
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
        for (int i = 0; i < WIDTH+2; i++) cout << "#";
        cout << endl;
        cout << "分数: " << game.score << " | 生命: ";
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
        for (int i = 0; i < game.lives; i++) cout << "♥ ";
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
        cout << "| WASD移动 空格射击";
    }
    void SpawnEnemy() {
        auto now = chrono::system_clock::now();
        if (chrono::duration_cast<chrono::milliseconds>(
            now - game.lastEnemySpawn).count() > 1500) {
            game.enemies.push_back({rand() % (WIDTH-2), 1, true});
            game.lastEnemySpawn = now;
        }
    }
    void UpdateBullets() {
        for (auto& bullet : game.bullets) {
            if (bullet.active) {
                bullet.y -= BULLET_SPEED;
                if (bullet.y < 0) bullet.active = false;
                for (auto& enemy : game.enemies) {
                    if (enemy.active && 
                        bullet.x == enemy.x && 
                        bullet.y == enemy.y) {
                        bullet.active = false;
                        enemy.active = false;
                        game.score += 10;
                        break;
                    }
                }
            }
        }
        game.bullets.erase(
            remove_if(game.bullets.begin(), game.bullets.end(), 
                [](const GameObject& b) { return !b.active; }),
            game.bullets.end()
        );
    }
    void UpdateEnemies() {
        for (auto& enemy : game.enemies) {
            if (enemy.active) {
                enemy.y += ENEMY_SPEED;
                if (enemy.y >= HEIGHT) {
                    enemy.active = false;
                    game.lives--;
                    if (game.lives <= 0) game.gameOver = true;
                }
                if (enemy.x == game.player.x && 
                    enemy.y == game.player.y) {
                    enemy.active = false;
                    game.lives--;
                    if (game.lives <= 0) game.gameOver = true;
                }
            }
        }
        game.enemies.erase(
            remove_if(game.enemies.begin(), game.enemies.end(), 
                [](const GameObject& e) { return !e.active; }),
            game.enemies.end()
        );
    }
    void ProcessInput() {
        if (_kbhit()) {
            switch (_getch()) {
                case 'a': 
                    if (game.player.x > 0) game.player.x -= PLAYER_SPEED; 
                    break;
                case 'd': 
                    if (game.player.x < WIDTH-1) game.player.x += PLAYER_SPEED; 
                    break;
                case 'w': 
                    if (game.player.y > 0) game.player.y -= PLAYER_SPEED; 
                    break;
                case 's': 
                    if (game.player.y < HEIGHT-1) game.player.y += PLAYER_SPEED; 
                    break;
                case ' ':
                    game.bullets.push_back({game.player.x, game.player.y-1, true});
                    break;
                case 27:
                    game.gameOver = true;
                    break;
            }
        }
    }
    int main() {
        srand(static_cast<unsigned>(time(0)));
        InitGame();
        CONSOLE_CURSOR_INFO cursorInfo;
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = FALSE;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
        while (!game.gameOver) {
            ProcessInput();
            SpawnEnemy();
            UpdateBullets();
            UpdateEnemies();
            DrawGame();
            Sleep(50);
        }
        system("cls");
        cout << "游戏结束! 最终分数: " << game.score << endl;
        cout << "按任意键退出...";
        _getch();
        return 0;
    }
    
    

    游戏代码4:

    #include <iostream>
    #include <vector>
    #include <conio.h>
    #include <windows.h>
    #include <cstdlib>
    #include <ctime>
    #include <deque>
    #include <algorithm>
    using namespace std;
    const int WIDTH = 30;
    const int HEIGHT = 20;
    const int BASE_SPEED = 150;
    enum Direction { UP, DOWN, LEFT, RIGHT };
    enum GameMode { PLAYER, AI_BATTLE };
    struct Point { int x, y; };
    struct GameState {
        deque<Point> snake;
        deque<Point> aiSnake;
        Point food;
        Point aiFood;
        Direction dir;
        Direction aiDir;
        int score;
        int aiScore;
        bool gameOver;
        GameMode mode;
    } game;
    void InitGame(GameMode mode) {
        game.snake = {{WIDTH/2, HEIGHT/2}};
        game.aiSnake = {{WIDTH/4, HEIGHT/2}};
        game.dir = RIGHT;
        game.aiDir = RIGHT;
        game.score = 0;
        game.aiScore = 0;
        game.gameOver = false;
        game.mode = mode;
        game.food.x = rand() % WIDTH;
        game.food.y = rand() % HEIGHT;
        if(mode == AI_BATTLE) {
            game.aiFood.x = rand() % WIDTH;
            game.aiFood.y = rand() % HEIGHT;
        }
    }
    void DrawGame() {
        system("cls");   
        for (int i = 0; i < WIDTH + 2; i++) cout << "#";
        cout << endl;
        for (int y = 0; y < HEIGHT; y++) {
            for (int x = 0; x < WIDTH; x++) {
                if (x == 0) cout << "#";
                bool drawn = false;
                if (x == game.snake.front().x && y == game.snake.front().y) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
                    cout << "O";
                    drawn = true;
                }
                for (auto it = game.snake.begin()+1; it != game.snake.end() && !drawn; it++) {
                    if (x == it->x && y == it->y) {
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
                        cout << "o";
                        drawn = true;
                    }
                }
                if (game.mode == AI_BATTLE && !drawn) {
                    if (x == game.aiSnake.front().x && y == game.aiSnake.front().y) {
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
                        cout << "A";
                        drawn = true;
                    }   
                    for (auto it = game.aiSnake.begin()+1; it != game.aiSnake.end() && !drawn; it++) {
                        if (x == it->x && y == it->y) {
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 4);
                            cout << "a";
                            drawn = true;
                        }
                    }
                }
                if (!drawn && x == game.food.x && y == game.food.y) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);
                    cout << "*";
                    drawn = true;
                }
                if (game.mode == AI_BATTLE && !drawn && x == game.aiFood.x && y == game.aiFood.y) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
                    cout << "@";
                    drawn = true;
                }
                if (!drawn) cout << " ";
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
                if (x == WIDTH-1) cout << "#";
            }
            cout << endl;
        }
        for (int i = 0; i < WIDTH + 2; i++) cout << "#";
        cout << endl;
        cout << "玩家分数: " << game.score;
        if(game.mode == AI_BATTLE) cout << " | AI分数: " << game.aiScore;
        cout << endl;
        cout << "WASD移动, P暂停, R重新开始, Q退出" << endl;
    }
    void AIMove() {
        Point head = game.aiSnake.front();   
        if (head.x < game.aiFood.x && game.aiDir != LEFT) {
            game.aiDir = RIGHT;
        } else if (head.x > game.aiFood.x && game.aiDir != RIGHT) {
            game.aiDir = LEFT;
        } else if (head.y < game.aiFood.y && game.aiDir != UP) {
            game.aiDir = DOWN;
        } else if (head.y > game.aiFood.y && game.aiDir != DOWN) {
            game.aiDir = UP;
        }
        Point newHead = head;
        switch (game.aiDir) {
            case UP: newHead.y--; break;
            case DOWN: newHead.y++; break;
            case LEFT: newHead.x--; break;
            case RIGHT: newHead.x++; break;
        }
        if (newHead.x < 0) newHead.x = WIDTH-1;
        if (newHead.x >= WIDTH) newHead.x = 0;
        if (newHead.y < 0) newHead.y = HEIGHT-1;
        if (newHead.y >= HEIGHT) newHead.y = 0;
        for (auto it = game.aiSnake.begin(); it != game.aiSnake.end(); it++) {
            if (newHead.x == it->x && newHead.y == it->y) {
                return;
            }
        }
        game.aiSnake.push_front(newHead);
        if (newHead.x == game.aiFood.x && newHead.y == game.aiFood.y) {
            game.aiScore += 10;
            game.aiFood.x = rand() % WIDTH;
            game.aiFood.y = rand() % HEIGHT;
        } else {
            game.aiSnake.pop_back();
        }
    }
    void UpdateGame() {
        if (game.gameOver) return;   
        Point head = game.snake.front();
        Point newHead = head;
        switch (game.dir) {
            case UP: newHead.y--; break;
            case DOWN: newHead.y++; break;
            case LEFT: newHead.x--; break;
            case RIGHT: newHead.x++; break;
        }
        if (newHead.x < 0) newHead.x = WIDTH-1;
        if (newHead.x >= WIDTH) newHead.x = 0;
        if (newHead.y < 0) newHead.y = HEIGHT-1;
        if (newHead.y >= HEIGHT) newHead.y = 0;
        for (auto it = game.snake.begin(); it != game.snake.end(); it++) {
            if (newHead.x == it->x && newHead.y == it->y) {
                game.gameOver = true;
                return;
            }
        }
        game.snake.push_front(newHead);
        if (newHead.x == game.food.x && newHead.y == game.food.y) {
            game.score += 10;
            game.food.x = rand() % WIDTH;
            game.food.y = rand() % HEIGHT;
        } else {
            game.snake.pop_back();
        }
        if (game.mode == AI_BATTLE) {
            AIMove();   
            for (auto s : game.snake) {
                if (game.aiSnake.front().x == s.x && game.aiSnake.front().y == s.y) {
                    game.aiScore -= 5;
                    game.aiSnake.pop_back();
                    if (game.aiSnake.empty()) {
                        game.gameOver = true;
                    }
                    break;
                }
            }
            for (auto a : game.aiSnake) {
                if (game.snake.front().x == a.x && game.snake.front().y == a.y) {
                    game.score -= 5;
                    game.snake.pop_back();
                    if (game.snake.empty()) {
                        game.gameOver = true;
                    }
                    break;
                }
            }
        }
    }
    void ProcessInput() {
        if (_kbhit()) {
            switch (_getch()) {
                case 'w': if (game.dir != DOWN) game.dir = UP; break;
                case 's': if (game.dir != UP) game.dir = DOWN; break;
                case 'a': if (game.dir != RIGHT) game.dir = LEFT; break;
                case 'd': if (game.dir != LEFT) game.dir = RIGHT; break;
                case 'p': 
                    cout << "游戏暂停,按任意键继续...";
                    _getch();
                    break;
                case 'r': InitGame(game.mode); break;
                case 'q': game.gameOver = true; break;
            }
        }
    }
    int main() {
        srand(static_cast<unsigned>(time(0)));   
        cout << "选择模式:\n1. 单人模式\n2. AI对战模式\n选择: ";
        int choice;
        cin >> choice;
        GameMode mode = (choice == 2) ? AI_BATTLE : PLAYER;
        InitGame(mode);
        CONSOLE_CURSOR_INFO cursorInfo;
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = FALSE;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
        while (!game.gameOver) {
            DrawGame();
            ProcessInput();
            UpdateGame();
            Sleep(BASE_SPEED);
        }
        DrawGame();
        cout << "游戏结束! 最终分数: " << game.score;
        if(mode == AI_BATTLE) cout << " | AI分数: " << game.aiScore;
        cout << endl;
        return 0;
    }
    
    

    游戏代码5:

    #include <iostream>
    #include <vector>
    #include <conio.h>
    #include <windows.h>
    #include <limits>
    #include <algorithm>
    using namespace std;
    
    const int BOARD_SIZE = 15;
    const int WIN_COUNT = 5;
    
    enum Player { NONE, HUMAN, AI };
    
    struct Game {
        vector<vector<Player>> board;
        Player currentPlayer;
        bool gameOver;
        bool vsAI;
        int cursorX, cursorY;
    };
    
    Game game;
    
    void InitGame(bool aiMode) {
        game.board.clear();
        game.board.resize(BOARD_SIZE, vector<Player>(BOARD_SIZE, NONE));
        game.currentPlayer = HUMAN;
        game.gameOver = false;
        game.vsAI = aiMode;
        game.cursorX = BOARD_SIZE / 2;
        game.cursorY = BOARD_SIZE / 2;
    }
    
    void DrawBoard() {
        system("cls");
        
        // 绘制列号
        cout << "   ";
        for (int j = 0; j < BOARD_SIZE; j++) {
            cout << (j < 10 ? " " : "") << j << " ";
        }
        cout << endl;
        
        // 绘制上边框
        cout << "  +";
        for (int j = 0; j < BOARD_SIZE; j++) cout << "---";
        cout << "-+" << endl;
        
        // 绘制棋盘
        for (int i = 0; i < BOARD_SIZE; i++) {
            cout << (i < 10 ? " " : "") << i << "|";
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (i == game.cursorY && j == game.cursorX && 
                    (game.currentPlayer == HUMAN || !game.vsAI)) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 112); // 反色
                }
                
                if (game.board[i][j] == HUMAN) {
                    cout << " ●";
                } else if (game.board[i][j] == AI) {
                    cout << " ○";
                } else {
                    cout << " ·";
                }
                
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
            }
            cout << " |" << endl;
        }
        
        // 绘制下边框
        cout << "  +";
        for (int j = 0; j < BOARD_SIZE; j++) cout << "---";
        cout << "-+" << endl;
        
        // 显示游戏信息
        cout << "当前玩家: " << (game.currentPlayer == HUMAN ? "玩家(●)" : "AI(○)") << endl;
        cout << "操作: WASD移动, 空格落子, Q退出" << endl;
    }
    
    bool CheckWin(int x, int y) {
        if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) return false;
        if (game.board[y][x] == NONE) return false;
    
        Player player = game.board[y][x];
        int directions[4][2] = {{1,0}, {0,1}, {1,1}, {1,-1}};
        
        for (auto dir : directions) {
            int count = 1;
            
            // 正向检查
            for (int i = 1; i < WIN_COUNT; i++) {
                int nx = x + dir[0] * i;
                int ny = y + dir[1] * i;
                if (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE && 
                    game.board[ny][nx] == player) {
                    count++;
                } else {
                    break;
                }
            }
            
            // 反向检查
            for (int i = 1; i < WIN_COUNT; i++) {
                int nx = x - dir[0] * i;
                int ny = y - dir[1] * i;
                if (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE && 
                    game.board[ny][nx] == player) {
                    count++;
                } else {
                    break;
                }
            }
            
            if (count >= WIN_COUNT) {
                return true;
            }
        }
        
        return false;
    }
    
    int EvaluatePosition(int x, int y, Player player) {
        if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || game.board[y][x] != NONE) {
            return 0;
        }
    
        int score = 0;
        int directions[4][2] = {{1,0}, {0,1}, {1,1}, {1,-1}};
    
        for (auto dir : directions) {
            int playerCount = 0;
            int emptyCount = 0;
            int opponentCount = 0;
    
            for (int i = -4; i <= 4; i++) {
                if (i == 0) continue;
                int nx = x + dir[0] * i;
                int ny = y + dir[1] * i;
                
                if (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE) {
                    if (game.board[ny][nx] == player) {
                        playerCount++;
                    } else if (game.board[ny][nx] == NONE) {
                        emptyCount++;
                    } else {
                        opponentCount++;
                    }
                }
            }
    
            // 评分规则
            if (playerCount >= 4) score += 10000;       // 四连
            else if (playerCount == 3 && emptyCount >= 1) score += 1000;  // 活三
            else if (playerCount == 2 && emptyCount >= 2) score += 100;  // 活二
            else if (playerCount == 1 && emptyCount >= 3) score += 10;    // 活一
    
            // 防守评分
            if (opponentCount >= 4) score += 5000;      // 阻挡对手四连
            else if (opponentCount == 3 && emptyCount >= 1) score += 500; // 阻挡活三
            else if (opponentCount == 2 && emptyCount >= 2) score += 50;  // 阻挡活二
        }
    
        // 中心位置加分
        int centerX = BOARD_SIZE / 2;
        int centerY = BOARD_SIZE / 2;
        score += 5 * (BOARD_SIZE - abs(x - centerX) - abs(y - centerY));
    
        return score;
    }
    
    void AIMove() {
        int bestScore = -1;
        int bestX = -1;
        int bestY = -1;
    
        // 遍历所有空位
        for (int y = 0; y < BOARD_SIZE; y++) {
            for (int x = 0; x < BOARD_SIZE; x++) {
                if (game.board[y][x] == NONE) {
                    // 计算进攻得分
                    int attackScore = EvaluatePosition(x, y, AI);
                    // 计算防守得分
                    int defendScore = EvaluatePosition(x, y, HUMAN);
                    // 总分为进攻和防守的加权
                    int totalScore = attackScore * 2 + defendScore;
                    
                    if (totalScore > bestScore) {
                        bestScore = totalScore;
                        bestX = x;
                        bestY = y;
                    }
                }
            }
        }
    
        // 落子
        if (bestX != -1 && bestY != -1) {
            game.board[bestY][bestX] = AI;
            if (CheckWin(bestX, bestY)) {
                game.gameOver = true;
            } else {
                game.currentPlayer = HUMAN;
            }
        }
    }
    
    void ProcessInput() {
        if (_kbhit()) {
            switch (_getch()) {
                case 'w': 
                    if (game.cursorY > 0) game.cursorY--;
                    break;
                case 's':
                    if (game.cursorY < BOARD_SIZE-1) game.cursorY++;
                    break;
                case 'a':
                    if (game.cursorX > 0) game.cursorX--;
                    break;
                case 'd':
                    if (game.cursorX < BOARD_SIZE-1) game.cursorX++;
                    break;
                case ' ':
                    if (game.board[game.cursorY][game.cursorX] == NONE && 
                        (game.currentPlayer == HUMAN || !game.vsAI)) {
                        game.board[game.cursorY][game.cursorX] = game.currentPlayer;
                        if (CheckWin(game.cursorX, game.cursorY)) {
                            game.gameOver = true;
                        } else {
                            game.currentPlayer = (game.currentPlayer == HUMAN) ? AI : HUMAN;
                        }
                    }
                    break;
                case 'q':
                    game.gameOver = true;
                    break;
            }
        }
    }
    
    void PlayGame(bool aiMode) {
        InitGame(aiMode);
        
        // 隐藏光标
        CONSOLE_CURSOR_INFO cursorInfo;
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = FALSE;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
        
        while (!game.gameOver) {
            DrawBoard();
            
            if (game.currentPlayer == HUMAN || !game.vsAI) {
                ProcessInput();
            } else {
                AIMove();
                Sleep(500); // AI思考时间
            }
        }
        
        DrawBoard();
        if (game.currentPlayer == HUMAN || game.currentPlayer == AI) {
            cout << "游戏结束! " << (game.currentPlayer == HUMAN ? "玩家" : "AI") << "获胜!" << endl;
        }
        cout << "按任意键返回..." << endl;
        _getch();
    }
    
    int main() {
        while (true) {
            system("cls");
            cout << "=== 五子棋游戏 ===" << endl;
            cout << "1. 玩家 vs 玩家" << endl;
            cout << "2. 玩家 vs AI" << endl;
            cout << "3. 退出" << endl;
            cout << "请选择: ";
            
            char choice;
            cin >> choice;
            
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            
            switch (choice) {
                case '1':
                    PlayGame(false);
                    break;
                case '2':
                    PlayGame(true);
                    break;
                case '3':
                    return 0;
                default:
                    cout << "无效输入,请重新选择!" << endl;
                    Sleep(1000);
                    break;
            }
        }
    }
    
    

    游戏代码6:

    #include <iostream>
    #include <vector>
    #include <conio.h>
    #include <windows.h>
    #include <cstdlib>
    #include <ctime>
    #include <map>
    using namespace std;
    
    // ===== 游戏配置 =====
    const int WIDTH = 40;
    const int HEIGHT = 20;
    const int MAX_LEVEL = 10;
    
    // ===== 游戏对象 =====
    enum TileType { EMPTY, WALL, DOOR, STAIRS };
    enum EntityType { PLAYER, ENEMY, ITEM };
    enum ItemType { WEAPON, ARMOR, POTION };
    
    struct Tile {
        TileType type;
        bool explored;
    };
    
    struct Entity {
        int x, y;
        char symbol;
        string name;
        int health;
        int maxHealth;
        int attack;
        int defense;
        int level;
        int exp;
        EntityType type;
        ItemType itemType; // 仅对物品有效
        int value; // 攻击力/防御力/恢复量
    };
    
    struct GameState {
        vector<vector<Tile>> map;
        Entity player;
        vector<Entity> enemies;
        vector<Entity> items;
        int currentLevel;
        bool gameOver;
    } game;
    
    // ===== 地图生成 =====
    void GenerateMap() {
        game.map.clear();
        game.map.resize(HEIGHT, vector<Tile>(WIDTH, {WALL, false}));
    
        // 随机生成房间和走廊
        for (int y = 1; y < HEIGHT-1; y++) {
            for (int x = 1; x < WIDTH-1; x++) {
                if (rand() % 3 > 0) { // 66%概率生成空地
                    game.map[y][x].type = EMPTY;
                }
            }
        }
    
        // 放置楼梯
        int stairsX = rand() % (WIDTH-2) + 1;
        int stairsY = rand() % (HEIGHT-2) + 1;
        game.map[stairsY][stairsX].type = STAIRS;
    }
    
    // ===== 生成敌人和物品 =====
    void GenerateEntities() {
        game.enemies.clear();
        game.items.clear();
    
        // 生成敌人(数量随关卡增加)
        int enemyCount = 3 + game.currentLevel;
        for (int i = 0; i < enemyCount; i++) {
            int x = rand() % (WIDTH-2) + 1;
            int y = rand() % (HEIGHT-2) + 1;
            if (game.map[y][x].type == EMPTY) {
                Entity enemy = {x, y, 'M', "怪物", 10 + game.currentLevel * 2, 
                               10 + game.currentLevel * 2, 2 + game.currentLevel, 
                               1 + game.currentLevel, 0, 0, ENEMY};
                game.enemies.push_back(enemy);
            }
        }
    
        // 生成物品(武器/护甲/药水)
        int itemCount = 2 + rand() % 3;
        for (int i = 0; i < itemCount; i++) {
            int x = rand() % (WIDTH-2) + 1;
            int y = rand() % (HEIGHT-2) + 1;
            if (game.map[y][x].type == EMPTY) {
                ItemType type = static_cast<ItemType>(rand() % 3);
                Entity item = {x, y, 
                              (type == WEAPON ? '!' : (type == ARMOR ? '[' : '~')), 
                              (type == WEAPON ? "武器" : (type == ARMOR ? "护甲" : "药水")),
                              0, 0, 0, 0, 0, 0, ITEM, type, 
                              (type == POTION ? 10 : 1 + game.currentLevel)};
                game.items.push_back(item);
            }
        }
    }
    
    // ===== 初始化游戏 =====
    void InitGame() {
        srand(static_cast<unsigned>(time(0)));
        game.currentLevel = 1;
        game.gameOver = false;
    
        // 初始化玩家
        game.player = {WIDTH/2, HEIGHT/2, '@', "冒险家", 20, 20, 3, 1, 1, 0, PLAYER};
        
        GenerateMap();
        GenerateEntities();
    }
    
    // ===== 绘制游戏 =====
    void DrawGame() {
        system("cls");
        
        // 绘制地图
        for (int y = 0; y < HEIGHT; y++) {
            for (int x = 0; x < WIDTH; x++) {
                if (game.player.x == x && game.player.y == y) {
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
                    cout << game.player.symbol;
                } else {
                    bool drawn = false;
                    
                    // 绘制敌人
                    for (auto& enemy : game.enemies) {
                        if (enemy.x == x && enemy.y == y) {
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
                            cout << enemy.symbol;
                            drawn = true;
                            break;
                        }
                    }
                    
                    // 绘制物品
                    if (!drawn) {
                        for (auto& item : game.items) {
                            if (item.x == x && item.y == y) {
                                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 
                                                      (item.itemType == POTION ? 13 : 14));
                                cout << item.symbol;
                                drawn = true;
                                break;
                            }
                        }
                    }
                    
                    // 绘制地图
                    if (!drawn) {
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 8);
                        switch (game.map[y][x].type) {
                            case WALL: cout << "#"; break;
                            case STAIRS: cout << ">"; break;
                            default: cout << " ";
                        }
                    }
                }
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
            }
            cout << endl;
        }
        
        // 显示状态信息
        cout << "等级:" << game.player.level << " 生命:" << game.player.health << "/" 
             << game.player.maxHealth << " 攻击:" << game.player.attack << " 防御:" 
             << game.player.defense << " 经验:" << game.player.exp << "/" 
             << (game.player.level * 10) << endl;
        cout << "操作: WASD移动, E交互, Q退出 | 当前楼层:" << game.currentLevel << endl;
    }
    
    // ===== 敌人AI =====
    void UpdateEnemies() {
        for (auto& enemy : game.enemies) {
            // 简单追踪AI
            int dx = 0, dy = 0;
            if (enemy.x < game.player.x) dx = 1;
            else if (enemy.x > game.player.x) dx = -1;
            
            if (enemy.y < game.player.y) dy = 1;
            else if (enemy.y > game.player.y) dy = -1;
            
            // 检查移动是否合法
            int newX = enemy.x + dx;
            int newY = enemy.y + dy;
            if (game.map[newY][newX].type != WALL) {
                enemy.x = newX;
                enemy.y = newY;
            }
            
            // 攻击玩家
            if (enemy.x == game.player.x && enemy.y == game.player.y) {
                int damage = max(1, enemy.attack - game.player.defense);
                game.player.health -= damage;
                cout << enemy.name << "对你造成了" << damage << "点伤害!" << endl;
                Sleep(500);
            }
        }
    }
    
    // ===== 处理输入 =====
    void ProcessInput() {
        if (_kbhit()) {
            int dx = 0, dy = 0;
            switch (_getch()) {
                case 'w': dy = -1; break;
                case 's': dy = 1; break;
                case 'a': dx = -1; break;
                case 'd': dx = 1; break;
                case 'e': // 交互(捡物品/使用楼梯)
                    for (auto it = game.items.begin(); it != game.items.end(); ) {
                        if (it->x == game.player.x && it->y == game.player.y) {
                            switch (it->itemType) {
                                case WEAPON:
                                    game.player.attack += it->value;
                                    cout << "获得了" << it->name << "!攻击力+" << it->value << endl;
                                    break;
                                case ARMOR:
                                    game.player.defense += it->value;
                                    cout << "获得了" << it->name << "!防御力+" << it->value << endl;
                                    break;
                                case POTION:
                                    game.player.health = min(game.player.maxHealth, 
                                                           game.player.health + it->value);
                                    cout << "使用了" << it->name << "!恢复" << it->value << "点生命" << endl;
                                    break;
                            }
                            it = game.items.erase(it);
                            Sleep(500);
                        } else {
                            ++it;
                        }
                    }
                    
                    // 检查楼梯
                    if (game.map[game.player.y][game.player.x].type == STAIRS) {
                        game.currentLevel++;
                        if (game.currentLevel > MAX_LEVEL) {
                            game.gameOver = true;
                            cout << "恭喜你通关了地牢!" << endl;
                        } else {
                            GenerateMap();
                            GenerateEntities();
                            game.player.health = min(game.player.maxHealth, 
                                                  game.player.health + 5); // 恢复一些生命
                        }
                    }
                    return;
                case 'q':
                    game.gameOver = true;
                    return;
            }
            
            // 移动玩家
            int newX = game.player.x + dx;
            int newY = game.player.y + dy;
            if (game.map[newY][newX].type != WALL) {
                game.player.x = newX;
                game.player.y = newY;
            }
        }
    }
    
    // ===== 主游戏循环 =====
    int main() {
        InitGame();
        
        // 隐藏光标
        CONSOLE_CURSOR_INFO cursorInfo;
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = FALSE;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
        
        while (!game.gameOver) {
            DrawGame();
            ProcessInput();
            
            // 检查战斗
            for (auto it = game.enemies.begin(); it != game.enemies.end(); ) {
                if (it->x == game.player.x && it->y == game.player.y) {
                    int damage = max(1, game.player.attack - it->defense);
                    it->health -= damage;
                    cout << "你对" << it->name << "造成了" << damage << "点伤害!" << endl;
                    Sleep(500);
                    
                    if (it->health <= 0) {
                        game.player.exp += it->level * 2;
                        cout << "击败了" << it->name << "!获得" << (it->level * 2) << "经验" << endl;
                        it = game.enemies.erase(it);
                        
                        // 检查升级
                        if (game.player.exp >= game.player.level * 10) {
                            game.player.level++;
                            game.player.maxHealth += 5;
                            game.player.health = game.player.maxHealth;
                            game.player.attack++;
                            game.player.defense++;
                            game.player.exp = 0;
                            cout << "升级了!现在等级:" << game.player.level << endl;
                        }
                        continue;
                    }
                }
                ++it;
            }
            
            UpdateEnemies();
            
            // 检查玩家死亡
            if (game.player.health <= 0) {
                game.gameOver = true;
                cout << "你死了!最终到达楼层:" << game.currentLevel << endl;
            }
            
            Sleep(50);
        }
        
        cout << "按任意键退出..." << endl;
        _getch();
        return 0;
    }
    
    
    
  • 通过的题目

  • 最近活动

题目标签

入门
165
基础
158
普及
82
模拟算法
50
数学
41
分支
39
STL容器
37
字符串
34
普及-
30
贪心
30
循环
29
语法基础
27
基本运算
22
枚举
21
深度优先搜索
21
动态规划
20
排序
18
算法基础
17
一维数组
16
二分查找
16