-
Notifications
You must be signed in to change notification settings - Fork 0
/
omok.c
120 lines (102 loc) · 2.44 KB
/
omok.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* @file omok.c
* @author Gyeongtae Kim(dev-dasae) <[email protected]>
*
* @brief Omok game implementation.
* @details This file contains the implementation of the Omok game.
*
* @version 0.1
* @date 2024-06-21
*
* @copyright Released under the MIT License. See LICENSE file for details.
*/
#include "omok.h"
#include <stdio.h>
void Board_init(Board* board) {
for (int i = 0; i < Board_kSize; ++i) {
for (int j = 0; j < Board_kSize; ++j) {
board->grid[i][j] = '.';
}
}
}
void Board_print(Board* board) {
for (int i = 0; i < Board_kSize; ++i) {
for (int j = 0; j < Board_kSize; ++j) {
printf("%c ", board->grid[i][j]);
}
printf("\n");
}
}
bool Board_isValidMove(Board* board, Point point) {
return (0 <= point.x && point.x < Board_kSize) &&
(0 <= point.y && point.y < Board_kSize) &&
(board->grid[point.x][point.y] == '.');
}
bool Board_hasWinner(Board* board, Point point) {
char player = board->grid[point.x][point.y];
// Check horizontal
int count = 0;
for (int j = 0; j < Board_kSize; ++j) {
if (board->grid[point.x][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// Check vertical
count = 0;
for (int i = 0; i < Board_kSize; ++i) {
if (board->grid[i][point.y] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// Check diagonal (top-left to bottom-right)
count = 0;
int i = point.x - point.y;
int j = 0;
if (i < 0) {
j = -i;
i = 0;
}
while (i < Board_kSize && j < Board_kSize) {
if (board->grid[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
i++;
j++;
}
// Check diagonal (top-right to bottom-left)
count = 0;
i = point.x + point.y;
j = 0;
if (Board_kSize <= i) {
j = i - Board_kSize + 1;
i = Board_kSize - 1;
}
while (0 <= i && j < Board_kSize) {
if (board->grid[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
i--;
j++;
}
return false;
}