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;

}

相关推荐
oplp3 小时前
第四章 C语言中的基本输入输出(六)
c语言
岁忧3 小时前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya3 小时前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
心无旁骛~4 小时前
python多进程和多线程问题
开发语言·python
星云数灵4 小时前
使用Anaconda管理Python环境:安装与验证Pandas、NumPy、Matplotlib
开发语言·python·数据分析·pandas·教程·环境配置·anaconda
kaikaile19954 小时前
基于遗传算法的车辆路径问题(VRP)解决方案MATLAB实现
开发语言·人工智能·matlab
四问四不知5 小时前
Rust语言进阶(结构体)
开发语言·后端·rust
q***9945 小时前
index.php 和 php
开发语言·php
oioihoii5 小时前
C++网络编程:从Socket混乱到优雅Reactor的蜕变之路
开发语言·网络·c++
笙年5 小时前
JavaScript Promise,包括构造函数、对象方法和类方法
开发语言·javascript·ecmascript