Elaborato_SO/src/F4Server.c

110 lines
2.5 KiB
C

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <server.h>
#include <structures.h>
#include <custom_sem.h>
#include <custom_shm.h>
#include <errExit.h>
#include <forza4.h>
#include <custom_msgq.h>
#include <custom_sig.h>
int bot = 0;
void waitPlayer(char name[2][MAX_NAME]) {
player_ds player;
semOp(_SEMID, SERVER, -1);
// ricevo nome primo client
rcvPlayer(&player);
strcpy(name[player.id], player.name_player);
_PIDS[player.id] = player.pid;
if (player.bot) {
bot = 1;
}
printf(PSERVER "Player %s connected\n", name[player.id]);
}
int main(int argc, char *argv[]) {
setupServer(argc, argv);
// aperta semaforo per connessione dei due client
printf(PSERVER "Waiting for players...\n");
semOp(_SEMID, CLIENT0, 1);
semOp(_SEMID, CLIENT1, 1);
char name[2][MAX_NAME];
// aspetto PRIMO client
waitPlayer(name);
if (bot) {
int child = fork();
if (child == 0) {
printf(PSERVER "Creating bot\n");
execl("./bin/F4Client", "./bin/F4Client", "Bot", "auto", (char *)NULL);
}
}
// aspetto SECONDO client
waitPlayer(name);
// avviso inizio partita
semOp(_SEMID, CLIENT0, 1);
semOp(_SEMID, CLIENT1, 1);
// PARTITA
printf(PSERVER "Starting game\n");
int turns_left = _INPUT_S.rows * _INPUT_S.collums;
tile_t result = -1;
move_t move;
do {
// apro semaforo al player di turno
semOp(_SEMID, turn, 1);
alarm(TIME_TO_MOVE);
printf(PSERVER "%s's turn\n", name[turn]);
// aspetto che mi mandi una mossa
rcvMove(&move);
alarm(0);
insertMove(move.move, turn);
// info
printf("move: %d\n", move.move);
printf("turns left: %d\n", turns_left - 1);
// dico al player che la mossa è stata effettuata per fargli stampare il campo
semOp(_SEMID, turn, 1);
// next turn
turn ^= 1;
} while (--turns_left && (result = checkWin(move.move)) == -1);
printf("result: %d\n", result);
if (result == -1) {
printf(PSERVER "Game ended in a draw\n");
} else {
printf(PSERVER "%s won\n", name[result]);
}
printf("winner %d\n", result);
end_game(result);
}