Skip to content

Commit

Permalink
Fixed inverted player names, added some error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ad-oliviero committed Mar 4, 2021
1 parent e40d9f1 commit 075a50e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/client.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ void* client_comm() { // communicating data with the server (mostly receiving)
}

// write events
if (turn != user_id) click_position = -1; // set click only if it's client's turn
if (turn == user_id) click_position = -1; // set click only if it's client's turn
send(sock, (char *) &click_position, 4, 0);
if (click_position >= 0 || is_game_over) click_position = -1;
send(sock, (char *) &ready, 4, 0);
Expand Down
12 changes: 6 additions & 6 deletions src/server.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ int is_game_over = 0;
int game_grid[9] = {0};
int ready_check[2];
int turn = 0;
int user_id = 0;
int winsP0 = 0;
int winsP1 = 0;
int winner = 0;
Expand All @@ -32,7 +31,7 @@ int main(void) {
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
bind(server_fd, (struct sockaddr *)&address, sizeof(address));
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) return -1;

// accepting clients
listen(server_fd, 3);
Expand All @@ -49,11 +48,11 @@ int main(void) {
listen(server_fd, 3);
send(clientfd[0], (char *) &user0, sizeof(user0), 0);
send(clientfd[0], (char *) &user1, sizeof(user1), 0);
send(clientfd[0], (char *) &user_id, 4, 0);
user_id++;
send(clientfd[0], (char *) &turn, 4, 0);
turn++;
send(clientfd[1], (char *) &user0, sizeof(user0), 0);
send(clientfd[1], (char *) &user1, sizeof(user1), 0);
send(clientfd[1], (char *) &user_id, 4, 0);
send(clientfd[1], (char *) &turn, 4, 0);

// creating and joining threads
pthread_t tid[2];
Expand Down Expand Up @@ -83,13 +82,14 @@ void* communication(void* arg) { // communicating data with the client (mostly s
recv(clientfd[i], (char *) &click, 4, 0);
recv(clientfd[i], (char *) &ready_check[i], sizeof(ready_check), 0);
winner = checkwinner();
if (turn != i) click = -1; // accepting click only from player's turn client
if (turn == i) click = -1; // accepting click only from player's turn client
if (click != -1 && game_grid[click] == 0 && is_game_over == 0 ) { // handling clicks
if (turn) game_grid[click] = 1;
else game_grid[click] = 2;
turn = !turn;
}
if (ready_check[0] && ready_check[1]) endGame(winner); // checks if all clients are ready to continue
}
close(clientfd[i]);
pthread_exit(NULL);
}

0 comments on commit 075a50e

Please sign in to comment.