用c语言写一个飞机打靶小程序、
时间: 2023-06-27 14:08:04 浏览: 66
好的,以下是一个简单的飞机打靶小程序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 25
// 定义靶子和飞机的结构体
typedef struct {
int x;
int y;
int is_alive;
} target;
typedef struct {
int x;
int y;
int score;
} airplane;
// 初始化靶子的位置和状态
void init_targets(target* targets, int count) {
for (int i = 0; i < count; i++) {
targets[i].x = rand() % SCREEN_WIDTH;
targets[i].y = rand() % (SCREEN_HEIGHT - 5);
targets[i].is_alive = 1;
}
}
// 初始化飞机的位置和分数
void init_airplane(airplane* ap) {
ap->x = SCREEN_WIDTH / 2;
ap->y = SCREEN_HEIGHT - 5;
ap->score = 0;
}
// 显示游戏界面
void draw_game(target* targets, int target_count, airplane* ap) {
system("cls"); // 清屏
// 显示靶子
for (int i = 0; i < target_count; i++) {
if (targets[i].is_alive) {
printf("o");
for (int j = 0; j < SCREEN_WIDTH; j++) {
if (j == targets[i].x) {
printf(" ");
} else {
printf("\b");
}
}
}
}
// 显示飞机和分数
printf("\n");
for (int i = 0; i < SCREEN_WIDTH; i++) {
if (i == ap->x) {
printf("+");
} else {
printf("-");
}
}
printf("\n");
printf("Score: %d\n", ap->score);
}
// 移动飞机
void move_airplane(airplane* ap) {
if (_kbhit()) { // 检测键盘输入
char ch = _getch();
if (ch == 'a' && ap->x > 0) { // 左移
ap->x--;
} else if (ch == 'd' && ap->x < SCREEN_WIDTH - 1) { // 右移
ap->x++;
} else if (ch == 'q') { // 退出游戏
exit(0);
}
}
}
// 移动靶子
void move_targets(target* targets, int count) {
for (int i = 0; i < count; i++) {
if (targets[i].is_alive) {
targets[i].y++;
if (targets[i].y >= SCREEN_HEIGHT - 5) {
targets[i].is_alive = 0;
}
}
}
}
// 判断是否命中靶子
void check_hit(target* targets, int count, airplane* ap) {
for (int i = 0; i < count; i++) {
if (targets[i].is_alive && targets[i].y == ap->y && targets[i].x == ap->x) {
targets[i].is_alive = 0;
ap->score++;
}
}
}
int main() {
srand((unsigned) time(NULL)); // 初始化随机数生成器
target targets[10];
init_targets(targets, 10);
airplane ap;
init_airplane(&ap);
while (1) {
draw_game(targets, 10, &ap);
move_airplane(&ap);
move_targets(targets, 10);
check_hit(targets, 10, &ap);
Sleep(50); // 暂停50毫秒,控制游戏速度
}
return 0;
}
```
这个程序使用了Windows下的控制台API,可以在Windows下编译运行。运行后,玩家可以通过键盘控制飞机左右移动,尝试击中屏幕上不停移动的靶子,每次命中会得到一分,游戏将一直进行直到玩家选择退出。