投骰子的随机游戏

来源:互联网 发布:ios手游模拟器 mac 编辑:程序博客网 时间:2024/05/24 06:22

每个骰子有六面,点数分别为1、2、3、4、5、6。游戏者在程序开始时输入一个无符号整数,作为产生随机数的种子。

每轮投两次骰子,第一轮如果和数为7或11则为胜,游戏结束;和数为2、3或12则为负,游戏结束;和数为其它值则将此值作为自己的点数,继续第二轮、第三轮…直到某轮的和数等于点数则取胜,若在此前出现和数为7则为负。

#include <iostream>#include <cstdlib>enum GameStatus{WIN,LOSE,PLAYING};//计算并输出和数int rollDice(){    int die1 = 1 + rand() % 6;    int die2 = 1 + rand() % 6;    int sum = die1 + die2;    printf("player rolled %d + %d = %d\n", die1, die2, sum);    return sum;}int main(){    int sum, myPoint;    GameStatus status;    unsigned seed;    //int rollDice();    scanf_s("%d", &seed);//输入随机数种子    srand(seed);//将种子传递给rand()    sum = rollDice();//第一轮投色子、计算和数    switch (sum){    case 7:    case 11:        status = WIN;        break;//和为7或11则为胜    case 2:    case 3:    case 12:        status = LOSE;        break;    default://其他情况尚无结果,状态为PLAYING        status = PLAYING;        myPoint = sum;        printf("point is %d\n", myPoint);        break;    }    while (status == PLAYING){        sum = rollDice();        if (sum == myPoint){            status = WIN;        }        else if (sum == 7){            status = LOSE;        }    }    //当状态不为PLAYING时循环结束,输出游戏结果    if (status == WIN){        printf("win!\n");    }    else{        printf("lose!\n");    }    system("pause");    return 0;}
2 0