#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
const int STONE = 0;
const int SCISSORS = 1;
const int PAPER = 2;
// 胜负关系判断
bool compare(int move1, int move2) {
return (move1 > move2);
}
// 比赛结果的存放方式,使用二维数组
struct Result {
int round;
int player1;
int player2;
int winner;
};
// 选手进程
void player_proc(int pipefd[2]) {
srand(time(NULL));
for (int i = 0; i < 100; ++i) {
int move = rand() % 3;
write(pipefd[1], &move, sizeof(move));
}
close(pipefd[1]);
}
// 裁判进程
void referee_proc(int pipefd[2]) {
Result results[100];
int num_rounds = 0;
// 读选手 1 的出招
read(pipefd[0], &results[num_rounds].player1, sizeof(results[num_rounds].player1));
// 读选手 2 的出招
read(pipefd[0], &results[num_rounds].player2, sizeof(results[num_rounds].player2));
// 判断胜负
results[num_rounds].winner = compare(results[num_rounds].player1, results[num_rounds].player2);
num_rounds++;
while (num_rounds < 100) {
int move1, move2;
// 读选手 1 的出招
read(pipefd[0], &move1, sizeof(move1));
// 读选手 2 的出招
read(pipefd[0], &move2, sizeof(move2));
results[num_rounds].round = num_rounds;
results[num_rounds].player1 = move1;
results[num_rounds].player2 = move2;
// 判断胜负
results[num_rounds].winner = compare(move1, move2);
num_rounds++;
// 通知选手结果
write(pipefd[1], &results[num_rounds - 1].winner, sizeof(results[num_rounds - 1].winner));
}
close(pipefd[0]);
// 打印每盘的胜负情况和总的结果
printf("比赛结果:\n");
for (int i = 0; i < num_rounds; ++i) {
printf("第%d 轮:玩家 1 的出招是%d,玩家 2 的出招是%d,获胜者是%d\n", results[i].round + 1, results[i].player1, results[i].player2, results[i].winner);
}
int player1_wins = 0;
int player2_wins = 0;
for (int i = 0;
int player2_wins = 0;
for (int i = 0; i < num_rounds; ++i) {
if (results[i].winner == STONE) {
player1_wins++;
} else if (results[i].winner == SCISSORS) {
player2_wins++;
}
}
printf("总的结果:玩家 1 获胜%d 次,玩家 2 获胜%d 次\n", player1_wins, player2_wins);
}
int main() {
int pipefd[2];
pipe(pipefd);
// 创建选手 1 进程
pid_t pid1 = fork();
if (pid1 == 0) {
player_proc(pipefd);
exit(0);
}
// 创建选手 2 进程
pid_t pid2 = fork();
if (pid2 == 0) {
player_proc(pipefd);
exit(0);
}
// 创建裁判进程
referee_proc(pipefd);
// 等待子进程结束
int status;
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
// 关闭管道
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
2-1shiyan
于 2024-04-19 02:35:36 首次发布