This repository has been archived by the owner on May 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.cpp
435 lines (407 loc) · 13.7 KB
/
client.cpp
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#include "client.h"
// 菜单
const char *offlinemenu[] = {"游戏菜单 - 离线模式", "1. 重新连接服务器",
"2. AI 模式", "3. 退出游戏"};
const char *onlinemenu[] = {"游戏菜单 - 联机模式", "1. 开始匹配", "2. AI 模式",
"3. 退出游戏"};
/* 获取用户输入的 ASCII。
index: 菜单项对应的变量的地址
start:菜单项的最小值
end: 菜单项的最大值 */
int Client::GetMenuInput(unsigned int *index, unsigned int start,
unsigned int end) {
system("stty -icanon"); // 关闭缓冲区,输入字符无需按回车键
char command;
command = getchar();
system("stty icanon"); // 恢复规范输入
switch (command) {
case UP:
if (*index > start)
*index -= 1;
break;
case DOWN:
if (*index < end)
*index += 1;
break;
case ENTER:
return ENTER;
}
return command;
}
/* 显示用户菜单。
menu:菜单标题和菜单子项
size:菜单子项的数量
index:当前被选中的菜单项
bckgcolor:背景色,数值参考 VT控制码 的颜色问题
fregcolor:前景色
tilcolor:标题颜色
indexcolor:被选中的菜单项的颜色
menu 从零开始计数,无标题的话 index 和 i 上界都要要减一,但我这里默认有标题*/
void Client::ShowMenu(const char **menu, unsigned int size, unsigned int index,
unsigned int bckgcolor, unsigned int fregcolor,
unsigned int tilcolor, unsigned int indexcolor,
float rowscale, float colscale) {
unsigned int posrow = rowscale * windows.ws_row;
unsigned int poscol = colscale * windows.ws_col;
system("clear"); // 清空控制台
for (unsigned int i = 0; i <= size; i++) {
if (i == index) { // 被选中的菜单子项
printf("\033[%dC", poscol); // 光标右移动
printf("\033[%d;%dm", bckgcolor, indexcolor);
printf(" ->%s\n", menu[i]);
printf("\033[%d;%dm", bckgcolor, fregcolor);
} else if (i == 0) { // 菜单标题
printf("\033[%dB\033[%dC", posrow, poscol); // 光标下移、右移动
printf("\033[%d;%dm", bckgcolor, tilcolor);
printf("%s\n", menu[i]);
printf("\033[%d;%dm", bckgcolor, fregcolor);
} else { // 未选中的菜单子项
printf("\033[%dC", poscol); // 光标右移动
printf(" %s\n", menu[i]);
}
}
}
/* 初始化背景色和前景色。
设置主要是为了刚开始全终端都是背景色,不设置的话只有一小块是背景色很突兀,
虽然这突兀的情况在用户输入一次后就会消失
bckgcolor:背景色,数值参考 VT控制码 的颜色问题
fregcolor:前景色
*/
void Client::SetColor(unsigned int bckgcolor, unsigned int fregcolor) {
printf("\033[%d;%dm", bckgcolor, fregcolor);
printf("\033[2J"); // 清空控制台,和 system("clear"); 效果还是有点区别的
}
void Client::ResetColor() { printf("\033[0m"); }
Client::Client() {
// 由域名获取 IP
struct hostent *host = gethostbyname(DOMAIN);
if (!host) {
perror("Get IP address error!");
exit(EXIT_FAILURE);
}
memset(&this->serv_addr, 0, sizeof(this->serv_addr)); //每个字节都用0填充
this->serv_addr.sin_family = AF_INET; //使用IPv4地址
this->serv_addr.sin_port = htons(PORT); //端口
if (inet_pton(AF_INET, inet_ntoa(*(struct in_addr *)host->h_addr_list[0]),
&this->serv_addr.sin_addr) <= 0) { // IP 地址绑定和检查
perror("Error: Invalid address/ Address not supported");
exit(EXIT_FAILURE);
}
ioctl(STDOUT_FILENO, TIOCGWINSZ, &windows); // 获取终端的行数、列数(高、宽)
SetColor(47, 30); // 背景色 47-白色,前景色(字体颜色) 30-黑色
}
bool Client::Connect() {
// 创建套接字
this->sock = socket(AF_INET, SOCK_STREAM, 0);
if (this->sock < 0) {
perror("Error: Socket creation failed");
close(sock);
exit(EXIT_FAILURE);
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("Error: Connection creation failed");
close(sock);
return false;
} else {
return true;
}
}
bool Client::Start() {
bool iscon = false;
bool isFinish = false;
while (!isFinish) {
iscon = this->Connect();
if (iscon) { // 联机模式
if (read(sock, bufRecv, sizeof(bufRecv)) == -1) { // 接收自己的序号
perror("套接字已被关闭 read");
close(sock);
return false;
} else {
// std::cout << bufRecv << std::endl;
}
while (true) {
ShowMenu(onlinemenu, 3, menuindex);
if (GetMenuInput(&menuindex, 1, 3) == ENTER) {
if (menuindex == 3) { // 逐步终止程序
isFinish = true;
shutdown(sock, SHUT_WR);
read(sock, bufSend, sizeof(bufSend));
return 0;
} else if (menuindex == 2) { // 人机模式
this->PlayAI();
} else if (menuindex == 1) { // 联机模式
clearScreen();
std::cout << "正在寻找对手" << std::endl;
std::sprintf(bufSend, "\\S");
if (write(sock, bufSend, sizeof(bufSend)) == -1) { // 发送匹配申请
perror("套接字已被关闭 write");
close(sock);
return false;
}
if (read(sock, bufRecv, sizeof(bufRecv)) == -1) { // 接收匹配结果
perror("套接字已被关闭 read");
close(sock);
return false;
} else if (bufRecv[0] == '\\' &&
bufRecv[1] == 'G') { // 匹配到可能的对手
char *result = NULL;
result = strtok(bufRecv, " "); // \G
result = strtok(NULL, " "); // 目标套接字
int target = atoi(result);
result = strtok(NULL, " "); // 指令,是否先手
bool isfirst = false;
if (!strcmp(result, "step1")) {
puts("YOu first");
isfirst = true;
}
// 开始游戏
clearScreen();
showBoard();
int winner = -1;
// 默认 先手 1 是自己,后手 2 是自己
int count = 0, turn, pos;
while (count < 9) {
turn = count % 2 + 1;
clearScreen();
showBoard();
if (turn == 2) {
if (isfirst) { // 先手等待
std::cout << "等待对方落子中...\n";
read(sock, bufRecv, sizeof(bufRecv));
result = NULL;
result = strtok(bufRecv, " "); // \p
result = strtok(NULL, " "); // 套接字
result = strtok(NULL, " "); // 落子位置
pos = atoi(result);
} else { // 后手下棋
std::cout << "轮到你落子啦: ";
pos = checkInput();
std::sprintf(bufSend, "\\p %d %d", target,
pos); // 向对方发送自己的棋
write(sock, bufSend, sizeof(bufSend));
}
} else { // turn 1
if (isfirst) { // 先手
std::cout << "轮到你落子啦: ";
pos = checkInput();
std::sprintf(bufSend, "\\p %d %d", target,
pos); // 向对方发送自己的棋
write(sock, bufSend, sizeof(bufSend));
} else { // 后手等待
std::cout << "等待对方落子中...\n";
read(sock, bufRecv, sizeof(bufRecv));
result = NULL;
result = strtok(bufRecv, " "); // \p
result = strtok(NULL, " "); // 套接字
result = strtok(NULL, " "); //
pos = atoi(result);
}
}
BOARD[pos] = turn;
winner = checkWinner();
if (winner > -1) {
break;
}
count++;
}
ShowWinner(winner, isfirst);
std::sprintf(bufSend, "\\W"); // 告诉服务器我游戏结束了
write(sock, bufSend, sizeof(bufSend));
read(sock, bufRecv, sizeof(bufRecv));
} else {
std::cout << "还没有匹配到和你一样机智的人类. 按 回车键 继续"
<< std::endl;
getchar();
}
}
}
}
} else { // 连接失败的时候
ShowMenu(offlinemenu, 3, menuindex);
if (GetMenuInput(&menuindex, 1, 3) == ENTER) {
if (menuindex == 3) {
break;
} else if (menuindex == 2) {
this->PlayAI();
}
}
}
}
return false;
}
void Client::showBoard(unsigned int bckgcolor, unsigned int fregcolor,
unsigned int Acolor, unsigned int Bcolor, float rowscale,
float colscale) {
// 显示棋盘以及棋子,四个参数分别是前景色、背景色,A棋颜色,B棋颜色,均有默认值
unsigned int posrow = rowscale * windows.ws_row;
unsigned int poscol = colscale * windows.ws_col;
// printf("\033[%dB", posrow); // 光标下移、右移动
printf("\033[%dB\033[%dC", posrow, poscol); // 光标下移、右移动
for (int i = 0; i < 9; i++) {
std::cout << " __";
if (BOARD[i] == 0) {
std::cout << i;
} else {
if (BOARD[i] == 1) {
printf("\033[%d;%dm", bckgcolor, Acolor);
std::cout << CHESSA;
printf("\033[%d;%dm", bckgcolor, fregcolor);
} else {
printf("\033[%d;%dm", bckgcolor, Bcolor);
std::cout << CHESSB;
printf("\033[%d;%dm", bckgcolor, fregcolor);
}
}
if ((i + 1) % 3 == 0) {
std::cout << "__" << std::endl;
if (i < 7) {
printf("\033[%dC", poscol); // 光标右移动
}
} else {
std::cout << "__ |";
}
}
}
int Client::checkInput() {
int pos = -1;
while (pos < 0 || pos > 8) {
std::cin >> pos;
if (BOARD[pos] != 0) {
std::cout << "唉,这个位置好像不能落子了呢,再选一个位置吧" << std::endl;
pos = -1;
}
}
return pos;
}
int Client::checkWinner() {
// 检测赢家,返回值 -1(无赢家) or 1(玩家一) or 2(玩家二)or 0 (平手)
int winner = -1;
for (int i = 0; i < 3; i++) {
if (BOARD[i] == BOARD[i + 3] && BOARD[i + 3] == BOARD[i + 6] &&
BOARD[i] != 0) { // 竖
winner = BOARD[i];
break;
} else if (BOARD[i * 3] == BOARD[i * 3 + 1] &&
BOARD[i * 3 + 1] == BOARD[i * 3 + 2] &&
BOARD[i * 3] != 0) { // 横
winner = BOARD[i * 3];
break;
}
}
// 对角线
if (BOARD[0] == BOARD[4] && BOARD[4] == BOARD[8] && BOARD[4] != 0) {
winner = BOARD[4];
} else if (BOARD[2] == BOARD[4] && BOARD[4] == BOARD[6] && BOARD[4] != 0) {
winner = BOARD[4];
}
if (winner == -1) { // 检查是否平手
winner = 0; // 假设平手
for (unsigned int i = 0; i < 9; i++) {
if (BOARD[i] == 0) { // 有空位置没下,推翻假设
winner = -1;
break;
}
}
}
return winner;
}
void Client::clearScreen() { system("clear"); }
int Client::AIInput() {
unsigned int i = 0;
bool found = false;
while (!found && i < 9) {
if (BOARD[i] == 0) {
BOARD[i] = 2; // 一下能赢的棋
if (checkWinner() == 2) {
found = true;
}
BOARD[i] = 0;
BOARD[i] = 1; // 不下会输的棋
if (checkWinner() == 1) {
found = true;
}
BOARD[i] = 0;
}
i++;
}
if (!found) { //第三种策略
const int next[9] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
unsigned int k = 0;
while (!found && k < 9) {
if (BOARD[next[k]] == 0) {
found = true;
}
k++;
}
return next[k - 1];
} else {
return i - 1; // 前两中策略有效
}
}
void Client::PlayAI() {
clearScreen();
showBoard();
int winner = -1;
// 默认玩家 1 是用户,玩家 2 是电脑
int count = 0, turn;
while (count < 9) {
int pos;
turn = count % 2 + 1;
if (turn == 2) {
pos = AIInput();
} else {
std::cout << "轮到机智的你落子啦: ";
pos = checkInput();
}
BOARD[pos] = turn;
clearScreen();
showBoard();
winner = checkWinner();
if (winner != -1) {
break;
}
count++;
}
ShowWinner(winner);
}
void Client::Reset() {
for (unsigned int i = 0; i < 9; i++) {
this->BOARD[i] = 0;
}
}
void Client::Close() { close(this->sock); }
/* 输出赢家输家。
winner:赢家 0~2
isfirst:是否先手,针对联机模式。离线模式默认 true
*/
void Client::ShowWinner(int winner, bool isfirst) {
this->Reset(); // 不重置再重新开局的话就棋盘还在
switch (winner) {
case 1:
if (isfirst) {
std::cout << "太棒了!你赢了这场智力比拼!" << std::endl;
} else {
std::cout << "对方险胜你一筹,还需要努力哟" << std::endl;
}
break;
case 2:
if (isfirst) {
std::cout << "对方险胜你一筹,还需要努力哟" << std::endl;
} else {
std::cout << "太棒了!你赢了这场智力比拼!" << std::endl;
}
break;
case 0:
std::cout << "这次不分伯仲呢" << std::endl;
break;
}
std::cout << "玩耍结束. 按 回车键 继续" << std::endl;
getchar(); // 两个模拟暂停
getchar();
}
int main() {
Client cli;
cli.Start();
cli.ResetColor();
return 0;
}