C语言实现一个飞机大战
时间: 2023-11-15 09:06:25 浏览: 33
好的,以下是一个简单的C语言实现飞机大战的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 50 // 游戏窗口宽度
#define HEIGHT 25 // 游戏窗口高度
int x, y; // 玩家飞机的坐标
int score; // 玩家的得分
void setCursor(int x, int y) // 设置光标位置
{
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void drawFrame() // 绘制游戏窗口边框
{
int i, j;
for (i = 0; i < HEIGHT; i++) {
setCursor(0, i);
printf("|");
setCursor(WIDTH - 1, i);
printf("|");
}
for (j = 0; j < WIDTH; j++) {
setCursor(j, 0);
printf("-");
setCursor(j, HEIGHT - 1);
printf("-");
}
}
void drawPlayer() // 绘制玩家飞机
{
setCursor(x, y);
printf("^");
}
void drawBullet(int bx, int by) // 绘制子弹
{
setCursor(bx, by);
printf("*");
}
void drawEnemy(int ex, int ey) // 绘制敌机
{
setCursor(ex, ey);
printf("V");
}
void moveBullet(int *bx, int *by) // 移动子弹
{
if (*by > 0) {
drawBullet(*bx, *by);
*by -= 1;
}
else {
*bx = -1;
*by = -1;
}
}
void moveEnemy(int *ex, int *ey) // 移动敌机
{
if (*ey < HEIGHT - 2) {
drawEnemy(*ex, *ey);
*ey += 1;
}
else {
*ex = rand() % (WIDTH - 2) + 1;
*ey = 1;
score += 1;
}
}
int main()
{
int bulletX = -1, bulletY = -1; // 子弹的坐标
int enemyX = rand() % (WIDTH - 2) + 1, enemyY = 1; // 敌机的坐标
x = WIDTH / 2;
y = HEIGHT - 2;
score = 0;
drawFrame();
drawPlayer();
while (1) {
if (_kbhit()) {
int ch = _getch();
if (ch == 'a' && x > 1) {
setCursor(x, y);
printf(" ");
x -= 1;
drawPlayer();
}
else if (ch == 'd' && x < WIDTH - 2) {
setCursor(x, y);
printf(" ");
x += 1;
drawPlayer();
}
else if (ch == ' ') {
if (bulletY == -1) {
bulletX = x;
bulletY = y - 1;
}
}
}
if (bulletY > 0) {
moveBullet(&bulletX, &bulletY);
}
moveEnemy(&enemyX, &enemyY);
if (bulletX == enemyX && bulletY == enemyY) {
score += 10;
enemyX = rand() % (WIDTH - 2) + 1;
enemyY = 1;
bulletX = -1;
bulletY = -1;
}
setCursor(0, HEIGHT);
printf("Score: %d", score);
Sleep(50); // 控制游戏速度
}
return 0;
}
```
注意:这是一个简单的实现,可能存在很多不足之处,可以根据需要进行修改和完善。