我必须开发一种C语言的迷你纸牌游戏(Go Fish),它有以下要求 1. 2-8个孩子的球员 2.每个孩子都必须通过二维管道与父母沟通。
我现在的进步是,我已经为每个孩子完成了孩子的创作和二维管道的设置,然而,当我开始处理交易卡过程时,出现了一些问题,我试了很久才想出来。不幸的是,我失败很多次,我想在这里问。
问题1:在交易过程中,父母将向孩子发放7张牌,每个孩子都需要接收这些牌并存入他们自己的牌组(这是一个字符串数组)。但是,我的输出显示字符串数组变为7等于不期望的卡。Output :All equal cards in the deck
问题2:如何使用动态字符串数组来存储卡片信息。因为在比赛期间,每个玩家可能有超过7张牌。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int seed;
void initrand(int myid){
seed = myid;
}
int myrand(){
return (seed++ % 99)+1;
}
int main(int argc, char *argv[]){
int pid, myid ,parentid, cid, seed, who, rank, cpp;//cpp = card per person
//Total number of argument
int num_arg = (argc-1);
int i,j,TotalchildNo,RemainchildNo,childNo;
//The total number of child process
TotalchildNo = RemainchildNo = atoi(argv[1]);
//<Pipes>
int parent_to_child[2*TotalchildNo];
int child_to_parent[2*TotalchildNo];
//</Pipes>
char writebuf[80], readbuf[80];
//For 2-4 players
if(TotalchildNo>=2||TotalchildNo<=4) cpp=7;
//For 4-8 players
else if (TotalchildNo>=4||TotalchildNo<=8) cpp=5;
//Creating Pipe
for (int i = 0; i < TotalchildNo; i++) {
pipe(&parent_to_child[2*i]);
pipe(&child_to_parent[2*i]);
}
//Creating child
for(i=0;i<TotalchildNo;i++){
childNo = i;
pid = fork();
if(pid){
continue;
} else if (pid==0){
break;
} else {
printf("fork error\n");
exit(1);
}
}
if(pid==0){ //Child process
//printf("%d Child: %d\n",getpid(),childNo);
//Pipe setup
close(parent_to_child[2*childNo+1]);
close(child_to_parent[2*childNo]);
char *cards[30];
int numOfCards=0;
const char s[2] = " ";
for(i=0;i<cpp;i++){
//printf("Child %d listening to parent.\n",childNo);
read(parent_to_child[2*childNo],readbuf,80);
cards[i]=readbuf;
printf("Card %d: %s %s\n",i+1,readbuf, cards[i]);
}
printf("\n");
printf("%s %s %s %s %s %s %s \n",cards[0],cards[1],cards[2],cards[3],cards[4],cards[5],cards[6]);
//exit(0);
}else
{// Parent process
//Pipe setup (Close for every child invalid pipe)
for (int i = 0; i < TotalchildNo; i++) {
close(parent_to_child[2*i]);
close(child_to_parent[2*i+1]);
}
//Initialize the deck of the parent
char card[4];
//Dealt card according to numbers of the players
for(i=0;i<cpp;i++){
for(j=0;j<TotalchildNo;j++){
//Send on card to specific player
fgets(card, sizeof card , stdin);
strcpy(writebuf,card);
write(parent_to_child[2*j+1],writebuf,80);
}
}
while(RemainchildNo>0){
cid = wait(NULL);
printf("Child %d has returned!\n",RemainchildNo);
--RemainchildNo;
}
}
}
英语不是我的母语,如果您认为我的解释不够明确,我会感到非常抱歉。