Step 1: 安装必要的工具

1
2
sudo apt-get update
sudo apt-get install build-essential

Step 2: 创建和编辑源代码文件

1
gedit rps_game.c

将下面的代码粘贴进去,然后保存并退出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include <unistd.h>

#define ROCK 0
#define PAPER 1
#define SCISSORS 2

struct Game {
long type;
int round;
};

void result_send(int msgid) {
struct Game game;
game.type = 1;
game.round = rand() % 3;
msgsnd(msgid, &game, sizeof(int), 0);
}

int result_announce(int a, int b) {
if ((a + 1) % 3 == b) return -1; // A wins
else if (a == b) return 0; // Draw
else return 1; // B wins
}

void print_results(int *result_list, int len) {
int countA = 0, countB = 0, pingju = 0;
for (int i = 0; i < len; i++) {
switch (result_list[i]) {
case -1:
countA++;
printf("NO.%d:A win\n", i + 1);
break;
case 0:
pingju++;
printf("NO.%d:end in a draw\n", i + 1);
break;
case 1:
countB++;
printf("NO.%d:B win\n", i + 1);
break;
}
}
printf("The final result is A win:%ds\nB win:%ds\nend in a draw %ds\n", countA, countB, pingju);
}

int main() {
int times;
printf("Game start, please input rounds: ");
scanf("%d", &times);

int *result_list = (int*)malloc(times * sizeof(int));
int msgid1 = msgget(1234, IPC_CREAT | 0666);
int msgid2 = msgget(5678, IPC_CREAT | 0666);

pid_t pid1 = fork();
if (pid1 == 0) {
srand(time(NULL) * 3000);
for (int i = 0; i < times; i++) result_send(msgid1);
exit(0);
}

pid_t pid2 = fork();
if (pid2 == 0) {
srand(time(NULL));
for (int i = 0; i < times; i++) result_send(msgid2);
exit(0);
}

wait(NULL);
wait(NULL);

for (int i = 0; i < times; i++) {
struct Game game1, game2;
msgrcv(msgid1, &game1, sizeof(int), 0, 0);
msgrcv(msgid2, &game2, sizeof(int), 0, 0);
result_list[i] = result_announce(game1.round, game2.round);
}

print_results(result_list, times);

msgctl(msgid1, IPC_RMID, 0);
msgctl(msgid2, IPC_RMID, 0);

free(result_list);

return 0;
}

Step 3: 编译源代码

1
gcc -o rps_game rps_game.c

Step 4: 运行程序

1
./rps_game

程序会提示你输入比赛轮数,例如输入 10,然后程序将执行并在终端打印每轮比赛结果和最终统计结果。

运行示例

运行程序后,如果输入 10 作为比赛轮数,则输出结果将类似以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Game start, please input rounds: 10
NO.1:end in a draw
NO.2:A win
NO.3:A win
NO.4:B win
NO.5:A win
NO.6:B win
NO.7:B win
NO.8:end in a draw
NO.9:end in a draw
NO.10:B win
The final result is A win:3s
B win:4s
end in a draw 3s