可以用C++写一个射击游戏吗
时间: 2023-10-29 18:06:56 浏览: 40
可以的,下面是一个简单的 C++ 射击游戏示例。这个示例中,玩家需要操作键盘控制一个小飞机射击从上往下掉落的敌机,每击落一个敌机得到一分,直到游戏结束。
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 30; // 游戏界面宽度
const int HEIGHT = 20; // 游戏界面高度
const int MAX_ENEMIES = 20; // 最大敌机数量
const int SHOOT_DELAY = 3; // 射击延迟
const int ENEMY_DELAY = 10; // 敌机创建延迟
void gotoxy(int x, int y) // 移动光标到指定位置
{
COORD coord = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
class Enemy // 敌机类
{
public:
int x, y;
bool active;
Enemy() { active = false; }
void move() { y++; }
void draw() { gotoxy(x, y); cout << "V"; }
void clear() { gotoxy(x, y); cout << " "; }
};
class Player // 玩家类
{
public:
int x, y, score;
bool active;
int shootDelay; // 射击延迟
Player() { x = WIDTH / 2; y = HEIGHT - 1; score = 0; active = true; shootDelay = 0; }
void move(int dx) { x += dx; if (x < 0) x = 0; if (x >= WIDTH) x = WIDTH - 1; }
void shoot();
void draw() { gotoxy(x, y); cout << "^"; }
void clear() { gotoxy(x, y); cout << " "; }
};
void Player::shoot() // 玩家射击
{
if (shootDelay > 0) return;
shootDelay = SHOOT_DELAY;
gotoxy(x, y - 1); cout << "*";
}
int main()
{
srand(time(NULL));
Player player;
Enemy enemies[MAX_ENEMIES];
int enemyDelay = ENEMY_DELAY;
while (true)
{
if (_kbhit()) // 处理键盘输入
{
char ch = _getch();
if (ch == 'a') player.move(-1);
if (ch == 'd') player.move(1);
if (ch == ' ') player.shoot();
}
if (player.shootDelay > 0) player.shootDelay--;
if (enemyDelay > 0) enemyDelay--;
else // 创建新敌机
{
for (int i = 0; i < MAX_ENEMIES; i++)
{
if (!enemies[i].active)
{
enemies[i].x = rand() % WIDTH;
enemies[i].y = 0;
enemies[i].active = true;
break;
}
}
enemyDelay = ENEMY_DELAY;
}
system("cls"); // 清屏
for (int i = 0; i < MAX_ENEMIES; i++) // 移动和绘制敌机
{
if (enemies[i].active)
{
enemies[i].clear();
enemies[i].move();
enemies[i].draw();
if (enemies[i].y >= HEIGHT) // 敌机超出屏幕
{
enemies[i].clear();
enemies[i].active = false;
}
else if (enemies[i].x == player.x && enemies[i].y == player.y) // 玩家被撞
{
player.active = false;
}
}
}
if (player.active) // 绘制玩家
{
player.clear();
player.draw();
}
else // 游戏结束
{
gotoxy(WIDTH / 2 - 4, HEIGHT / 2);
cout << "Game Over!";
gotoxy(WIDTH / 2 - 4, HEIGHT / 2 + 1);
cout << "Score: " << player.score;
break;
}
for (int i = 0; i < MAX_ENEMIES; i++) // 处理玩家的射击
{
if (enemies[i].active)
{
for (int j = 0; j < SHOOT_DELAY; j++)
{
if (player.active && player.x == enemies[i].x && player.y - j == enemies[i].y)
{
enemies[i].clear();
enemies[i].active = false;
player.score++;
break;
}
}
}
}
Sleep(30); // 延迟一段时间
}
return 0;
}
```
这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。