C语言实现飞行小游戏

以下是一个简单的C语言实现飞行小游戏的代码示例。这个游戏中,一个飞机需要控制左右移动来避开悬挂在屏幕上方的飞行杂物,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
 
#define WIDTH 20
#define HEIGHT 15
#define SPEED 500
 
int score = 0;
 
// 飞机结构体
typedef struct {
    int x;
    int y;
} Plane;
 
// 杂物结构体
typedef struct {
    int x;
    int y;
    int speed;
} Obstacle;
 
// 初始化飞机
void initPlane(Plane *plane) {
    plane->x = WIDTH / 2;
    plane->y = HEIGHT - 1;
}
 
// 初始化杂物
void initObstacle(Obstacle *obstacle) {
    obstacle->x = rand() % WIDTH;
    obstacle->y = -2;
    obstacle->speed = rand() % SPEED + 1;
}
 
// 绘制界面
void draw(Plane plane, Obstacle obstacle) {
    system("cls"); // 清屏
    for (int i = 0; i < WIDTH; i++) {
        if (i == plane.x) {
            printf("^"); // 绘制飞机
        } else if (i == obstacle.x) {
            printf("*"); // 绘制杂物
        } else {
            printf(" "); // 绘制空白
        }
    }
    printf("\n");
}
 
// 更新位置
void update(Plane *plane, Obstacle *obstacle) {
    if (obstacle->y > HEIGHT) {
        initObstacle(obstacle); // 杂物飞出界面,重新初始化
        score++; // 增加分数
    } else {
        obstacle->y++; // 杂物向下移动
    }
}
 
// 玩家控制飞机移动
void control(Plane *plane, char key) {
    switch (key) {
        case 'a':
            if (plane->x > 0) plane->x--;
            break;
        case 'd':
            if (plane->x < WIDTH - 1) plane->x++;
            break;
    }
}
 
int main() {
    srand(time(0)); // 初始化随机数生成器
    Plane plane;
    Obstacle obstacle;
    initPlane(&plane);
    initObstacle(&obstacle);
 
    char key = ' ';
    while (1) {
        if (_kbhit()) { // 检测键盘输入
            key = _getch(); // 非阻塞读取键盘输入
            control(&plane, key);
        }
        update(&plane, &obstacle);
        draw(plane, obstacle);
 
        if (plane.x == obstacle.x && plane.y == obstacle.y) {
            printf("Game Over! Your score is: %d\n", score);
            break;
        }
        Sleep(obstacle.speed); // 暂停以控制游戏速度
    }
    return 0;
}

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2193410903

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值