Untitled
unknown
c_cpp
4 years ago
2.3 kB
18
Indexable
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
char *optionToString(char option){
switch(option){
case '0':
return "Papel";
break;
case '1':
return "Piedra";
break;
default:
return "Tijera";
break;
}
}
int whoWin(char P1, char P2){
switch (P1)
{
case '0':
if (P2 == '1')return 1;
else return 2;
break;
case '1':
if (P2 == '0')return 1;
else return 2;
break;
default:
if (P2 == '0')return 1;
else return 2;
}
}
char randomNumInChar(){
int num = rand()%3;
char out = '0' + num;
return out;
}
int main(){
pid_t child1 = -1,child2=-1;
int pipe1[2],pipe2[2];
char inputP1[300],inputP2[300];
srand(time(NULL));
char continueGame = 'x';
pipe(pipe1);
pipe(pipe2);
while (continueGame != 'n'){
if (child1 == -1){
child1 = fork();
if (child1 == 0){
close(pipe1[0]);
while(1){
char val = randomNumInChar();
char *value = &val;
write(pipe1[1], value, strlen(value)+1);
sleep(20);
}
}
}
if (child2 == -1){
child2 = fork();
if (child2 == 0){
close(pipe2[0]);
while(1){
char val = randomNumInChar();
char *value = &val;
write(pipe2[1], value , strlen(value)+1);
sleep(20);
}
}
}
printf("Antes de ver el ganador, desea realizar un nuevo juego? Para terminar presione n, para continuar presione cualquier tecla:");
scanf("%c", &continueGame);
if (child1 > 0 && child2 > 0){
close(pipe1[1]);
close(pipe2[1]);
read(pipe1[0], inputP1, 300);
read(pipe2[0], inputP2, 300);
if (inputP1[0] == inputP2[0]){
printf("Ambos jugadores escogieron %s, ambos mueren \n.",optionToString(inputP1[0]));
kill(child1, SIGKILL);
kill(child2, SIGKILL);
child1 = -1;
child2 = -1;
}
if (whoWin(inputP1[0], inputP2[0]) == 1){
printf("El ganador es el jugador 1, escogió %s mientras que el jugador 2 escogió %s \n", optionToString(inputP1[0]), optionToString(inputP2[0]));
kill(child2, SIGKILL);
child2 = -1;
}
else {
printf("El ganador es el jugador 1, escogió %s mientras que el jugador 2 escogió %s \n", optionToString(inputP1[0]), optionToString(inputP2[0]));
kill(child1, SIGKILL);
child1 = -1;
}
}
}
}Editor is loading...