#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct ut_state { char tiles[9][9]; char boards[3][3]; int playBoard; char player; char host_player; }; const struct ut_state ut_initial = { .boards = {0}, .tiles = {0}, .playBoard = -1, .player = 'X', .host_player = '\0', }; const char *HELP_TEXT = "\ Usage: uttt (--local | --host | --join)\n\ \n\ --local play non-network game\n\ --host host game at 127.0.0.1:6669\n\ --join join game at 127.0.0.1:6669\n\ "; const char *arg_local = "--local"; const char *arg_host = "--host"; const char *arg_join = "--join"; char ut_turn(char player) { switch(player) { case 'X': return 'O'; case 'O': return 'X'; default: return '\0'; } } int ut_random_player(char *player) { int random = open("/dev/urandom", O_RDONLY); if (read(random, player, 1) < 0) {return errno;} *player = *player % 2 == 0 ? 'X' : 'O'; return 0; } #define T(r, c) (tiles[offset + stride * r + c]) char ut_winner(const char *tiles, int offset, int stride) { // whoreizontal wins for (int y = 0; y < 3; y++) { char tile = T(y, 0); if (tile == '\0') {continue;} if (tile == T(y, 1) && tile == T(y, 2)) {return tile;} } // vertical wins for (int x = 0; x < 3; x++) { char tile = T(0, x); if (tile == '\0') {continue;} if (tile == T(1, x) && tile == T(2, x)) {return tile;} } // diagonalz char tile = T(1, 1); if (tile != '\0') { if (tile == T(0, 0) && tile == T(2, 2)) {return tile;} if (tile == T(2, 0) && tile == T(0, 2)) {return tile;} } for(int y = 0; y < 3; y++) { for(int x = 0; x < 3; x++) { if(T(y, x) == '\0') {return '\0';} // in progress } } return ' '; // draw } int ut_move(struct ut_state *new_state, const struct ut_state *old_state, int row, int col) { // bad move - out of bounds if(row < 0 || row >= 9 || col < 0 || col >= 9) {return 1;} // state->playBoard == -1 means all boards playable; otherwise only one board is playable if (old_state->playBoard != -1 && old_state->playBoard != 3 * (row / 3) + (col / 3)) {return 1;} // bad move - tile is occupied if(old_state->tiles[row][col] != '\0') {return 1;} // bad move - board is finished if(old_state->boards[row / 3][col / 3] != '\0') {return 1;} // copy old_state->{tiles,boards} to new_state->{tiles,boards} memmove(new_state->tiles, old_state->tiles, sizeof(old_state->tiles)); memmove(new_state->boards, old_state->boards, sizeof(old_state->boards)); // do move new_state->tiles[row][col] = old_state->player; new_state->boards[row / 3][col / 3] = ut_winner((char *)new_state->tiles, 27 * (row / 3) + 3 * (col / 3), 9); // next play board - if next play board is not playable, play any board new_state->playBoard = new_state->boards[row % 3][col % 3] == '\0' ? 3 * (row % 3) + (col % 3) : -1; new_state->player = ut_turn(old_state->player); return 0; } void ut_drawBoard(const char *tiles, int offset, int stride, int iy, int ix, char winner, bool highlight) { // 5x5 board display /* * X|X|X * -+-+- * X|X|X * -+-+- * X|X|X */ for(int r = 0; r < 3; r++) for(int c = 0; c < 3; c++) mvaddch(iy + 2 * r, ix + 2 * c, T(r, c) != '\0' ? T(r, c) : ' '); //char info = winner != '\0' ? winner : highlight ? '*' : ' '; for(int r = 0; r < 3; r++) for(int c = 0; c < 2; c++) mvaddch(iy + 2 * r, ix + 2 * c + 1, winner != '\0' ? winner : '|'); for(int r = 0; r < 2; r++) for(int c = 0; c < 3; c++) mvaddch(iy + 2 * r + 1, ix + 2 * c, winner != '\0' ? winner : '-'); for(int r = 0; r < 2; r++) for(int c = 0; c < 2; c++) mvaddch(iy + 2 * r + 1, ix + 2 * c + 1, winner != '\0' ? winner : highlight ? '*' : '+'); } void ut_draw(const struct ut_state *state) { for(int r = 0; r < 3; r++) for(int c = 0; c < 3; c++) ut_drawBoard((char *)state->tiles, 27 * r + 3 * c, 9, 7 * r + 1, 7 * c + 1, state->boards[r][c], state->playBoard == -1 || state->playBoard == 3 * r + c); //refresh(); } int ut_click(const struct ut_state *state, int *r, int *c) { #define P(r, c, d) ((state->playBoard == -1 || state->playBoard == 3 * (r / 3) + (c / 3)) && \ (state->boards[r / 3][c / 3] == '\0' || d % 3 == 1)) MEVENT event; mvaddstr(21, 0, "Select move with arrow keys or mouse."); if(state->playBoard == -1) { *r = 3 * (*r / 3) + 1; *c = 3 * (*c / 3) + 1; } else { *r = 3 * (state->playBoard / 3) + 1; *c = 3 * (state->playBoard % 3) + 1; } for(;;) { /*if(state->boards[*r / 3][*c / 3] != '\0') { *r = 3 * (*r / 3) + 1; *c = 3 * (*c / 3) + 1; }*/ move((7 * (*r / 3) + 1) + (2 * (*r % 3)), (7 * (*c / 3) + 1) + (2 * (*c % 3))); refresh(); switch(getch()) { case KEY_MOUSE: if(getmouse(&event) == OK && (event.bstate & BUTTON1_CLICKED)) { if(event.y < 0 || event.y >= 21) {break;} if(event.x < 0 || event.x >= 21) {break;} *r = (event.y % 7 - 1) / 2 + 3 * (event.y / 7); *c = (event.x % 7 - 1) / 2 + 3 * (event.x / 7); if(((event.y % 7) - 1) % 2 != 0) {break;} if(((event.x % 7) - 1) % 2 != 0) {break;} return 0; } break; case 'k': /* FALLTHROUGH */ case 'w': /* FALLTHROUGH */ case KEY_UP: //*r = (((*r - 1) % 9) + 9) % 9; for(int i = 0; i < 9 + 1; i++) { *r = (*r + 9 - 1) % 9; if(P(*r, *c, *r)) {break;} } break; case 'h': /* FALLTHROUGH */ case 'a': /* FALLTHROUGH */ case KEY_LEFT: //*c = (((*c - 1) % 9) + 9) % 9; for(int i = 0; i < 9 + 1; i++) { *c = (*c + 9 - 1) % 9; if(P(*r, *c, *c)) {break;} } break; case 'j': /* FALLTHROUGH */ case 's': /* FALLTHROUGH */ case KEY_DOWN: //*r = (*r + 1) % 9; for(int i = 0; i < 9 + 1; i++) { *r = (*r + 1) % 9; if(P(*r, *c, *r)) {break;} } break; case 'l': /* FALLTHROUGH */ case 'd': /* FALLTHROUGH */ case KEY_RIGHT: //*c = (*c + 1) % 9; for(int i = 0; i < 9 + 1; i++) { *c = (*c + 1) % 9; if(P(*r, *c, *c)) {break;} } break; case ' ': /* FALLTHROUGH */ case '\r': /* FALLTHROUGH */ case KEY_ENTER: return 0; case ERR: /* FALLTHROUGH */ default: break; } } #undef P } int info_line; // set this to 21 and reset it on erase TODO void ut_info(const char *str, int n) { mvaddnstr(info_line, 0, str, n); // info_line++; // depends on str not containing newlines int y, x; getyx(stdscr, y, x); info_line = y + 1; } int ut_readfill(int fd, char *x, size_t l) { while(l > 0) { int r = read(fd, x, l); if(r < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {continue;} else {return 1;} } else if(r == 0) {return 2;} x += r; l -= r; } return 0; } int ut_writefill(int fd, const char *x, size_t l) { while(l > 0) { int r = write(fd, x, l); if(r < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {continue;} else {return 1;} } x += r; l -= r; } return 0; } #define MAX_LINE 128 int ut_dprintf(int fd, const char *restrict format, ...) { char line[MAX_LINE]; va_list ap; va_start(ap, format); int n = vsnprintf(line, MAX_LINE, format, ap); va_end(ap); if(n < 0 || n > MAX_LINE - 1) {return -1;} if(ut_writefill(fd, line, n)) {return -1;} return n; } int ut_cursprintf(const char *restrict format, ...) { char line[MAX_LINE]; va_list ap; va_start(ap, format); int n = vsnprintf(line, MAX_LINE, format, ap); va_end(ap); if(n < 0 || n > MAX_LINE - 1) {return -1;} ut_info(line, n); return n; } void ut_show(const struct ut_state *state, int fd, bool as_comment) { #define tiles state->tiles ut_dprintf(fd, "%sTurn: %c\n%sPlay board: %d\n", as_comment ? "| " : "", (int)state->player, as_comment ? "| " : "", state->playBoard); int play_board_row = -1; int play_board_col = -1; if (state->playBoard != -1) { play_board_row = state->playBoard / 3; play_board_col = state->playBoard % 3; } ut_dprintf(fd, "%s 012 345 678\n", as_comment ? "| " : ""); for(int y = 0; y < 9; y++) { if (y == 3 || y == 6) { ut_dprintf(fd, "%s ---+---+---\n", as_comment ? "| " : ""); } ut_dprintf(fd, "%s%d ", as_comment ? "| " : "", y); for(int x = 0; x < 9; x++) { if (x == 3 || x == 6) { ut_writefill(fd, "|", 1); } ut_writefill(fd, tiles[y][x] ? &tiles[y][x] : " ", 1); } if (y / 3 == play_board_row || play_board_row == -1) { ut_writefill(fd, "<", 1); } ut_writefill(fd, "\n", 1); } if (play_board_col == -1) { ut_dprintf(fd, "%s ^^^ ^^^ ^^^", as_comment ? "| " : ""); } else { ut_dprintf(fd, "%s ", as_comment ? "| " : ""); for (int i = 0; i < play_board_col; i++) { ut_dprintf(fd, " "); } ut_dprintf(fd, "^^^"); } ut_writefill(fd, "\n", 1); #undef tiles } void ut_show_boards(const struct ut_state *state) { for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { putchar(state->boards[j][i] ? state->boards[j][i] : ' '); } putchar('\n'); } } bool getpos(const struct ut_state *state, int *x, int *y) { while (true) { printf("Place token %c at position x,y: ", state->player); char line[5] = {0}; if (fgets(line, 5, stdin) == NULL) return false; // line was too short if (line[3] == '\0') continue; // line was too long if (line[3] != '\n') { // consume rest of line while (true) { int garbage = getchar(); if (garbage == EOF) return false; if (garbage == '\n') break; } continue; } int sscanf_result = sscanf(line, "%d,%d", x, y); if (sscanf_result == EOF) return false; if (sscanf_result != 2) continue; break; } return true; } void getpos_net(const struct ut_state *state, int sock, int *x, int *y) { // TODO const int MAX_LINE_LEN = 120; char byte; int n; while (true) { n = recv(sock, &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(sock, &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(sock); exit(1); } } else { if (byte == '\n') { printf("Partner ended line before coords were complete - retrying\n"); ut_dprintf(sock, "| Invalid coordinates. Try again: "); continue; } *x = byte - 0x30; n = recv(sock, &byte, 1, 0); if (n == 0) {goto conn_closed;} if (byte == '\n') { printf("Partner ended line before coords were complete - retrying\n"); ut_dprintf(sock, "| Invalid coordinates. Try again: "); continue; } n = recv(sock, &byte, 1, 0); if (n == 0) {goto conn_closed;} if (byte == '\n') { printf("Partner ended line before coords were complete - retrying\n"); ut_dprintf(sock, "| Invalid coordinates. Try again: "); continue; } *y = byte - 0x30; n = recv(sock, &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"); ut_dprintf(sock, "| Invalid coordinates. Try again: "); // ignore the rest of this line for (int i = 0; i < MAX_LINE_LEN; i++) { n = recv(sock, &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(sock); 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) { // putchar('\n'); endwin(); // other cleanup exit(0); } /*int main(int argc, char *argv[]) { signal(SIGINT, finish); initscr(); keypad(stdscr, TRUE); nonl(); // \r instead of \r\n cbreak(); noecho(); mousemask(BUTTON1_CLICKED, NULL); struct ut_state state = ut_initial; while (true) { int r, c, err; erase(); ut_draw(&state); char w = ut_winner((char *)state.boards, 0, 3); if(w) { if(w == ' ') { mvaddstr(21, 0, "Draw!"); } else { mvaddch(21, 0, w); mvaddstr(21, 1, " Wins!"); } mvaddstr(22, 0, "Press any key to exit."); refresh(); mousemask(0, NULL); getch(); break; } err = ut_click(&state, &r, &c); if (err) {continue;} err = ut_move(&state, &state, r, c); if (err) {continue;} } finish(0); return 0; }*/ int ut_local_game(struct ut_state *state) { // TODO replace with from ncurses main int x, y; while (true) { ut_show(state, 1, false); ut_show_boards(state); bool ok = getpos(state, &x, &y); if (!ok) {continue;} int err = ut_move(state, state, y, x); if (err) {continue;} char w = ut_winner((char *)state->boards, 0, 3); if(w) { if(w == ' ') { printf("\nDraw!\n"); } else { printf("\n%c wins!\n", (int)w); } break; } } return 0; } int ut_network_game(struct ut_state *state, int sock, char player) { // TODO int x, y; bool host = player == state->host_player; printf("You play as %c.\n", player); while (true) { ut_show(state, 1, false); ut_show_boards(state); ut_show(state, sock, true); if (state->player == player) { if (host) {ut_dprintf(sock, "| Waiting for game partner ...\n");} bool ok = getpos(state, &x, &y); if (!ok) {continue;} ut_dprintf(sock, "%d,%d\n", x, y); } else { printf("Waiting for game partner ...\n"); if (host) { ut_dprintf(sock, "|\n"); // aligns game board each turn ut_dprintf(sock, "| Place token %c in position x,y: ", ut_turn(player)); } getpos_net(state, sock, &x, &y); } int err = ut_move(state, state, y, x); if (err) {continue;} ut_dprintf(sock, "|\n"); char w = ut_winner((char *)state->boards, 0, 3); if(w) { if(w == ' ') { printf("\nDraw!\n"); } else { printf("\n%c wins!\n", (int)w); } break; } } return 0; } int ut_host_game(struct ut_state *state) { 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) }, }; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)); if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) { int errsv = errno; printf("error %d\n", errsv); return 1; } if (listen(sock, 128) == -1) { int errsv = errno; printf("error %d\n", errsv); return 1; } printf("Waiting for game partner at 127.0.0.1:6669 ...\n"); int conn = accept(sock, NULL, NULL); if (conn == -1) { int errsv = errno; printf("error %d\n", errsv); return 1; } // decide X or O if (ut_random_player(&state->host_player) != 0) {return 1;} // tell partner X or O ut_dprintf(conn, "%c\n", ut_turn(state->host_player)); // TODO return ut_network_game(state, conn, state->host_player); } int ut_join_game(struct ut_state *state) { 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)); // host decides X or O char player; int r = ut_readfill(sock, &player, 1); if (r == 2) {printf("Connection closed.\n");} if (r != 0) {return 1;} state->host_player = ut_turn(player); return ut_network_game(state, sock, player); } int main(int argc, char **argv) { signal(SIGINT, finish); struct ut_state state = ut_initial; if (argc != 2) { printf(HELP_TEXT); return 1; } else if (strncmp(argv[1], arg_local, strlen(arg_local)) == 0) { return ut_local_game(&state); } else if (strncmp(argv[1], arg_host, strlen(arg_host)) == 0) { return ut_host_game(&state); } else if (strncmp(argv[1], arg_join, strlen(arg_join)) == 0) { return ut_join_game(&state); } else { printf(HELP_TEXT, argv[1]); return 1; } }