C语言父进程猜拳游戏代码
时间: 2024-04-21 22:20:31 浏览: 17
当然,我可以给你介绍一下C语言中实现父进程猜拳游戏的代码。以下是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#define ROCK 0
#define PAPER 1
#define SCISSORS 2
int main() {
int parent, child;
int parent_choice, child_choice;
// 创建子进程
child = fork();
if (child < 0) {
printf("无法创建子进程\n");
exit(1);
} else if (child == 0) {
// 子进程逻辑
srand(time(NULL));
child_choice = rand() % 3; // 随机生成子进程的选择
exit(child_choice); // 子进程退出,并将选择作为退出码返回给父进程
} else {
// 父进程逻辑
printf("欢迎来到猜拳游戏!\n");
printf("请输入你的选择(0-石头,1-剪刀,2-布):");
scanf("%d", &parent_choice);
// 等待子进程退出,并获取子进程的选择
wait(&parent);
child_choice = WEXITSTATUS(parent);
printf("你的选择:%d\n", parent_choice);
printf("对手的选择:%d\n", child_choice);
// 判断胜负
if (parent_choice == child_choice) {
printf("平局!\n");
} else if ((parent_choice == ROCK && child_choice == SCISSORS) ||
(parent_choice == PAPER && child_choice == ROCK) ||
(parent_choice == SCISSORS && child_choice == PAPER)) {
printf("你赢了!\n");
} else {
printf("你输了!\n");
}
}
return 0;
}
```
这段代码实现了一个简单的猜拳游戏,父进程和子进程分别选择石头、剪刀或布,然后判断胜负并输出结果。