用C++做一个飞机游戏
时间: 2023-12-19 18:04:46 浏览: 27
好的,让我们来看看如何用C++语言制作一个简单的飞机游戏。以下是一个简单的游戏框架:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 80;
const int HEIGHT = 25;
int x, y; // 飞机的坐标
void gotoxy(int x, int y)
{
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void draw_plane()
{
gotoxy(x, y);
cout << " /\\";
gotoxy(x, y + 1);
cout << " / \\";
gotoxy(x, y + 2);
cout << "/____\\";
}
void clear_plane()
{
gotoxy(x, y);
cout << " ";
gotoxy(x, y + 1);
cout << " ";
gotoxy(x, y + 2);
cout << " ";
}
void move_plane(int dx, int dy)
{
clear_plane();
x += dx;
y += dy;
draw_plane();
}
int main()
{
x = WIDTH / 2 - 1;
y = HEIGHT - 3;
draw_plane();
while (true) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'a' && x > 1) {
move_plane(-1, 0);
} else if (ch == 'd' && x < WIDTH - 4) {
move_plane(1, 0);
} else if (ch == 'w' && y > 1) {
move_plane(0, -1);
} else if (ch == 's' && y < HEIGHT - 4) {
move_plane(0, 1);
}
}
}
return 0;
}
```
这个程序使用了Windows API来控制控制台窗口的输出,所以只能在Windows系统上运行。程序中定义了飞机的坐标,然后使用`gotoxy()`函数在控制台上输出ASCII字符来绘制飞机。使用`_kbhit()`和`_getch()`函数来获取键盘输入,并且使用`move_plane()`函数来移动飞机。
这只是一个简单的示例,你可以添加更多的功能和特效来增加游戏的乐趣。例如,你可以添加敌机和子弹,添加音乐和音效,或者设计关卡系统。