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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
#include <stdio.h>
#include <stdlib.h>
#include "myarray.h"
#include "mystring.h"
enum {
O_PIECE,
X_PIECE,
EMPTY_PIECE,
};
const char piece[EMPTY_PIECE + 1] = {'O', 'X', ' '};
void print_field(MArray field) {
int i;
printf(" 1 2 3\n");
printf(" +---+---+---+\n");
for (i = 0; i < field->len; i++) {
if (i % 3 == 0) {
printf("%d ", i / 3 + 1);
}
printf("%c| %c", i % 3 != 0 ? ' ' : '\0', piece[myarray_get(field, int, i)]);
if (i % 3 == 2) {
printf(" |\n +---+---+---+\n");
}
}
}
MArray field_new() {
MArray field = myarray_new(9, 1, sizeof(char));
int i;
int piece = EMPTY_PIECE;
for (i = 0; i < 9; i++) {
myarray_append(field, piece);
}
return field;
}
unsigned int coords_to_index(unsigned int x, unsigned int y) {
return (x - 1) + (y - 1) * 3;
}
int get_winner(MArray field) {
int i, j;
int a1;
int a2;
int a3;
int a4;
int b1;
int b2;
int b3;
int b4;
for (i = 1; i < 4; i++) {
a1 = 0;
a2 = 0;
a3 = 0;
a4 = 0;
b1 = 0;
b2 = 0;
b3 = 0;
b4 = 0;
for (j = 1; j < 4; j++) {
switch (myarray_get(field, int, coords_to_index(i, j))) {
case O_PIECE:
a1++;
break;
case X_PIECE:
b1++;
break;
}
switch (myarray_get(field, int, coords_to_index(j, i))) {
case O_PIECE:
a2++;
break;
case X_PIECE:
b2++;
break;
}
}
switch (myarray_get(field, int, coords_to_index(i, i))) {
case O_PIECE:
a3++;
break;
case X_PIECE:
b3++;
break;
}
switch (myarray_get(field, int, coords_to_index(4-i, i))) {
case O_PIECE:
a4++;
break;
case X_PIECE:
b4++;
break;
}
if (a1 == 3 || a2 == 3 || a3 == 3 || a4 == 3) return O_PIECE;
if (b1 == 3 || b2 == 3 || b3 == 3 || b4 == 3) return X_PIECE;
}
return EMPTY_PIECE;
}
unsigned int prompt(MArray field, unsigned int player) {
char x, y;
unsigned int index;
MString input = mystring_new(2, 1);
while (1) {
printf("Enter coordinates for your piece, player %c: ", piece[player]);
mystring_clear(input);
mystring_getline(input, stdin);
switch (sscanf(input->str, "%c%c", &x, &y)) {
case EOF:
printf("\n");
exit(EXIT_SUCCESS);
break;
case 2:
index = coords_to_index(x - '0', y - '0');
if (index >= 9 || index < 0 || myarray_get(field, int, index) != EMPTY_PIECE) continue;
mystring_free(input);
return index;
}
}
}
int main(int argc, char **argv) {
MArray field = field_new();
int player = 0;
unsigned int index;
while (1) {
print_field(field);
if (get_winner(field) != EMPTY_PIECE) break;
index = prompt(field, player);
myarray_get(field, int, index) = player;
player ^= 1;
}
printf("Player %c won!\n", get_winner(field) == O_PIECE ? piece[O_PIECE] : piece[X_PIECE]);
myarray_free(field);
return 0;
}
|