目标
模拟乒乓球比赛, 游戏规则:双方来回击球,直至一方出错,对方获得一份;当双方中 一方的比分达到11分,比赛结束。(注:没有追加赛,没有晋级赛。)
比如甲乙两人成绩如下
1 0
2 0
3 0
4 0
4 1
4 2
4 3
5 3
6 3
6 4
6 5
7 5
8 5
9 5
10 5
10 6
11 6于是我们就说甲赢得了比赛。
代码部分:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int point(int wRank)
{
while (1)
{
if (wRank==0)
{
int shot = rand()%16;
MPI_Ssend(&shot, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
if (shot==0)
return 1;
else
MPI_Recv(&shot, 1, MPI_INT, 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (shot==0)
return 0;
}
else
{
int shot;
MPI_Recv(&shot, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (shot==0)
return 1;
else
{
shot = rand()%16;
MPI_Ssend(&shot, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
if (shot==0)
return 0;
}
}
}
void set(int wRank)
{
int score[2] = {0, 0};
while (score[0]!=11 && score[1]!=11)
{
++score[point(wRank)];
if (wRank==0)
printf("%d-%d\n", score[0], score[1]);
}
if(wRank == 0)
if(score[0]==11)
printf("the man a who stands for process 0 win the game!\n");
else
printf("the man b who stands for process 1 win the game!\n");
}
int main()
{
MPI_Init(NULL, NULL);
int wRank, wSize;
MPI_Comm_rank(MPI_COMM_WORLD, &wRank);
MPI_Comm_size(MPI_COMM_WORLD, &wSize);
if (wSize!=2)
{
MPI_Finalize();
return 0;
}
srand(time(NULL) + wRank);
set(wRank);
MPI_Finalize();
return 0;
}