C++飞机大战小游戏

这是一款基于C++开发的控制台飞机大战游戏,玩家使用wasd键控制飞机移动,通过击落敌机获得分数。游戏代码可供修改和扩展,适合初学者实践。

这是一个简单的控制台飞机大战游戏,使用wasd控制飞机移动,目标是通过吃掉敌机来得分。请根据自己的需求进行修改和扩展。希望能帮到你!

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

using namespace std;

bool gameOver;
const int width = 20;
const int height = 20;
int x, y; // 飞机坐标
int enemyX, enemyY; // 敌机坐标
int score; // 得分

enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;

void Setup()
{
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height - 1;
    enemyX = rand() % width;
    enemyY = 0;
    score = 0;
}

void Draw()
{
    system("cls"); // 清屏

    // 绘制顶部边界
    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)
                cout << "#"; // 绘制左边界

            if (i == y && j == x)
                cout << "A"; // 绘制飞机
            else if (i == enemyY && j == enemyX)
                cout << "E"; // 绘制敌机
            else
                cout << " ";

            if (j == width - 1)
                cout << "#"; // 绘制右边界
        }
        cout << endl;
    }

    // 绘制底部边界
    for (int i = 0; i < width + 2; i++)
        cout << "#";
    cout << endl;

    cout << "Score: " << score << endl;
}

void Input()
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'a':
            dir = LEFT;
            break;
        case 'd':
            dir = RIGHT;
            break;
        case 'w':
            dir = UP;
            break;
        case 's':
            dir = DOWN;
            break;
        case 'x':
            gameOver = true;
            break;
        }
    }
}

void Logic()
{
    // 飞机移动
    switch (dir)
    {
    case LEFT:
        x--;
        break;
    case RIGHT:
        x++;
        break;
    case UP:
        y--;
        break;
    case DOWN:
        y++;
        break;
    }

    // 边界检测
    if (x < 0)
        x = 0;
    else if (x >= width)
        x = width - 1;

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

    // 敌机移动
    enemyY++;

    // 碰撞检测
    if (x == enemyX && y == enemyY)
    {
        score++;
        enemyX = rand() % width;
        enemyY = 0;
    }
}

int main()
{
    Setup();

    while (!gameOver)
    {
        Draw();
        Input();
        Logic();
        Sleep(10); // 控制游戏速度
    }

    return 0;
}

 

麻烦点赞。。。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值