-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic_board.c
102 lines (87 loc) · 2.58 KB
/
tic_board.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
96
97
98
99
100
101
102
#include <stdio.h>
#include <stdlib.h>
#include "tic_board.h"
void initMatrix(Tic_Matrix * pntr_tm)
{
for(int i = 0; i < TIC_N; i++)
{
pntr_tm -> x[i].counter = 0;
pntr_tm -> y[i].counter = 0;
}
pntr_tm -> diag1.counter = 0;
pntr_tm -> diag2.counter = 0;
}
void win(bool is_x)
{
if(is_x)
printf("Player X win");
else
printf("Player O win");
getc(stdin);
exit(0);
}
void turn(Tic_Matrix * pntr_tm, char entry, int x, int y)
{
bool is_x = entry == 'X' ? 1 : 0;
// Check if entry belong to the first diagonal
if(x == y)
{
// Check if entry is different from entries across diag1
if(pntr_tm -> diag1.counter && is_x != pntr_tm -> diag1.is_x || pntr_tm -> diag1.counter == -1)
pntr_tm -> diag1.counter = -1;
else
{
pntr_tm -> diag1.counter++;
pntr_tm -> diag1.is_x = is_x;
}
// Check a win
if(pntr_tm -> diag1.counter == TIC_N)
win(pntr_tm -> diag1.is_x);
}
// Check if entry belong to the second diagonal
if((TIC_N - x) == (y - 1))
{
// Check if entry is different from entries across diag2
if(pntr_tm -> diag2.counter && is_x != pntr_tm -> diag2.is_x || pntr_tm -> diag2.counter == -1)
pntr_tm -> diag2.counter = -1;
else
{
pntr_tm -> diag2.counter++;
pntr_tm -> diag2.is_x = is_x;
}
// Check a win
if(pntr_tm -> diag2.counter == TIC_N)
win(pntr_tm -> diag2.is_x);
}
// Check if entry is different from entries across column x
if(pntr_tm -> x[x - 1].counter && is_x != pntr_tm -> x[x - 1].is_x || pntr_tm -> x[x - 1].counter == -1)
pntr_tm -> x[x - 1].counter = -1;
else
{
pntr_tm -> x[x - 1].counter++;
pntr_tm -> x[x - 1].is_x = is_x;
}
// Check if entry is different from entries across row y
if(pntr_tm -> y[y - 1].counter && is_x != pntr_tm -> y[y - 1].is_x || pntr_tm -> y[y - 1].counter == -1)
pntr_tm -> y[y - 1].counter = -1;
else
{
pntr_tm -> y[y - 1].counter++;
pntr_tm -> y[y - 1].is_x = is_x;
}
// Check a win
if(pntr_tm -> x[x - 1].counter == TIC_N)
win(pntr_tm -> x[x - 1].is_x);
if(pntr_tm -> y[y - 1].counter == TIC_N)
win(pntr_tm -> y[y - 1].is_x);
}
void clear(Tic_Matrix * pntr_tm)
{
for(int i = 0; i < TIC_N; i++)
{
pntr_tm -> x[i - 1].counter = 0;
pntr_tm -> y[i - 1].counter = 0;
}
pntr_tm -> diag1.counter = 0;
pntr_tm -> diag2.counter = 0;
}