C语言实现射击小游戏

以下是一个简单的C语言射击小游戏的实现示例。这个游戏中,玩家控制一个飞船,敌方飞船会随机出现并向玩家移动。如果玩家的飞船与敌方飞船相撞,玩家就失去一条生命,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define WIDTH 10
#define HEIGHT 5
#define ENEMY_SHIP 'E'
#define PLAYER_SHIP 'S'
#define BULLET '|'
 
char game_field[HEIGHT][WIDTH + 1];
int player_ship_x = WIDTH / 2;
int enemy_ship_x = -1;
int enemy_ship_y = -1;
int bullet_x = -1;
int bullet_y = -1;
int lives = 3;
 
void draw_game_field() {
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            if (j == player_ship_x && i == bullet_y) {
                printf("%c", BULLET);
            } else if (j == player_ship_x && i == 0) {
                printf("%c", PLAYER_SHIP);
            } else if (j == enemy_ship_x && i == enemy_ship_y) {
                printf("%c", ENEMY_SHIP);
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }
    printf("Lives: %d\n", lives);
}
 
void move_enemy_ship() {
    if (enemy_ship_x < WIDTH - 1) {
        enemy_ship_x++;
    } else {
        enemy_ship_y++;
        enemy_ship_x = 0;
    }
    if (enemy_ship_y == HEIGHT) {
        enemy_ship_y = 0;
    }
}
 
void move_bullet() {
    if (bullet_x > 0) {
        bullet_x--;
    } else {
        bullet_x = player_ship_x;
        bullet_y = -1;
    }
}
 
void handle_collisions() {
    if (bullet_x == enemy_ship_x && bullet_y == enemy_ship_y) {
        bullet_x = player_ship_x;
        bullet_y = -1;
        enemy_ship_x = -1;
        enemy_ship_y = -1;
        lives--;
    }
}
 
void game_loop() {
    srand(time(0));
    while (lives > 0) {
        draw_game_field();
        move_enemy_ship();
        move_bullet();
        handle_collisions();
        if (enemy_ship_x != -1 && enemy_ship_y != -1) {
            draw_game_field();
            char input = getchar();
            if (input == 'a') {
                if (player_ship_x > 0) {
                    player_ship_x--;
                }
            } else if (input == 'd') {
                if (player_ship_x < WIDTH - 1) {
                    player_ship_x++;
                }
            } else if (input == 'w') {
                bullet_y = player_ship_x;
                bullet_x = player_ship_x;
            }
        }
    }
}
 
int main() {
    game_loop();
    printf("Game Over\n");
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

2193410903

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

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

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

打赏作者

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

抵扣说明:

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

余额充值