c语言射击游戏代码
时间: 2023-08-01 10:12:49 浏览: 64
以下是一个简单的C语言射击游戏代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_TARGETS 10
#define MAX_SHOTS 5
int main() {
int targets[MAX_TARGETS]; // 存放目标的数组
int shots[MAX_SHOTS]; // 存放玩家的射击结果的数组
int num_targets = 0; // 目标数量
int num_shots = 0; // 射击次数
int i, j, hit_count = 0; // 循环计数器和命中数量
srand(time(NULL)); // 种子初始化
// 随机生成目标
while (num_targets < MAX_TARGETS) {
int target = rand() % 10 + 1; // 生成1~10之间的随机数
int is_duplicate = 0; // 是否重复标志位
// 判断是否重复
for (i = 0; i < num_targets; i++) {
if (targets[i] == target) {
is_duplicate = 1;
break;
}
}
// 如果不重复则添加到目标数组中
if (!is_duplicate) {
targets[num_targets++] = target;
}
}
// 开始射击
while (num_shots < MAX_SHOTS) {
int shot;
printf("请输入第%d次射击的目标数字(1~10): ", num_shots + 1);
scanf("%d", &shot);
// 判断是否命中
for (i = 0; i < num_targets; i++) {
if (targets[i] == shot) {
printf("恭喜你,命中目标!\n");
hit_count++;
break;
}
}
// 将射击结果添加到数组中
shots[num_shots++] = shot;
}
// 输出结果
printf("射击结束,你一共命中了%d个目标,你的射击记录为: ", hit_count);
for (i = 0; i < MAX_SHOTS; i++) {
printf("%d ", shots[i]);
}
printf("\n");
return 0;
}
```
这个游戏的规则是,随机生成10个1~10之间的数字作为目标,玩家有5次射击机会,每次输入一个数字,判断是否命中目标。射击结束后输出命中数量和射击记录。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)