OpenMPI学习笔记(五)之乒乓球比赛模拟(一)

目标

模拟乒乓球比赛, 游戏规则:双方来回击球,直至一方出错,对方获得一份;当双方中 一方的比分达到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;
}

结果截图:

result

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值