用C++写一个飞机大战游戏代码
时间: 2024-01-28 12:04:56 浏览: 115
飞机大战游戏代码c++
5星 · 资源好评率100%
当然可以!以下是一个简单的示例代码,用C++编写的飞机大战游戏:
```cpp
#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 20;
const int height = 20;
int x, y; // 飞机的坐标
int enemyX, enemyY; // 敌人的坐标
int bulletX, bulletY; // 子弹的坐标
bool isFired = false; // 是否发射子弹
int score = 0; // 得分
void Setup()
{
x = width / 2;
y = height - 1;
enemyX = rand() % width;
enemyY = 0;
bulletX = x;
bulletY = y - 1;
}
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 if (isFired && i == bulletY && j == bulletX)
cout << "|";
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':
x--;
break;
case 'd':
x++;
break;
case ' ':
isFired = true;
bulletX = x;
bulletY = y - 1;
break;
}
}
}
void Logic()
{
if (isFired)
bulletY--;
enemyY++;
if (enemyY == height)
{
enemyX = rand() % width;
enemyY = 0;
score++;
}
if (bulletY <= 0)
isFired = false;
if (bulletY == enemyY && bulletX == enemyX)
{
score++;
isFired = false;
enemyX = rand() % width;
enemyY = 0;
}
if (x < 0)
x = 0;
else if (x >= width)
x = width - 1;
}
int main()
{
Setup();
while (true)
{
Draw();
Input();
Logic();
}
return 0;
}
```
这只是一个简单的示例,你可以根据自己的需求进行扩展和改进。希望这可以帮助到你!
阅读全文