这是一个简单的控制台飞机大战游戏,使用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;
}

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

被折叠的 条评论
为什么被折叠?



