Merge remote-tracking branch 'origin/network' into network

このコミットが含まれているのは:
woosh 2023-11-13 04:53:53 -08:00
コミット 534ea26de3
1個のファイルの変更29行の追加11行の削除

40
uttt.c
ファイルの表示

@ -447,7 +447,7 @@ void ut_local_game(struct ut_state *state) { // TODO replace with from ncurses m
ut_show_boards(state);
bool ok = getpos(state, &x, &y);
if (!ok) {continue;}
int err = ut_move(state, state, x, y);
int err = ut_move(state, state, y, x);
if (err) {continue;}
char w = ut_winner((char *)state->boards, 0, 3);
if(w)
@ -464,22 +464,22 @@ void ut_local_game(struct ut_state *state) { // TODO replace with from ncurses m
}
}
void ut_host_game(struct ut_state *state, int conn, char host_player) {
void ut_network_game(struct ut_state *state, int conn, FILE* conn_file, char player) {
int x, y;
printf("You play as %c.\n", host_player);
FILE* conn_file = fdopen(conn, "w");
printf("You play as %c.\n", player);
while (true) {
ut_show(state, stdout, false);
ut_show_boards(state);
ut_show(state, conn_file, true);
if (state->player == host_player) {
if (state->player == player) {
fprintf(conn_file, "| Waiting for game partner ...\n");
fflush(conn_file);
bool ok = getpos(state, &x, &y);
if (!ok) {continue;}
fprintf(conn_file, "%d,%d\n", x, y);
} else {
printf("Waiting for game partner ...\n");
fprintf(conn_file, "| Place token %c in position x,y: ", ut_turn(host_player));
fprintf(conn_file, "| Place token %c in position x,y: ", ut_turn(player));
fflush(conn_file);
getpos_net(state, conn, conn_file, &x, &y);
}
@ -536,15 +536,33 @@ int main(int argc, char **argv) {
printf("error %d\n", errsv);
return 1;
}
FILE* conn_file = fdopen(conn, "w");
// decide X or O
int random = open("/dev/urandom", O_RDONLY);
int byte;
read(random, &byte, 1);
//printf("%d\n", byte);
char host_player = byte % 2 == 0 ? 'X' : 'O';
//printf("%c\n", host_player);
ut_host_game(&state, conn, host_player);
char player = byte % 2 == 0 ? 'X' : 'O';
// tell partner X or O
fprintf(conn_file, "%c\n", ut_turn(player));
ut_network_game(&state, conn, conn_file, player);
} else if (strncmp(argv[1], arg_join, strlen(arg_join)) == 0) {
printf("no ;)\n");
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
int errsv = errno;
printf("error %d\n", errsv);
return 1;
}
const struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(6669),
.sin_addr = { .s_addr = htonl(0x7f000001) },
};
printf("Connecting to game host at 127.0.0.1:6669 ...\n");
connect(sock, (struct sockaddr*)&addr, sizeof(addr));
FILE* sock_file = fdopen(sock, "w");
char player_buf[2];
if (recv(sock, &player_buf, 2, 0) != 2) {return 1;}
ut_network_game(&state, sock, sock_file, player_buf[0]);
} else {
printf("%s\n", argv[1]);
}