C++飞机大战代码
时间: 2023-07-10 21:04:12 浏览: 59
这是一个简单的 C++ 飞机大战游戏代码。请注意,这只是一个基础版本,您可以根据自己的需求进行修改和优化。
```c++
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
const int WIDTH = 30;
const int HEIGHT = 20;
const int MAX_BULLETS = 5;
struct point {
int x, y;
};
struct player {
point pos;
int score;
};
struct bullet {
point pos;
bool isActive;
};
player p = { { WIDTH / 2, HEIGHT - 1 }, 0 };
bullet bullets[MAX_BULLETS];
point enemyPos = { WIDTH / 2, 0 };
void drawPlayer() {
cout << "P";
}
void clearScreen() {
system("cls");
}
void drawBullet(int index) {
bullet b = bullets[index];
if (b.isActive) {
cout << "|";
}
}
void drawEnemy() {
cout << "E";
}
void drawScore() {
cout << "Score: " << p.score << endl;
}
void movePlayer(int x) {
p.pos.x += x;
if (p.pos.x < 0) {
p.pos.x = 0;
} else if (p.pos.x >= WIDTH) {
p.pos.x = WIDTH - 1;
}
}
void fireBullet() {
for (int i = 0; i < MAX_BULLETS; i++) {
if (!bullets[i].isActive) {
bullets[i].pos = { p.pos.x, p.pos.y - 1 };
bullets[i].isActive = true;
break;
}
}
}
void moveBullet(int index) {
bullet& b = bullets[index];
if (b.isActive) {
b.pos.y--;
if (b.pos.y < 0) {
b.isActive = false;
}
}
}
void moveEnemy() {
enemyPos.y++;
if (enemyPos.y >= HEIGHT) {
enemyPos = { rand() % WIDTH, 0 };
p.score++;
}
}
bool isColliding(point a, point b) {
return a.x == b.x && a.y == b.y;
}
bool isGameOver() {
for (int i = 0; i < MAX_BULLETS; i++) {
if (bullets[i].isActive && isColliding(bullets[i].pos, enemyPos)) {
return true;
}
}
return isColliding(p.pos, enemyPos);
}
void draw() {
clearScreen();
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (x == p.pos.x && y == p.pos.y) {
drawPlayer();
} else if (x == enemyPos.x && y == enemyPos.y) {
drawEnemy();
} else {
bool isBulletDrawn = false;
for (int i = 0; i < MAX_BULLETS; i++) {
if (x == bullets[i].pos.x && y == bullets[i].pos.y) {
drawBullet(i);
isBulletDrawn = true;
break;
}
}
if (!isBulletDrawn) {
cout << " ";
}
}
}
cout << endl;
}
drawScore();
}
int main() {
while (true) {
if (_kbhit()) {
int c = _getch();
switch (c) {
case 'a':
movePlayer(-1);
break;
case 'd':
movePlayer(1);
break;
case ' ':
fireBullet();
break;
}
}
for (int i = 0; i < MAX_BULLETS; i++) {
moveBullet(i);
}
moveEnemy();
draw();
if (isGameOver()) {
clearScreen();
cout << "Game Over!" << endl;
cout << "Your Score: " << p.score << endl;
break;
}
Sleep(100);
}
return 0;
}
```