Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/c/go/go.c
364 views
1
#define EXTERN_GAME_H
2
#include "main.h"
3
4
char visited[WIDTH][HEIGHT];
5
int qx[SIZE], qy[SIZE]; // 理论上循环队列空间需要加一, 但这里不可能用尽
6
int sx[SIZE], sy[SIZE];
7
int qfront = 0, qrear = 0, top = 0;
8
9
// 围棋: 判断 (x,y) 所在的连通分量是否被围死
10
int go_isdead(int x, int y)
11
{
12
top = 0;
13
if (!bounded(x, y) || board[x][y] != color)
14
return 0;
15
int dx[] = {0, 0, -1, 1};
16
int dy[] = {1, -1, 0, 0};
17
18
// 广度优先
19
memset(visited, false, sizeof(visited));
20
qfront = qrear = 0;
21
qx[qrear] = x;
22
qy[qrear] = y;
23
qrear = (qrear+1) % SIZE;
24
visited[x][y] = true;
25
while (qfront != qrear) {
26
x = qx[qfront];
27
y = qy[qfront];
28
qfront = (qfront+1) % SIZE;
29
30
// 要移除的棋子入栈
31
sx[top] = x;
32
sy[top++] = y;
33
34
for (int i = 0; i < 4; ++i) {
35
x += dx[i];
36
y += dy[i];
37
if (bounded(x, y) && !visited[x][y]) {
38
if (board[x][y] == color) {
39
qx[qrear] = x;
40
qy[qrear] = y;
41
qrear = (qrear+1) % SIZE;
42
visited[x][y] = true;
43
} else if (board[x][y] == BLANK) {
44
return 0;
45
}
46
}
47
x -= dx[i];
48
y -= dy[i];
49
}
50
}
51
return top;
52
}
53
54
// 围棋: 吃掉含 (x,y) 的一个连通分量
55
int go_do_eat(int x, int y)
56
{
57
int ret = top = go_isdead(x, y);
58
while (top--) {
59
x = sx[top];
60
y = sy[top];
61
set_board(x, y, BLANK);
62
}
63
return ret;
64
}
65
66
// 围棋: 落子于 (x,y), 返回吃子数
67
int go_eat(int x, int y)
68
{
69
color = flip(color);
70
int ret
71
= go_do_eat(x, y+1)
72
+ go_do_eat(x, y-1)
73
+ go_do_eat(x-1, y)
74
+ go_do_eat(x+1, y);
75
if (ret)
76
MSG("提子: %d", ret);
77
color = flip(color);
78
return ret;
79
}
80
81
// 围棋: 若游戏结束, 返回 true
82
bool rule_go(int x, int y)
83
{
84
board[x][y] = color; // try
85
int flag_dead = go_isdead(x, y);
86
int flag_eat = go_eat(x, y);
87
if (flag_dead && !flag_eat) {
88
board[x][y] = BLANK; // restore
89
MSG("此处不可落子");
90
} else {
91
set_board(x, y, color);
92
color = flip(color);
93
}
94
return false;
95
}
96
97