双骰子(Craps)C/C++实现

C/C++ 2014年08月13日

双骰子(Craps)是一个流行过的游戏,今天使用C/C++来实现。

双骰子(Craps)规则

玩家掷两个骰子。如果首次投掷的点数和是7或者11,那么玩家赢;如果首次投掷的点数和是2、3或者12(称为craps),那么玩家输;如果首次投掷不是上述点数,记这个点数为玩家“点数”。玩家必须连续掷骰子,直到掷出相同点数。如果在得到点数前,掷到7,那么玩家输。

C/C++来实现双骰子(Craps)

/**
 * @file	craps.cpp
 * @brief	craps game
 * @details	craps game. http://en.wikipedia.org/wiki/Craps
 * @author	http://furzoom.com
 * @version     1.0
 * @date	2014-08
 * @history
 */
#include <iostream>
using std::cout;
using std::endl;

#include <cstdlib>
using std::rand;
using std::srand;

#include <ctime>
using std::time;

// rolls dice, calculates and displays sum
int rollDice(void);

int main()
{
	// enumeration with constants that represent the game status
	enum Status{CONTINUE, WON, LOST};
	int myPoint;
	Status gameStatus;

	//randomize random number generator using current time
	srand(time(0));
	int sumOfDice = rollDice();//first roll of the dice
	switch(sumOfDice)
	{
		case 7:
		case 11:
			gameStatus = WON;
			break;
		case 2:
		case 3:
		case 12:
			gameStatus = LOST;
			break;
		default:
			gameStatus = CONTINUE;
			myPoint = sumOfDice;
			cout<<"Point is "<<myPoint<<endl;
	}

	//while the game is not complete
	while(gameStatus == CONTINUE)
	{
		sumOfDice = rollDice();
		if(sumOfDice == myPoint)
		{
			gameStatus = WON;
		}
		else
			if(sumOfDice == 7)
			{
				gameStatus = LOST;
			}
	}
	if(gameStatus == WON)
	{
		cout<<"Player wins"<<endl;
	}
	else
	{
		cout<<"Player loses"<<endl;
	}
	return 0;
}
// roll dice http://furzoom.com/craps/
int rollDice(void)
{
	// pick random die values
	int die1 = 1 + rand() % 6;
	int die2 = 1 + rand() % 6;

	int sum = die1 + die2;

	//display results of this roll
	cout<<"Player rolled "<<die1<<" + "<<die2<<" = "<<sum<<endl;
	return sum;
}

运行结果如下:

craps

furzoom在这里只是实现了基本功能,还有很多可以完善的地方,如增加搬运投掷功能,增加界面等。

如无特别说明,本站文章皆为原创,若要转载,务必请注明以下原文信息:
日志标题:《双骰子(Craps)C/C++实现》
日志链接:http://furzoom.com/craps/
博客名称:枫竹梦

发表评论

插入图片

NOTICE1:请申请gravatar头像,没有头像的评论可能不会被回复!

回到顶部