以下是一个简单的用C++编写的人机枪战二维游戏的示例代码。在这个游戏中,玩家使用W、A、S、D键控制角色移动,空格键用于发射子弹。游戏中的人机敌人移动速度较慢。

#include <iostream>
#include <conio.h>

const int WIDTH = 10;
const int HEIGHT = 10;

class Player {
private:
    int x;
    int y;

public:
    Player(int startX, int startY) : x(startX), y(startY) {}

    void move(char direction) {
        switch (direction) {
            case 'w':
                if (y > 0) y--;
                break;
            case 'a':
                if (x > 0) x--;
                break;
            case 's':
                if (y < HEIGHT - 1) y++;
                break;
            case 'd':
                if (x < WIDTH - 1) x++;
                break;
            default:
                break;
        }
    }

    int getX() const {
        return x;
    }

    int getY() const {
        return y;
    }
};

class Enemy {
private:
    int x;
    int y;

public:
    Enemy(int startX, int startY) : x(startX), y(startY) {}

    void move() {
        // 敌人的移动速度较慢,根据实际需求可以调整移动速度
        if (x < WIDTH - 1) x++;
        else x = 0;
    }

    int getX() const {
        return x;
    }

    int getY() const {
        return y;
    }
};

class Game {
private:
    Player player;
    Enemy enemy;

public:
    Game() : player(0, 0), enemy(WIDTH - 1, HEIGHT - 1) {}

    void update(char input) {
        player.move(input);
        enemy.move();
    }

    void draw() const {
        for (int i = 0; i < HEIGHT; i++) {
            for (int j = 0; j < WIDTH; j++) {
                if (i == player.getY() && j == player.getX()) std::cout << 'P';
                else if (i == enemy.getY() && j == enemy.getX()) std::cout << 'E';
                else std::cout << '.';
            }
            std::cout << std::endl;
        }
    }
};

int main() {
    Game game;

    while (true) {
        if (_kbhit()) {
            char input = _getch();

            if (input == ' ') {
                // 发射子弹的逻辑
                std::cout << "子弹发射!" << std::endl;
            } else {
                game.update(input);
                game.draw();
            }
        }
    }

    return 0;
}

请注意,上述代码在Windows平台上使用了conio.h头文件中的_kbhit()_getch()函数来检测键盘输入。如果您在其他平台上使用此代码,您可能需要使用相应的库来实现相同的功能。此外,该示例仅提供了基本的游戏框架,您可以根据自己的需求进一步扩展和完善游戏的功能


原文地址: https://www.cveoy.top/t/topic/hTCW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录