-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
798 lines (669 loc) · 24.2 KB
/
Copy pathserver.cpp
File metadata and controls
798 lines (669 loc) · 24.2 KB
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// UNO Game Server - Combined Source File
// This file includes all server-side code: game logic, scheduler, client handler, and logger
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fstream>
#include <vector>
#include <signal.h>
#include <ctime>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <cctype>
//==============================================================================
// CONSTANTS AND DEFINITIONS
//==============================================================================
#define SHM_NAME "/uno_game_shm"
#define PORT 8080
#define SCORES_FILE "scores.txt"
#define MAX_PLAYERS 5
#define MAX_HAND_SIZE 20
#define DECK_SIZE 108
//==============================================================================
// DATA STRUCTURES
//==============================================================================
// Color: 'R'(Red), 'G'(Green), 'B'(Blue), 'Y'(Yellow), 'W'(Wild/Black)
// Value: 0-9 (Number), 10 (Skip), 11 (Reverse), 12 (DrawTwo), 13 (Wild), 14 (WildDraw4)
struct Card
{
char color;
int value;
};
struct SharedGameState
{
// === synchronization ===
pthread_mutex_t mutex;
pthread_cond_t turn_cond;
// === UNO game state ===
Card deck[DECK_SIZE];
int deck_top_index;
Card discard_pile_top;
Card player_hands[MAX_PLAYERS][MAX_HAND_SIZE];
int hand_counts[MAX_PLAYERS]; // Number of cards in each player's hand
// === game flow control ===
int current_player_id;
int total_players;
int direction;
bool skip_next;
int draw_penalty;
// === system status ===
bool is_active[MAX_PLAYERS];
int scores[MAX_PLAYERS];
bool game_running;
bool turn_completed;
// [NEW] Winner ID to broadcast result
int winner_id;
// === connection status ===
int connected_count;
};
// Fixed size struct for IPC logging
struct LogEntryIPC
{
time_t timestamp;
int player_id;
char message[256];
};
//==============================================================================
// LOGGER CLASS
//==============================================================================
class GameLogger
{
private:
static int pipe_fds[2]; // 0: read, 1: write
static bool logger_running;
static pthread_t logger_thread;
public:
static void initLogger()
{
if (pipe(pipe_fds) == -1)
{
perror("pipe");
exit(1);
}
logger_running = true;
pthread_create(&logger_thread, NULL, loggerThreadFunc, NULL);
}
static void logEvent(const std::string &message, int player_id = -1)
{
LogEntryIPC entry;
entry.timestamp = time(0);
entry.player_id = player_id;
strncpy(entry.message, message.c_str(), sizeof(entry.message) - 1);
entry.message[sizeof(entry.message) - 1] = '\0';
// Atomic write to pipe (size < PIPE_BUF)
write(pipe_fds[1], &entry, sizeof(entry));
}
static void stopLogger()
{
logEvent("STOP_LOGGER", -999);
logger_running = false;
pthread_join(logger_thread, NULL);
close(pipe_fds[0]);
close(pipe_fds[1]);
}
static void* loggerThreadFunc(void *arg)
{
(void)arg;
std::ofstream logfile("game.log", std::ios::app);
LogEntryIPC entry;
while (logger_running)
{
ssize_t bytes = read(pipe_fds[0], &entry, sizeof(entry));
if (bytes <= 0) break;
if (entry.player_id == -999) break;
// Format timestamp
struct tm *timeinfo = localtime(&entry.timestamp);
char timestamp[50];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", timeinfo);
// Log to file
logfile << "[" << timestamp << "]";
if (entry.player_id >= 0)
{
logfile << " [Player " << entry.player_id << "]";
}
logfile << " " << entry.message << std::endl;
logfile.flush();
std::cout << "[" << timestamp << "]";
if (entry.player_id >= 0)
{
std::cout << " [Player " << entry.player_id << "]";
}
std::cout << " " << entry.message << std::endl;
}
logfile.close();
return NULL;
}
};
// Static member definitions
int GameLogger::pipe_fds[2];
bool GameLogger::logger_running = false;
pthread_t GameLogger::logger_thread;
//==============================================================================
// GAME RULES CLASS
//==============================================================================
class GameRules
{
public:
static void initGame(SharedGameState *game)
{
srand(time(0));
// 1. create deck
int idx = 0;
char colors[] = {'R', 'G', 'B', 'Y'};
for (char c : colors)
{
game->deck[idx++] = {c, 0};
for (int v = 1; v <= 9; v++)
{
game->deck[idx++] = {c, v};
game->deck[idx++] = {c, v};
}
game->deck[idx++] = {c, 10}; // Skip
game->deck[idx++] = {c, 12}; // Draw Two
}
while (idx < DECK_SIZE)
{
game->deck[idx++] = {'W', 13}; // Wild
}
game->deck_top_index = 0;
// 2. Knuth Shuffle
for (int i = idx - 1; i > 0; i--)
{
int j = rand() % (i + 1);
Card temp = game->deck[i];
game->deck[i] = game->deck[j];
game->deck[j] = temp;
}
// 3. 7 cards to each player
for (int p = 0; p < MAX_PLAYERS; p++)
{
game->hand_counts[p] = 0;
for (int k = 0; k < 7; k++)
{
drawCard(game, p);
}
game->is_active[p] = false;
}
game->discard_pile_top = game->deck[game->deck_top_index++];
// 4. initialize game state
game->current_player_id = 0;
game->direction = 1;
game->skip_next = false;
game->draw_penalty = 0;
game->game_running = true;
game->turn_completed = false;
// [NEW] Initialize winner_id
game->winner_id = -1;
}
// player draws a card
static void drawCard(SharedGameState *game, int player_id)
{
if (game->deck_top_index >= DECK_SIZE)
{
game->deck_top_index = 0;
}
int count = game->hand_counts[player_id];
if (count < MAX_HAND_SIZE)
{
game->player_hands[player_id][count] = game->deck[game->deck_top_index++];
game->hand_counts[player_id]++;
}
}
// logic to check if a played card is valid
static bool isValidMove(SharedGameState *game, int player_id, int card_index)
{
if (card_index < 0 || card_index >= game->hand_counts[player_id])
return false;
Card played = game->player_hands[player_id][card_index];
Card top = game->discard_pile_top;
// 1. same color
if (played.color == top.color)
return true;
// 2. same value
if (played.value == top.value)
return true;
// 3. wild card
if (played.color == 'W')
return true;
// [Safety Fix] If top card is Wild, any card can be played (if no color was enforced/or just simplified)
// Note: The upgraded playCard logic enforces color declaration for new wilds,
// but checking 'W' on top here ensures we don't block play if previous was Wild.
if (top.color == 'W')
return true;
return false;
}
// player plays a card
static void playCard(SharedGameState *game, int player_id, int card_index, char wild_color = '\0')
{
Card played = game->player_hands[player_id][card_index];
// For Wild cards, use the declared color instead of 'W'
if (played.color == 'W' && wild_color != '\0')
{
game->discard_pile_top = {wild_color, played.value};
}
else
{
game->discard_pile_top = played;
}
int count = game->hand_counts[player_id];
for (int i = card_index; i < count - 1; i++)
{
game->player_hands[player_id][i] = game->player_hands[player_id][i + 1];
}
game->hand_counts[player_id]--;
if (played.value == 10)
{ // Skip
game->skip_next = true;
}
else if (played.value == 12)
{ // Draw Two
game->draw_penalty = 2;
}
else if (played.value == 11)
{ // Reverse
game->direction *= -1;
}
else if (played.value == 14)
{ // Wild Draw Four
game->draw_penalty = 4;
}
if (game->hand_counts[player_id] == 0)
{
game->game_running = false;
game->scores[player_id]++;
// [NEW] Set the winner
game->winner_id = player_id;
}
game->turn_completed = true;
}
};
//==============================================================================
// SCHEDULER (Round Robin)
//==============================================================================
void *round_robin_scheduler(void *arg)
{
SharedGameState *game = (SharedGameState *)arg;
while (true)
{
pthread_mutex_lock(&game->mutex);
if (!game->game_running)
{
pthread_mutex_unlock(&game->mutex);
break;
}
if (!game->turn_completed)
{
pthread_mutex_unlock(&game->mutex);
usleep(50000);
continue;
}
int next = (game->total_players + game->current_player_id + game->direction) % game->total_players;
while (!game->is_active[next] && game->total_players > 0)
{
next = (game->total_players + next + game->direction) % game->total_players;
}
if (game->skip_next)
{
std::cout << "[Scheduler] Player " << next << " was SKIPPED!" << std::endl;
next = (game->total_players + next + game->direction) % game->total_players;
game->skip_next = false;
}
if (game->draw_penalty > 0)
{
std::cout << "[Scheduler] Player " << next << " must draw " << game->draw_penalty << " cards!" << std::endl;
for (int k = 0; k < game->draw_penalty; k++)
{
GameRules::drawCard(game, next);
}
game->draw_penalty = 0;
}
game->current_player_id = next;
game->turn_completed = false;
pthread_cond_broadcast(&game->turn_cond);
pthread_mutex_unlock(&game->mutex);
}
return NULL;
}
//==============================================================================
// CLIENT HANDLER
//==============================================================================
void handle_client_real(SharedGameState *game, int my_id, int socket_fd)
{
char buffer[256];
// Wait for all players to connect
pthread_mutex_lock(&game->mutex);
game->connected_count++;
// Send welcome message
std::string welcome = "Welcome Player " + std::to_string(my_id) + "! Waiting for other players...\n";
send(socket_fd, welcome.c_str(), welcome.length(), 0);
while (game->connected_count < game->total_players)
{
pthread_cond_wait(&game->turn_cond, &game->mutex);
}
pthread_cond_broadcast(&game->turn_cond); // Wake up others when we reach full count
pthread_mutex_unlock(&game->mutex);
while (game->game_running)
{
pthread_mutex_lock(&game->mutex);
// Wait if it's not my turn OR if I just finished my turn (waiting for scheduler)
while ((game->current_player_id != my_id || game->turn_completed) && game->game_running)
{
// Notify waiting player about status
int current = game->current_player_id;
bool processing = game->turn_completed;
// Unlock to perform I/O (send) to avoid holding lock during network op
pthread_mutex_unlock(&game->mutex);
std::string status;
if (processing) {
status = "Waiting for server to process turn...\n";
} else {
status = "Waiting for Player " + std::to_string(current) + " to play...\n";
}
send(socket_fd, status.c_str(), status.length(), 0);
// Re-acquire lock to check condition again and wait
pthread_mutex_lock(&game->mutex);
// Check condition again before waiting
if ((game->current_player_id != my_id || game->turn_completed) && game->game_running) {
pthread_cond_wait(&game->turn_cond, &game->mutex);
}
}
if (!game->game_running)
{
pthread_mutex_unlock(&game->mutex);
break;
}
std::string msg = "\n=== UNO GAME ===\n";
msg += "Top Card: [" + std::string(1, game->discard_pile_top.color) +
std::to_string(game->discard_pile_top.value) + "]\n";
msg += "Your Hand:\n";
for (int i = 0; i < game->hand_counts[my_id]; i++)
{
Card c = game->player_hands[my_id][i];
msg += std::to_string(i) + ": [" + c.color + std::to_string(c.value) + "] ";
}
msg += "\nActions: Enter index (0-N) to play, or -1 to DRAW card.\n> ";
send(socket_fd, msg.c_str(), msg.length(), 0);
pthread_mutex_unlock(&game->mutex);
memset(buffer, 0, sizeof(buffer));
int bytes = recv(socket_fd, buffer, sizeof(buffer) - 1, 0);
if (bytes <= 0)
{
break;
}
int choice = atoi(buffer);
pthread_mutex_lock(&game->mutex);
if (game->current_player_id == my_id && game->game_running)
{
if (choice == -1)
{
GameRules::drawCard(game, my_id);
send(socket_fd, "You drew a card.\n", 17, 0);
game->turn_completed = true;
}
else if (GameRules::isValidMove(game, my_id, choice))
{
// Check if it's a Wild card (W13 or W14)
Card card = game->player_hands[my_id][choice];
if (card.color == 'W' && (card.value == 13 || card.value == 14))
{
// Prompt for color declaration
send(socket_fd, "\nWild Card Played! Declare a color: R(Red), G(Green), B(Blue), Y(Yellow)\n> ", 79, 0);
pthread_mutex_unlock(&game->mutex);
memset(buffer, 0, sizeof(buffer));
int color_bytes = recv(socket_fd, buffer, sizeof(buffer) - 1, 0);
if (color_bytes <= 0)
{
close(socket_fd);
return;
}
char declared_color = '\0';
char *color_str = buffer;
while (*color_str && isspace(*color_str)) color_str++;
if (*color_str == 'R' || *color_str == 'r') declared_color = 'R';
else if (*color_str == 'G' || *color_str == 'g') declared_color = 'G';
else if (*color_str == 'B' || *color_str == 'b') declared_color = 'B';
else if (*color_str == 'Y' || *color_str == 'y') declared_color = 'Y';
if (declared_color == '\0')
{
send(socket_fd, "Invalid color! Turn skipped.\n", 29, 0);
pthread_mutex_lock(&game->mutex);
game->turn_completed = true;
pthread_cond_broadcast(&game->turn_cond);
pthread_mutex_unlock(&game->mutex);
continue;
}
pthread_mutex_lock(&game->mutex);
GameRules::playCard(game, my_id, choice, declared_color);
std::string wild_msg = "Wild Card Played! Color declared: " + std::string(1, declared_color) + "\n";
send(socket_fd, wild_msg.c_str(), wild_msg.length(), 0);
}
else
{
GameRules::playCard(game, my_id, choice);
send(socket_fd, "Card Played!\n", 13, 0);
}
if (game->hand_counts[my_id] == 1)
{
send(socket_fd, "UNO!!\n", 6, 0);
}
}
else
{
send(socket_fd, "Invalid Move! Try again (turn skipped for simplicity).\n", 55, 0);
game->turn_completed = true;
}
pthread_cond_broadcast(&game->turn_cond);
}
pthread_mutex_unlock(&game->mutex);
}
pthread_mutex_lock(&game->mutex);
game->is_active[my_id] = false;
// [NEW] Winner notification
if (game->winner_id != -1)
{
std::string win_msg;
if (game->winner_id == my_id)
{
win_msg = "\n***********************************\n";
win_msg += "* CONGRATULATIONS! YOU WON! 🏆 *\n";
win_msg += "***********************************\n";
}
else
{
win_msg = "\n===================================\n";
win_msg += " GAME OVER! Player " + std::to_string(game->winner_id) + " Wins! \n";
win_msg += "===================================\n";
}
send(socket_fd, win_msg.c_str(), win_msg.length(), 0);
}
pthread_mutex_unlock(&game->mutex);
// Allow small delay for message to reach client before closing
sleep(1);
close(socket_fd);
}
//==============================================================================
// SHARED MEMORY MANAGEMENT
//==============================================================================
SharedGameState *global_game_ptr = NULL;
// Initialize shared memory
SharedGameState *initSharedMemory()
{
shm_unlink(SHM_NAME);
int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) { perror("shm_open"); exit(1); }
if (ftruncate(shm_fd, sizeof(SharedGameState)) == -1) { perror("ftruncate"); exit(1); }
SharedGameState *game = (SharedGameState *)mmap(NULL, sizeof(SharedGameState), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (game == MAP_FAILED) { perror("mmap"); exit(1); }
close(shm_fd);
return game;
}
void cleanupSharedMemory(SharedGameState *game)
{
if (game) {
munmap(game, sizeof(SharedGameState));
shm_unlink(SHM_NAME);
}
}
void initializeMutexesInSharedMemory(SharedGameState *game)
{
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
pthread_condattr_t cond_attr;
pthread_condattr_init(&cond_attr);
pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&game->mutex, &mutex_attr);
pthread_cond_init(&game->turn_cond, &cond_attr);
pthread_mutexattr_destroy(&mutex_attr);
pthread_condattr_destroy(&cond_attr);
}
//==============================================================================
// SCORE MANAGEMENT
//==============================================================================
void loadScores(SharedGameState *game)
{
std::ifstream infile(SCORES_FILE);
if (infile.is_open()) {
for (int i = 0; i < MAX_PLAYERS; i++) {
if (!(infile >> game->scores[i])) {
game->scores[i] = 0;
}
}
infile.close();
GameLogger::logEvent("Scores loaded from " SCORES_FILE);
} else {
GameLogger::logEvent("No scores file found. Starting with 0 scores.");
for (int i = 0; i < MAX_PLAYERS; i++) game->scores[i] = 0;
}
}
void saveScores(SharedGameState *game)
{
if (!game) return;
std::ofstream outfile(SCORES_FILE);
if (outfile.is_open()) {
for (int i = 0; i < MAX_PLAYERS; i++) {
outfile << game->scores[i] << (i == MAX_PLAYERS - 1 ? "" : "\n");
}
outfile.close();
GameLogger::logEvent("Scores saved to " SCORES_FILE);
} else {
std::cerr << "Failed to save scores to " << SCORES_FILE << std::endl;
}
}
//==============================================================================
// SIGNAL HANDLER
//==============================================================================
void signalHandler(int signum)
{
std::cout << "\nInterrupt signal (" << signum << ") received.\n";
if (global_game_ptr) {
saveScores(global_game_ptr);
cleanupSharedMemory(global_game_ptr);
}
GameLogger::stopLogger();
exit(signum);
}
//==============================================================================
// MAIN FUNCTION
//==============================================================================
int main(int argc, char *argv[])
{
int num_players = 3;
if (argc > 1) {
num_players = atoi(argv[1]);
if (num_players < 3 || num_players > MAX_PLAYERS) {
std::cerr << "Number of players must be between 3 and " << MAX_PLAYERS << std::endl;
return 1;
}
}
signal(SIGINT, signalHandler);
signal(SIGPIPE, SIG_IGN);
GameLogger::initLogger();
GameLogger::logEvent("=== UNO Game Server Started ===");
SharedGameState *game = initSharedMemory();
global_game_ptr = game;
memset(game, 0, sizeof(SharedGameState));
loadScores(game);
initializeMutexesInSharedMemory(game);
game->total_players = num_players;
game->connected_count = 0;
GameRules::initGame(game);
for(int i=0; i<num_players; i++) game->is_active[i] = true;
int server_fd;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, num_players) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
GameLogger::logEvent("Server listening on port " + std::to_string(PORT));
std::cout << "Waiting for " << num_players << " players to connect..." << std::endl;
pthread_t scheduler_tid;
pthread_create(&scheduler_tid, NULL, round_robin_scheduler, (void *)game);
GameLogger::logEvent("Scheduler thread started");
pid_t child_pids[MAX_PLAYERS];
int joined_players = 0;
while (joined_players < num_players)
{
int new_socket;
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
continue;
}
GameLogger::logEvent("Connection accepted", joined_players);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
close(new_socket);
} else if (pid == 0) {
// Child process
close(server_fd); // Child doesn't need listener
GameLogger::logEvent("Player process started for Player " + std::to_string(joined_players));
handle_client_real(game, joined_players, new_socket);
close(new_socket);
exit(0);
} else {
// Parent process
child_pids[joined_players] = pid;
close(new_socket); // Parent doesn't need client socket
joined_players++;
}
}
// Wait for all children
for (int i = 0; i < num_players; i++) {
waitpid(child_pids[i], NULL, 0);
}
GameLogger::logEvent("Game finished. Saving scores...");
saveScores(game); // Save scores after game
pthread_cancel(scheduler_tid);
pthread_join(scheduler_tid, NULL);
cleanupSharedMemory(game);
GameLogger::stopLogger();
return 0;
}