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 小时前
C#正则表达式完全攻略:从基础到实战的全场景应用指南
开发语言·正则表达式·c#·regex
哈库纳玛塔塔1 小时前
放弃 MyBatis,拥抱新一代 Java 数据访问库
java·开发语言·数据库·mybatis·orm·dbvisitor
你怎么知道我是队长2 小时前
C语言---typedef
c语言·c++·算法
phltxy2 小时前
从零入门JavaScript:基础语法全解析
开发语言·javascript
带土12 小时前
5. enum(枚举)关键字在C/C++中的作用
c语言·c++
天“码”行空3 小时前
java面向对象的三大特性之一多态
java·开发语言·jvm
odoo中国4 小时前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
代码N年归来仍是新手村成员4 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
Z1Jxxx5 小时前
01序列01序列
开发语言·c++·算法
沐知全栈开发5 小时前
C语言中的强制类型转换
开发语言