summaryrefslogtreecommitdiffstats
path: root/hw2/player.c
blob: 03a2f58fc2a304b38182c265226db34716936f9c (plain) (blame)
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
/* b01902062 藍挺瑋 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "xwrap.h"

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

int main (int argc, char* argv[]) {
    if (argc < 4) {
        fprintf (stderr, "Usage: %s judge_id player_index random_key\n", argv[0]);
        return 1;
    }

    char* judge_id = argv[1];
    char* player_index = argv[2];
    char* random_key = argv[3];

    pid_t mypid = getpid();
    srandom (mypid + getppid () + getpgid (mypid) + getsid (mypid) + time (NULL));

    FILE* rf = NULL;
    FILE* wf = NULL;
    char* fifoname;
    int oth[4];
    int cnt[3] = { 0, 0, 0 };
    int i = 0;

    do {
        if (wf == NULL) {
            wf = fopen (fifoname = xstrcat ("judge", judge_id, ".FIFO", (char*)NULL), "wb");
            if (wf == NULL) {
                fprintf (stderr, "%s: Cannot open `%s\': %s\n", argv[0], fifoname, strerror (errno));
                return 1;
            }
            free (fifoname);
        }

        const char* val = "135";
        if (i) {
            fprintf (wf, "%s %s %c\n", player_index, random_key, val[random () % 3]);
        } else {
            int hismin = INT_MAX;
            int choice = 0;

            for (int j = 0; j < 4; j++) {
                switch (oth[j]) {
                    case 1: cnt[0]++; break;
                    case 3: cnt[1]++; break;
                    case 5: cnt[2]++; break;
                }
            }

            for (int j = 0; j < 3; j++) {
                if (cnt[j] < hismin) {
                    choice = j;
                    hismin = cnt[j];
                }
            }

            fprintf (wf, "%s %s %c\n", player_index, random_key, val[choice]);
        }
        fflush (wf);

        if (rf == NULL) {
            rf = fopen (fifoname = xstrcat ("judge", judge_id,
                "_", player_index, ".FIFO", (char*)NULL), "rb");
            if (rf == NULL) {
                fprintf (stderr, "%s: Cannot open `%s\': %s\n", argv[0], fifoname, strerror (errno));
                return 1;
            }
            free (fifoname);
        }
    } while (++i < 20 && fscanf (rf, "%d %d %d %d", &oth[0], &oth[1], &oth[2], &oth[3]) == 4);

    return 0;
}