network coords parsing

このコミットが含まれているのは:
ninya9k 2023-11-13 11:55:12 +00:00
コミット 61cfc2db1c
1個のファイルの変更72行の追加13行の削除

85
uttt.c
ファイルの表示

@ -188,19 +188,78 @@ bool getpos(const struct ut_state *state, int *x, int *y) {
return true;
}
void getpos_net(const struct ut_state *state, int conn, int *x, int *y) {
char buf[4];
int n = recv(conn, &buf, 4, 0); // lazy way but idc
printf("bytes received: %d\n", n);
printf("buf=%s\n", buf);
*x = buf[0] - 0x30;
*y = buf[2] - 0x30;
printf("x=%d y=%d\n", *x, *y);
if (buf[1] != ',' || buf[3] != '\n' || *x >= 9 || *y >= 9 || *x < 0 || *y < 0) {
printf("protocol not followed perfectly by partner - exiting\n");
close(conn);
exit(1);
void getpos_net(const struct ut_state *state, int conn, FILE* conn_file, int *x, int *y) {
const int MAX_LINE_LEN = 120;
char byte;
int n;
while (true) {
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte == '|') {
// ignore this line
for (int i = 0; i < MAX_LINE_LEN; i++) {
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte == '\n') {break;}
}
if (byte != '\n') {
printf("Partner sent too much data in one comment line - exiting\n");
close(conn);
exit(1);
}
} else {
if (byte == '\n') {
printf("Partner ended line before coords were complete - retrying\n");
fprintf(conn_file, "Invalid coordinates. Try again: ");
fflush(conn_file);
continue;
}
*x = byte - 0x30;
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte == '\n') {
printf("Partner ended line before coords were complete - retrying\n");
fprintf(conn_file, "Invalid coordinates. Try again: ");
fflush(conn_file);
continue;
}
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte == '\n') {
printf("Partner ended line before coords were complete - retrying\n");
fprintf(conn_file, "Invalid coordinates. Try again: ");
fflush(conn_file);
continue;
}
*y = byte - 0x30;
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte != '\n') {
printf("Partner sent extra data after coords were complete - ignoring and retrying\n");
fprintf(conn_file, "Invalid coordinates. Try again: ");
fflush(conn_file);
// ignore the rest of this line
for (int i = 0; i < MAX_LINE_LEN; i++) {
n = recv(conn, &byte, 1, 0);
if (n == 0) {goto conn_closed;}
if (byte == '\n') {break;}
}
if (byte != '\n') {
printf("Partner sent too much extra data - exiting\n");
close(conn);
exit(1);
}
continue;
}
break;
}
}
printf("x=%d y=%d\n", *x, *y);
return;
conn_closed:
printf("Connection closed.\n");
exit(1);
}
void finish(int sig)
@ -252,7 +311,7 @@ void ut_host_game(struct ut_state *state, int conn, char host_player) {
printf("Waiting for game partner ...\n");
fprintf(conn_file, "Place token %c in position x,y: ", ut_turn(host_player));
fflush(conn_file);
getpos_net(state, conn, &x, &y);
getpos_net(state, conn, conn_file, &x, &y);
}
int err = ut_move(state, state, y, x);
if (err) {continue;}