C/C++ rand()产生随机数 模拟 掷骰子 小游戏代码

1、源代码如下:

/*! @file
********************************************************************************
模块名 :
文件名 : tossGame.cpp
相关文件 :
文件实现功能 : 模拟掷骰子的随即过程,同时掷出2个骰子,如果结果和为7或者11则玩家获胜,
如果结果为2则玩家失败;其他结果可以按回车继续,或者输入q结束程序。
作者 : QuNengrong (Qunero)
公司 :
版本 : 1.0
新版 :
--------------------------------------------------------------------------------
多线程安全性 :
异常时安全性 :
--------------------------------------------------------------------------------
备注 :
--------------------------------------------------------------------------------
修改记录 :
日 期 版本 修改人 修改内容
10/08/2011 1.0 QuNengrong 创建
********************************************************************************

* 版权所有(c) 2011, 保留所有权利

******************************************************************************
*/


#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cstdio>

int main(){
using namespace std;
cout << "Note: press RETURN to play, if you get 7 or 11 you win, if you get 2 you lose\n"
" Or you can input q to quit the game!" << endl;
char ch;
int a,b;
srand(time(0));
ch=getchar();
while(ch != 'q'){
a = random() % 6;
if( a==0 ) a=6;
b = random() % 6;
if(b == 0) b=6;
switch(a+b){
case 7:
case 11:
cout << "You get " << a+b;
cout << ", and You Win!\n";
return 0;
case 2:
cout << "You get " << 2;
cout << ", You lose!\n";
return 0;
default:
cout << "You get " << a+b;
cout << " Press return to go on\n";
}
ch=getchar();
}
}

2、运行效果如下:

$ ./tossGame 
Note: press RETURN to play, if you get 7 or 11 you win, if you get 2 you lose
Or you can input q to quit the game!

You get 5 Press return to go on

You get 6 Press return to go on

You get 8 Press return to go on

You get 9 Press return to go on

You get 4 Press return to go on

You get 6 Press return to go on

You get 7, and You Win!

3、原文参考:

http://qubuntu.blog.163.com/blog/static/195703121201192563112516/ 

可惜网易blog对代码支持的不好啊,代码全乱了~~

转载于:https://www.cnblogs.com/QuLory/archive/2011/10/26/linux_C_CPP_funny_random_toss_game.html

猜你喜欢

转载自blog.csdn.net/weixin_34192732/article/details/93154336