C++第三章课本例题

游戏规则是:每个骰子有6面,点数分别为1、2、3、4、5、6。游戏者在程序开始时输入个无符号整数,作为产生随机数的种子。每轮投两次骰子,第一轮如果和数为7或11则为胜,游戏结束;和数为2、3或12则为负,游戏结束;和数为其他值则将此值作为自己的原数,继续第二轮、第三轮……直到某轮的和数等于点数则取胜,若在此前出现和数为7则为负。

复制代码
#include <iostream>
#include <cstdlib>
using namespace std;
int rolldice(){                       //投骰子,计算合数,输出合数 
    int die1=1+rand()%6;
    int die2=1+rand()%6;
    int sum=die1+die2;
    cout<<"player rolled"<<die1<<"+"<<die2<<"="<<sum<<endl;
    return sum;
} 
enum GameStatus {WIN,LOSE,PLAYING};  
int main()
{
    int sum,mypoint;
    GameStatus status;
    unsigned seed;
    cin>>seed;                       //输入随机种子数 
    srand(seed);                       //将种子传递给rand函数 
    sum=rolldice();//第一轮投色子,计算和树 
    switch(sum){
        case 7:
        case 11:
            status=WIN;//如果合数为7,11则获胜,状态为win 
            break;
        case 2:
        case 3:
        case 12:
            status=LOSE;//如果合数为2,3,12,则输,状态为lose 
            break;
        default:
            status=PLAYING;//其他情况,游戏无结果,状态为playing,记下点数,为下一轮做准备 
            mypoint=sum;
            cout<<"point is"<<mypoint<<endl;
            break;
    } 
    while(status==PLAYING){//只要状态为playing,仍然继续 
        sum=rolldice();
        if(sum==mypoint)
        status=WIN;//合数等于点数的话获胜 
        else if(sum==7)
        status=LOSE;//合数等于7的话失败 
    }
    if(status==WIN)//状态不为playing,上面循环结束,以下程序输出结果 
    {
        cout<<"player win"<<endl;
    }
    else
    {
        cout<<"player lose"<<endl;
    }
}
复制代码

 

posted @   新晋软工小白  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示