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;

}

相关推荐
fs哆哆1 小时前
在VB.net中一维数组,与VBA有什么区别
java·开发语言·数据结构·算法·.net
johnZhangqi1 小时前
深圳大学-计算机信息管理课程实验 C++ 自考模拟题
java·开发语言·c++
Sally璐璐1 小时前
Go语言变量声明与初始化详解
java·开发语言·golang
luofeiju2 小时前
交叉编译笔记
开发语言
StudyWinter2 小时前
【C++】仿函数和回调函数
开发语言·c++·回调函数·仿函数
C4程序员2 小时前
北京JAVA基础面试30天打卡14
java·开发语言·面试
黑客影儿3 小时前
Go特有的安全漏洞及渗透测试利用方法(通俗易懂)
开发语言·后端·安全·web安全·网络安全·golang·系统安全
你好,我叫C小白4 小时前
C语言 常量,数据类型
c语言·开发语言·数据类型·常量
小红帽2.04 小时前
从ioutil到os:Golang在线客服聊天系统文件读取的迁移实践
服务器·开发语言·golang
Zafir20245 小时前
Qt实现TabWidget通过addTab函数添加的页,页内控件自适应窗口大小
开发语言·c++·qt·ui