21xrx.com
2025-04-02 10:29:35 Wednesday
文章检索 我的文章 写文章
C++编写的飞机大战游戏源代码
2023-06-27 05:06:53 深夜i     100     0
C++ 编写 飞机大战 游戏 源代码

飞机大战是一款经典的射击游戏,玩家需要控制自己的战机躲避敌机的攻击并消灭它们。如果您想学习C++编程或者想制作一款游戏,以下是一份C++编写的飞机大战游戏的源代码,可供参考和学习。

#include

#include

#include

#include

#include

using namespace std;

int const width = 20; // 游戏画面宽度

int const height = 20; // 游戏画面高度

int x, y; // 玩家坐标

int bulletX, bulletY; // 子弹坐标

int enemyX, enemyY; // 敌机坐标

int score; // 得分

bool gameOver; // 游戏是否结束

// 初始化游戏

void Initialize()

{

  x = width / 2; // 玩家在屏幕中央

  y = height - 1; // 玩家在屏幕底部

  bulletX = x; // 子弹与玩家坐标相同

  bulletY = y - 1; // 子弹在玩家上方

  enemyX = rand() % width; // 敌机在屏幕随机位置

  enemyY = 0; // 敌机在屏幕顶部

  score = 0; // 得分清零

  gameOver = false; // 游戏未结束

}

// 绘制游戏画面

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 == bulletY && j == bulletX)

        cout << "|"; // 绘制子弹

      else if (i == enemyY && j == enemyX)

        cout << "V"; // 绘制敌机

      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': // 左移

        if (x > 1)

          x--;

        break;

      case 'd': // 右移

        if (x < width - 2)

          x++;

        break;

      case 'w': // 发射子弹

        bulletY--;

        break;

      case 'x': // 退出游戏

        gameOver = true;

        break;

    }

  }

}

// 更新游戏状态

void Update()

{

  bulletY--; // 子弹向上移动

  enemyY++; // 敌机向下移动

  // 如果子弹打中敌机

  if (bulletX == enemyX && bulletY == enemyY) {

    score++; // 得分增加

    enemyX = rand() % width; // 重新生成敌机坐标

    enemyY = 0;

    bulletY = y - 1; // 子弹回到玩家头顶

  }

  // 如果敌机撞到玩家或者敌机飞出屏幕

  if ((enemyY == y && enemyX == x) || enemyY == height)

    gameOver = true; // 游戏结束

}

// 游戏主循环

void GameLoop()

{

  do {

    Draw(); // 绘制游戏画面

    Input(); // 处理用户输入

    Update(); // 更新游戏状态

    Sleep(50); // 等待50毫秒

  } while (!gameOver); // 游戏未结束

}

// 游戏结束

void GameOver()

{

  system("cls"); // 清屏

  cout << "Game Over!" << endl;

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

}

// 主函数

int main()

{

  Initialize(); // 初始化游戏

  GameLoop(); // 进入游戏主循环

  GameOver(); // 游戏结束

  return 0;

}

这份源代码是一个简单版的飞机大战游戏,玩家只能左右移动和发射子弹,敌机向下移动并且在子弹击中后能重新生成,无法射击多个子弹,也不能获得新的血量或强化道具。但作为C++学习者和初学者,可用此代码参照并实现其他功能。即使是游戏开发工作室,尝试着在源代码的基础上进行优化,用自己的思路和方法来创作一个更好的飞机大战,或者更加有个性特色的新游戏。记得享受编程和游戏开发中的有趣之处!

  
  
下一篇: 不支持node.js

评论区