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;

}

相关推荐
侃侃_天下10 小时前
最终的信号类
开发语言·c++·算法
echoarts10 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix11 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题11 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说11 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔12 小时前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔12 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing1023292912 小时前
Day03_刷题niuke20250915
c语言
我是菜鸟0713号12 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_12 小时前
QT(4)
开发语言·汇编·c++·qt·算法