以下是一个简单的C++飞机大战游戏的代码示例,使用了Windows API来创建窗口和绘制图形,以及键盘输入来控制飞机的移动。游戏中的图形是用字符画实现的,没有使用任何图片素材。

#include <iostream>
#include <windows.h>
using namespace std;

// 游戏窗口大小
const int screenWidth = 80;
const int screenHeight = 25;

// 飞机初始位置
int planeX = screenWidth / 2;
int planeY = screenHeight - 1;

// 子弹位置
int bulletX = -1;
int bulletY = -1;

// 敌机位置
int enemyX = -1;
int enemyY = -1;

// 绘制游戏界面
void Draw()
{
    // 清空屏幕
    system("cls");

    for (int y = 0; y < screenHeight; y++)
    {
        for (int x = 0; x < screenWidth; x++)
        {
            // 绘制飞机
            if (x == planeX && y == planeY)
                cout << "^";
            
            // 绘制子弹
            else if (x == bulletX && y == bulletY)
                cout << "|";
            
            // 绘制敌机
            else if (x == enemyX && y == enemyY)
                cout << "V";

            // 绘制其他空白区域
            else
                cout << " ";
        }
        cout << endl;
    }
}

// 处理键盘输入
void ProcessInput()
{
    if (GetAsyncKeyState(VK_LEFT))
        planeX--;
    if (GetAsyncKeyState(VK_RIGHT))
        planeX++;
    if (GetAsyncKeyState(VK_SPACE) && bulletY == -1)
    {
        // 发射子弹
        bulletX = planeX;
        bulletY = planeY - 1;
    }
}

// 更新游戏逻辑
void Update()
{
    // 更新子弹位置
    if (bulletY > 0)
        bulletY--;
    else
    {
        bulletX = -1;
        bulletY = -1;
    }

    // 更新敌机位置
    if (enemyY == -1 || enemyY >= screenHeight - 1)
    {
        enemyX = rand() % screenWidth;
        enemyY = 0;
    }
    else
        enemyY++;

    // 判断碰撞
    if ((bulletX == enemyX && bulletY == enemyY) || (planeX == enemyX && planeY == enemyY))
    {
        bulletX = -1;
        bulletY = -1;
        enemyX = -1;
        enemyY = -1;
    }
}

int main()
{
    // 隐藏光标
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cci;
    cci.bVisible = FALSE;
    cci.dwSize = sizeof(cci);
    SetConsoleCursorInfo(hOut, &cci);

    // 设置窗口大小
    HWND console = GetConsoleWindow();
    RECT r;
    GetWindowRect(console, &r);
    MoveWindow(console, r.left, r.top, screenWidth * 10, screenHeight * 20, TRUE);

    srand(time(NULL));

    while (true)
    {
        ProcessInput();
        Update();
        Draw();
        Sleep(50);
    }

    return 0;
}

这是一个非常简单的飞机大战游戏示例,只有一个玩家飞机和一个敌机,玩家可以控制飞机左右移动并发射子弹,敌机会从上方不断下降。当子弹击中敌机或玩家与敌机碰撞时,游戏结束。你可以根据自己的需求进行扩展和改进

请用C++写一个飞机大战游戏是有窗口的而且不能有任何图片素材必须代码实现

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

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