飞机大战c语言代码eazyx
时间: 2025-01-06 21:35:29 浏览: 98
### 简易 C语言实现飞机大战游戏
#### 游戏概述
该游戏是一个简单的命令行版本的飞机大战,玩家通过键盘输入来控制一架战斗机在屏幕上移动并发射子弹击落敌机。此项目不依赖任何第三方库[^2]。
#### 主要功能模块
- **检测碰撞**
#### 完整代码示例
```c
#include <stdio.h>
#include <conio.h> /* _getch */
#include <windows.h>
#define WIDTH 40 // 屏幕宽度
#define HEIGHT 20 // 屏幕高度
// 移动方向枚举定义
enum Direction {
UP, DOWN, LEFT, RIGHT,
};
typedef struct {
int x;
int y;
} Point;
void gotoxy(int column, int line) { // 设置光标位置
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void clearScreen() { // 清屏函数
system("cls");
}
void drawBorder() { // 绘制边界线
for (int i = 0; i <= WIDTH; ++i) printf("-");
printf("\n");
for (int j = 0; j < HEIGHT; ++j) {
for (int k = 0; k <= WIDTH; ++k) {
if (k == 0 || k == WIDTH)
putchar('|');
else
putchar(' ');
}
printf("\n");
}
for (int i = 0; i <= WIDTH; ++i) printf("-");
printf("\n");
}
Point playerPos = {WIDTH / 2, HEIGHT - 1}; // 初始化玩家坐标
void movePlayer(enum Direction dir) { // 处理玩家移动逻辑
switch (dir) {
case UP:
if (playerPos.y > 1) --playerPos.y;
break;
case DOWN:
if (playerPos.y < HEIGHT - 1) ++playerPos.y;
break;
case LEFT:
if (playerPos.x > 1) --playerPos.x;
break;
case RIGHT:
if (playerPos.x < WIDTH - 1) ++playerPos.x;
break;
}
}
char getCharAtXY(short int x, short int y) { // 获取指定坐标的字符
CHAR_INFO ci;
COORD xy = {0, 0};
SMALL_RECT rect = {(short)x, (short)y, (short)(x + 1), (short)(y + 1)};
DWORD n;
ReadConsoleOutputA(
GetStdHandle(STD_OUTPUT_HANDLE),
&ci,
1,
xy,
&rect
);
return ci.Char.AsciiChar;
}
void shootBullet(Point bullet[]) { // 子弹射击逻辑
static int count = 0;
char ch;
while (_kbhit()) {
ch = _getch();
if(ch == ' ') {
bullet[count].x = playerPos.x;
bullet[count++].y = playerPos.y - 1;
if(count >= MAX_BULLETS) count = 0;
}
}
for(int i=0;i<count;++i){
if(bullet[i].y != 0 && getCharAtXY(bullet[i].x,bullet[i].y-1)==' ')
--bullet[i].y;
else{
bullet[i].x = 0;
bullet[i].y = 0;
}
}
}
void mainLoop() { // 主循环
enum Direction direction;
char input;
Point bullets[MAX_BULLETS];
do {
clearScreen();
drawBorder();
// 显示玩家位置
gotoxy(playerPos.x, playerPos.y);
putchar('@');
// 更新子弹的位置
shootBullet(bullets);
// 打印所有活动中的子弹
for(int i=0;i<MAX_BULLETS;++i){
if(bullets[i].y!=0){
gotoxy(bullets[i].x,bullets[i].y);
putchar('*');
}
}
Sleep(75); // 控制帧率
if(_kbhit()){
input=_getch(); // 接收按键
if(input=='w') // 上移
direction = UP;
else if(input=='s') // 下移
direction = DOWN;
else if(input=='a') // 左移
direction = LEFT;
else if(input=='d') // 右移
direction = RIGHT;
movePlayer(direction);
}
} while (input != 'q'); // 按下 q 键退出程序
}
```
上述代码实现了基本的游戏框架,包括了玩家角色、敌人以及子弹之间的交互机制。为了简化起见,这里省略了一些细节上的优化和额外的功能扩展。
阅读全文
相关推荐








