c语言实现剪刀石头布游戏,进程通信,编写代码
时间: 2024-12-01 18:12:57 浏览: 6
在C语言中,我们可以创建一个简单的剪刀、石头、布(Rock-Paper-Scissors, RPS)游戏,同时利用管道来进行进程间通信。以下是基本的步骤和代码示例:
首先,我们需要创建两个进程:一个是主程序,另一个是用户输入处理器。主程序会启动用户输入处理器,然后等待结果。
**1. 用户输入处理器(game_player.c)**
```c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFER_SIZE 10
int choose() {
char choice[BUFFER_SIZE];
printf("请输入选择 (r/s/p): ");
fgets(choice, sizeof(choice), stdin);
choice[strlen(choice) - 1] = '\0'; // remove newline character
return choice[0] == 'r' ? 0 : // rock
choice[0] == 's' ? 1 : // scissors
choice[0] == 'p' ? 2 : 0; // paper
}
void communicate_result(int player_choice, int computer_choice) {
write(1, &player_choice, sizeof(player_choice));
write(1, &computer_choice, sizeof(computer_choice));
}
int main() {
pid_t child_pid = fork();
if (child_pid > 0) { // parent process
close(1); // redirect stdout to pipe
dup2(fileno(stdout), 1);
// Wait for the child process result
wait(NULL);
} else { // child process
int user_choice = choose();
int computer_choice = rand() % 3;
communicate_result(user_choice, computer_choice);
exit(0);
}
return 0;
}
```
**2. 主程序(main.c)**
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int read_and_process_results() {
int player_choice, computer_choice;
read(0, &player_choice, sizeof(player_choice));
read(0, &computer_choice, sizeof(computer_choice));
printf("You chose: %d\n", player_choice);
printf("Computer chose: %d\n", computer_choice);
switch ((player_choice + computer_choice) % 3) {
case 0:
printf("平局!\n");
break;
case 1:
printf("你赢了!\n");
break;
default:
printf("电脑赢了!\n");
break;
}
return 0;
}
int main() {
pid_t pipe_pid = pipe();
fork_and_redirect_stdout(pipe_pid[0]);
pid_t game_pid = fork();
if (game_pid > 0) { // parent process
close(pipe_pid[0]); // close unused end of the pipe
wait(NULL);
} else { // child process
close(1);
dup2(pipe_pid[1], 1); // redirect stderr to pipe
_exit(read_and_process_results());
}
return 0;
}
// Helper function to fork and redirect stdout to a pipe
void fork_and_redirect_stdout(int fd) {
pid_t child_pid = fork();
if (child_pid > 0) {
close(fd); // close unused end of the pipe in parent
dup2(open("/dev/null", O_RDWR), 1); // redirect stdout to /dev/null
} else {
dup2(fd, 1); // redirect stdout to pipe in child
close(fd); // close unused end of the pipe in child
}
}
```
运行`make`命令构建并执行程序。每个玩家通过管道向主程序发送他们的选择,主程序读取这些选择并计算胜负。
阅读全文